answer
stringlengths
17
10.2M
package technology.tabula.detectors; import org.apache.pdfbox.pdfparser.PDFStreamParser; import org.apache.pdfbox.pdfwriter.ContentStreamWriter; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDStream; import org.apache.pdfbox.util.ImageIOUtil; import org.apache.pdfbox.util.PDFOperator; import technology.tabula.*; import technology.tabula.Rectangle; import technology.tabula.extractors.BasicExtractionAlgorithm; import java.awt.*; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.awt.image.Raster; import java.io.File; import java.io.IOException; import java.util.*; import java.util.List; public class NurminenDetectionAlgorithm implements DetectionAlgorithm { private static final int GRAYSCALE_INTENSITY_THRESHOLD = 25; private static final float TABLE_PADDING_AMOUNT = 1.0f; private static final Comparator<Point2D.Float> pointComparator = new Comparator<Point2D.Float>() { @Override public int compare(Point2D.Float o1, Point2D.Float o2) { if (o1.equals(o2)) { return 0; } if (o1.getY() == o2.getY()) { return Double.compare(o1.getX(), o2.getX()); } else { return Double.compare(o1.getY(), o2.getY()); } } }; BufferedImage debugImage; String debugFileOut; @Override public List<Rectangle> detect(Page page, File referenceDocument) { // open a PDDocument to read stuff in PDDocument pdfDocument; try { pdfDocument = PDDocument.load(referenceDocument); } catch (Exception e) { return new ArrayList<Rectangle>(); } // get the page in question PDPage pdfPage = (PDPage) pdfDocument.getDocumentCatalog().getAllPages().get(page.getPageNumber() - 1); // debugging stuff - spit out an image with what we want to see debugFileOut = referenceDocument.getAbsolutePath().replace(".pdf", "-" + page.getPageNumber() + ".jpg"); BufferedImage image; try { image = pdfPage.convertToImage(BufferedImage.TYPE_BYTE_GRAY, 144); debugImage = pdfPage.convertToImage(BufferedImage.TYPE_INT_RGB, 72); } catch (IOException e) { return new ArrayList<Rectangle>(); } List<Line2D.Float> horizontalRulings = this.getHorizontalRulings(image); // now check the page for vertical lines, but remove the text first to make things less confusing try { this.removeText(pdfDocument, pdfPage); image = pdfPage.convertToImage(BufferedImage.TYPE_BYTE_GRAY, 144); } catch (Exception e) { return new ArrayList<Rectangle>(); } List<Line2D.Float> verticalRulings = this.getVerticalRulings(image); List<Line2D.Float> allEdges = new ArrayList<Line2D.Float>(horizontalRulings); allEdges.addAll(verticalRulings); List<Rectangle> tableAreas = new ArrayList<Rectangle>(); List<Rectangle> cells = null; Set<Point2D.Float> crossingPoints = null; // if we found some edges, try to find some tables based on them if (allEdges.size() > 0) { // now we need to snap edge endpoints to a grid Utils.snapPoints(allEdges, 8f, 8f); // next get the crossing points of all the edges crossingPoints = this.getCrossingPoints(horizontalRulings, verticalRulings); // merge the edge lines into rulings - this makes finding edges between crossing points in the next step easier horizontalRulings = this.mergeHorizontalEdges(horizontalRulings); verticalRulings = this.mergeVerticalEdges(verticalRulings); // use the rulings and points to find cells cells = this.findRectangles(crossingPoints, horizontalRulings, verticalRulings); // then use those cells to make table areas tableAreas = this.getTableAreasFromCells(cells); } // now find text alignments in the document List<TextChunk> textChunks = TextElement.mergeWords(page.getText()); List<Line> lines = TextChunk.groupByLines(textChunks); List<Line2D.Float> leftTextEdges = new ArrayList<Line2D.Float>(); List<Line2D.Float> midTextEdges = new ArrayList<Line2D.Float>(); List<Line2D.Float> rightTextEdges = new ArrayList<Line2D.Float>(); Map<Integer, List<TextChunk>> currLeftEdges = new HashMap<Integer, List<TextChunk>>(); Map<Integer, List<TextChunk>> currMidEdges = new HashMap<Integer, List<TextChunk>>(); Map<Integer, List<TextChunk>> currRightEdges = new HashMap<Integer, List<TextChunk>>(); for (Line textRow : lines) { for (TextChunk text : textRow.getTextElements()) { Integer left = new Integer((int)Math.floor(text.getLeft())); Integer right = new Integer((int)Math.floor(text.getRight())); Integer mid = new Integer(left + ((right - left)/2)); // first put this chunk into any edge buckets it belongs to List<TextChunk> leftEdge = currLeftEdges.getOrDefault(left, new ArrayList<TextChunk>()); leftEdge.add(text); currLeftEdges.put(left, leftEdge); List<TextChunk> midEdge = currMidEdges.getOrDefault(mid, new ArrayList<TextChunk>()); midEdge.add(text); currMidEdges.put(mid, midEdge); List<TextChunk> rightEdge = currRightEdges.getOrDefault(right, new ArrayList<TextChunk>()); rightEdge.add(text); currRightEdges.put(right, rightEdge); // now see if this text chunk blows up any other edges for (Iterator<Map.Entry<Integer, List<TextChunk>>> iterator = currLeftEdges.entrySet().iterator(); iterator.hasNext();) { Map.Entry<Integer, List<TextChunk>> entry = iterator.next(); Integer key = entry.getKey(); if (key > left && key < right) { iterator.remove(); List<TextChunk> edgeChunks = entry.getValue(); if (edgeChunks.size() >= 4) { TextChunk first = edgeChunks.get(0); TextChunk last = edgeChunks.get(edgeChunks.size() - 1); leftTextEdges.add(new Line2D.Float(key, first.getTop(), key, last.getBottom())); } } } for (Iterator<Map.Entry<Integer, List<TextChunk>>> iterator = currMidEdges.entrySet().iterator(); iterator.hasNext();) { Map.Entry<Integer, List<TextChunk>> entry = iterator.next(); Integer key = entry.getKey(); if (key > left && key < right && Math.abs(key - mid) > 2) { iterator.remove(); List<TextChunk> edgeChunks = entry.getValue(); if (edgeChunks.size() >= 4) { TextChunk first = edgeChunks.get(0); TextChunk last = edgeChunks.get(edgeChunks.size() - 1); midTextEdges.add(new Line2D.Float(key, first.getTop(), key, last.getBottom())); } } } for (Iterator<Map.Entry<Integer, List<TextChunk>>> iterator = currRightEdges.entrySet().iterator(); iterator.hasNext();) { Map.Entry<Integer, List<TextChunk>> entry = iterator.next(); Integer key = entry.getKey(); if (key > left && key < right) { iterator.remove(); List<TextChunk> edgeChunks = entry.getValue(); if (edgeChunks.size() >= 4) { TextChunk first = edgeChunks.get(0); TextChunk last = edgeChunks.get(edgeChunks.size() - 1); rightTextEdges.add(new Line2D.Float(key, first.getTop(), key, last.getBottom())); } } } } } // add the leftovers for (Integer key : currLeftEdges.keySet()) { List<TextChunk> edgeChunks = currLeftEdges.get(key); if (edgeChunks.size() >= 4) { TextChunk first = edgeChunks.get(0); TextChunk last = edgeChunks.get(edgeChunks.size() - 1); leftTextEdges.add(new Line2D.Float(key, first.getTop(), key, last.getBottom())); } } for (Integer key : currMidEdges.keySet()) { List<TextChunk> edgeChunks = currMidEdges.get(key); if (edgeChunks.size() >= 4) { TextChunk first = edgeChunks.get(0); TextChunk last = edgeChunks.get(edgeChunks.size() - 1); midTextEdges.add(new Line2D.Float(key, first.getTop(), key, last.getBottom())); } } for (Integer key : currRightEdges.keySet()) { List<TextChunk> edgeChunks = currRightEdges.get(key); if (edgeChunks.size() >= 4) { TextChunk first = edgeChunks.get(0); TextChunk last = edgeChunks.get(edgeChunks.size() - 1); rightTextEdges.add(new Line2D.Float(key, first.getTop(), key, last.getBottom())); } } //this.debug(lines); this.debug(leftTextEdges); this.debug(midTextEdges); this.debug(rightTextEdges); // next find any vertical rulings that intersect tables - sometimes these won't have completely been captured as // cells if there are missing horizontal lines (which there often are) // let's assume though that these lines should be part of the table //Map<Line2D.Float, Rectangle> verticalTableRulings = new HashMap<Line2D.Float, Rectangle>(); for (Line2D.Float verticalRuling : verticalRulings) { for (Rectangle tableArea : tableAreas) { if (verticalRuling.intersects(tableArea) && !(tableArea.contains(verticalRuling.getP1()) && tableArea.contains(verticalRuling.getP2()))) { //verticalTableRulings.put(verticalRuling, tableArea); tableArea.setTop((float)Math.floor(Math.min(tableArea.getTop(), verticalRuling.getY1()))); tableArea.setBottom((float)Math.ceil(Math.max(tableArea.getBottom(), verticalRuling.getY2()))); break; } } } // the tabula Page coordinate space is half the size of the PDFBox image coordinate space // so halve the table area size before proceeding and add a bit of padding to make sure we capture everything for (Rectangle area : tableAreas) { area.x = (float)Math.floor(area.x/2) - TABLE_PADDING_AMOUNT; area.y = (float)Math.floor(area.y/2) - TABLE_PADDING_AMOUNT; area.width = (float)Math.ceil(area.width/2) + TABLE_PADDING_AMOUNT; area.height = (float)Math.ceil(area.height/2) + TABLE_PADDING_AMOUNT; } // now look at each text row and see what kind of and how many vertical rulings it intersects // this will help us figure out what text rows should be part of a table // first look for text rows that intersect an existing table - those lines should probably be part of the table for (Line textRow : lines) { for (Rectangle tableArea : tableAreas) { if (!tableArea.contains(textRow) && textRow.intersects(tableArea)) { // expand the table area to contain the rest of the text row tableArea.setLeft((float)Math.floor(Math.min(textRow.getLeft(), tableArea.getLeft()))); tableArea.setRight((float)Math.ceil(Math.max(textRow.getRight(), tableArea.getRight()))); } } } //this.debug(verticalTableRulings.keySet()); // again look for text that intersects one of these rulings and extend the table accordingly /* for (Line textRow : lines) { for (Line2D.Float verticalRuling : verticalTableRulings.keySet()) { if (verticalRuling.intersects(textRow)) { Rectangle tableArea = verticalTableRulings.get(verticalRuling); if (!tableArea.contains(textRow)) { tableArea.setLeft(Math.min(textRow.getLeft(), tableArea.getLeft())); tableArea.setTop(Math.min(textRow.getTop(), tableArea.getTop())); tableArea.setRight(Math.max(textRow.getRight(), tableArea.getRight())); tableArea.setBottom(Math.max(textRow.getBottom(), tableArea.getBottom())); } } } } // then use the text edges as a guide to what rows should be part of tables // first find edges that intersect existing table areas List<Line2D.Float> allTextEdges = new ArrayList<Line2D.Float>(leftTextEdges); allTextEdges.addAll(midTextEdges); allTextEdges.addAll(rightTextEdges); for (Line2D.Float edge : allTextEdges) { for (Rectangle tableArea : tableAreas) { if (!(tableArea.contains(edge.getP1()) && tableArea.contains(edge.getP2())) && edge.intersects(tableArea)) { // ok this line intersects. now find all intersecting text lines that aren't in the table // maybe they should be part of it! // decide based on spacing of rows above and below and whether those rows are part of a table float tableRowHeight = 0f; float tableRowDistance = 0f; Iterator<Line> iterator = lines.iterator(); Line prevRow = iterator.next(); while (prevRow != null && iterator.hasNext()) { Line currRow = iterator.next(); if (tableArea.contains(currRow) && tableArea.contains(prevRow)) { tableRowHeight = currRow.height; tableRowDistance = currRow.getTop() - prevRow.getTop(); } else if (tableArea.contains(prevRow) && !tableArea.contains(currRow) && tableRowDistance > 0 && currRow.intersectsLine(edge)) { float heightDiff = Math.abs(tableRowHeight - currRow.height); float distanceDiff = Math.abs(tableRowDistance - (currRow.getTop() - prevRow.getTop())); if (heightDiff <= 1.0 && distanceDiff <= 1.0) { // let's extend the table down to include this row tableArea.setBottom(currRow.getBottom()); } } prevRow = currRow; } } } } */ // before we return the table areas remove all duplicates Set<Rectangle> tableSet = new TreeSet<Rectangle>(new Comparator<Rectangle>() { @Override public int compare(Rectangle o1, Rectangle o2) { float overlap = o1.overlapRatio(o2); System.out.println("Overlap ratio of " + o1.toString() + " and " + o2.toString() + " is " + overlap); if (overlap >= 0.98) { return 0; } else { return 1; } } }); tableSet.addAll(tableAreas); this.debug(tableSet); return new ArrayList<Rectangle>(tableSet); } private List<Line2D.Float> mergeHorizontalEdges(List<Line2D.Float> horizontalEdges) { if (horizontalEdges.size() == 0) { return horizontalEdges; } List<Line2D.Float> horizontalRulings = new ArrayList<Line2D.Float>(); // sort rulings by top-leftmost first Collections.sort(horizontalEdges, new Comparator<Line2D.Float>() { @Override public int compare(Line2D.Float o1, Line2D.Float o2) { if (o1.equals(o2)) { return 0; } if (o1.y1 == o2.y1) { return Float.compare(o1.x1, o2.x1); } else { return Float.compare(o1.y1, o2.y1); } } }); Line2D.Float currentRuling = horizontalEdges.get(0); for (int i=1; i<horizontalEdges.size(); i++) { Line2D.Float nextEdge = horizontalEdges.get(i); if (currentRuling.y1 == nextEdge.y1 && nextEdge.x1 >= currentRuling.x1 && nextEdge.x1 <= currentRuling.x2) { // this line segment can be part of the current line currentRuling.x2 = Math.max(nextEdge.x2, currentRuling.x2); } else { // store the complete line and continue horizontalRulings.add(currentRuling); currentRuling = nextEdge; } } horizontalRulings.add(currentRuling); return horizontalRulings; } private List<Line2D.Float> mergeVerticalEdges(List<Line2D.Float> verticalEdges) { if (verticalEdges.size() == 0) { return verticalEdges; } List<Line2D.Float> verticalRulings = new ArrayList<Line2D.Float>(); // sort by left-topmost first Collections.sort(verticalEdges, new Comparator<Line2D.Float>() { @Override public int compare(Line2D.Float o1, Line2D.Float o2) { if (o1.equals(o2)) { return 0; } if (o1.x1 == o2.x1) { return Float.compare(o1.y1, o2.y1); } else { return Float.compare(o1.x1, o2.x1); } } }); Line2D.Float currentRuling = verticalEdges.get(0); for (int i=1; i<verticalEdges.size(); i++) { Line2D.Float nextEdge = verticalEdges.get(i); if (currentRuling.x1 == nextEdge.x1 && nextEdge.y1 >= currentRuling.y1 && nextEdge.y1 <= currentRuling.y2) { // line segment is part of the current line currentRuling.y2 = Math.max(nextEdge.y2, currentRuling.y2); } else { // store the complete line and continue verticalRulings.add(currentRuling); currentRuling = nextEdge; } } verticalRulings.add(currentRuling); return verticalRulings; } private void debug(Collection<? extends Shape> shapes) { Color[] COLORS = { new Color(27, 158, 119), new Color(217, 95, 2), new Color(117, 112, 179), new Color(231, 41, 138), new Color(102, 166, 30) }; Graphics2D g = (Graphics2D) debugImage.getGraphics(); g.setStroke(new BasicStroke(2f)); int i = 0; for (Shape s : shapes) { g.setColor(COLORS[(i++) % 5]); g.draw(s); } try { ImageIOUtil.writeImage(debugImage, debugFileOut, 72); } catch (IOException e) { } } private List<Rectangle> getTableAreasFromCells(List<Rectangle> cells) { List<List<Rectangle>> cellGroups = new ArrayList<List<Rectangle>>(); for (Rectangle cell : cells) { boolean addedToGroup = false; cellCheck: for (List<Rectangle> cellGroup : cellGroups) { for (Rectangle groupCell : cellGroup) { Point2D[] groupCellCorners = groupCell.getPoints(); Point2D[] candidateCorners = cell.getPoints(); for (int i=0; i<candidateCorners.length; i++) { for (int j=0; j<groupCellCorners.length; j++) { if (candidateCorners[i].distance(groupCellCorners[j]) < 10) { cellGroup.add(cell); addedToGroup = true; break cellCheck; } } } } } if (!addedToGroup) { ArrayList<Rectangle> cellGroup = new ArrayList<Rectangle>(); cellGroup.add(cell); cellGroups.add(cellGroup); } } // create table areas based on cell group List<Rectangle> tableAreas = new ArrayList<Rectangle>(); for (List<Rectangle> cellGroup : cellGroups) { // less than four cells should not make a table if (cellGroup.size() < 4) { continue; } float top = Float.MAX_VALUE; float left = Float.MAX_VALUE; float bottom = Float.MIN_VALUE; float right = Float.MIN_VALUE; for (Rectangle cell : cellGroup) { if (cell.getTop() < top) top = cell.getTop(); if (cell.getLeft() < left) left = cell.getLeft(); if (cell.getBottom() > bottom) bottom = cell.getBottom(); if (cell.getRight() > right) right = cell.getRight(); } tableAreas.add(new Rectangle(top, left, right - left, bottom - top)); } return tableAreas; } private List<Rectangle> findRectangles( Set<Point2D.Float> crossingPoints, List<Line2D.Float> horizontalEdges, List<Line2D.Float> verticalEdges) { List<Rectangle> foundRectangles = new ArrayList<Rectangle>(); ArrayList<Point2D.Float> sortedPoints = new ArrayList<Point2D.Float>(crossingPoints); // sort all points by y value and then x value - this means that the first element // is always the top-leftmost point Collections.sort(sortedPoints, pointComparator); for (int i=0; i<sortedPoints.size(); i++) { Point2D.Float topLeftPoint = sortedPoints.get(i); ArrayList<Point2D.Float> pointsBelow = new ArrayList<Point2D.Float>(); ArrayList<Point2D.Float> pointsRight = new ArrayList<Point2D.Float>(); for (int j=i+1; j<sortedPoints.size(); j++) { Point2D.Float checkPoint = sortedPoints.get(j); if (topLeftPoint.getX() == checkPoint.getX() && topLeftPoint.getY() < checkPoint.getY()) { pointsBelow.add(checkPoint); } else if (topLeftPoint.getY() == checkPoint.getY() && topLeftPoint.getX() < checkPoint.getX()) { pointsRight.add(checkPoint); } } nextCrossingPoint: for (Point2D.Float belowPoint : pointsBelow) { if (!this.edgeExistsBetween(topLeftPoint, belowPoint, verticalEdges)) { break nextCrossingPoint; } for (Point2D.Float rightPoint : pointsRight) { if (!this.edgeExistsBetween(topLeftPoint, rightPoint, horizontalEdges)) { break nextCrossingPoint; } Point2D.Float bottomRightPoint = new Point2D.Float(rightPoint.x, belowPoint.y); if (sortedPoints.contains(bottomRightPoint) && this.edgeExistsBetween(belowPoint, bottomRightPoint, horizontalEdges) && this.edgeExistsBetween(rightPoint, bottomRightPoint, verticalEdges)) { foundRectangles.add(new Rectangle( topLeftPoint.y, topLeftPoint.x, bottomRightPoint.x - topLeftPoint.x, bottomRightPoint.y - topLeftPoint.y) ); break nextCrossingPoint; } } } } return foundRectangles; } private boolean edgeExistsBetween(Point2D.Float p1, Point2D.Float p2, List<Line2D.Float> edges) { for (Line2D.Float edge : edges) { if (p1.x >= edge.x1 && p1.x <= edge.x2 && p1.y >= edge.y1 && p1.y <= edge.y2 && p2.x >= edge.x1 && p2.x <= edge.x2 && p2.y >= edge.y1 && p2.y <= edge.y2) { return true; } } return false; } private Set<Point2D.Float> getCrossingPoints(List<Line2D.Float> horizontalEdges, List<Line2D.Float> verticalEdges) { Set<Point2D.Float> crossingPoints = new HashSet<Point2D.Float>(); for (Line2D.Float horizontalEdge : horizontalEdges) { for (Line2D.Float verticalEdge : verticalEdges) { if (horizontalEdge.intersectsLine(verticalEdge)) { crossingPoints.add(new Point2D.Float(verticalEdge.x1, horizontalEdge.y1)); } } } return crossingPoints; } private List<Line2D.Float> getHorizontalRulings(BufferedImage image) { ArrayList<Line2D.Float> horizontalRulings = new ArrayList<Line2D.Float>(); Raster r = image.getRaster(); int width = r.getWidth(); int height = r.getHeight(); for (int x=0; x<width; x++) { int[] lastPixel = r.getPixel(x, 0, (int[])null); for (int y=1; y<height-1; y++) { int[] currPixel = r.getPixel(x, y, (int[])null); int diff = Math.abs(currPixel[0] - lastPixel[0]); if (diff > GRAYSCALE_INTENSITY_THRESHOLD) { // we hit what could be a line // don't bother scanning it if we've hit a pixel in the line before boolean alreadyChecked = false; for (Line2D.Float line : horizontalRulings) { if (y == line.getY1() && x >= line.getX1() && x <= line.getX2()) { alreadyChecked = true; break; } } if (alreadyChecked) { lastPixel = currPixel; continue; } int lineX = x + 1; while (lineX < width) { int[] linePixel = r.getPixel(lineX, y, (int[]) null); int[] abovePixel = r.getPixel(lineX, y - 1, (int[]) null); if (Math.abs(linePixel[0] - abovePixel[0]) <= GRAYSCALE_INTENSITY_THRESHOLD || Math.abs(currPixel[0] - linePixel[0]) > GRAYSCALE_INTENSITY_THRESHOLD) { break; } lineX++; } int endX = lineX - 1; int lineWidth = endX - x; if (lineWidth > 100) { horizontalRulings.add(new Line2D.Float(x, y, endX, y)); } } lastPixel = currPixel; } } return horizontalRulings; } private List<Line2D.Float> getVerticalRulings(BufferedImage image) { ArrayList<Line2D.Float> verticalRulings = new ArrayList<Line2D.Float>(); Raster r = image.getRaster(); int width = r.getWidth(); int height = r.getHeight(); for (int y=0; y<height; y++) { int[] lastPixel = r.getPixel(0, y, (int[])null); for (int x=1; x<width-1; x++) { int[] currPixel = r.getPixel(x, y, (int[])null); int diff = Math.abs(currPixel[0] - lastPixel[0]); if (diff > GRAYSCALE_INTENSITY_THRESHOLD) { // we hit what could be a line // don't bother scanning it if we've hit a pixel in the line before boolean alreadyChecked = false; for (Line2D.Float line : verticalRulings) { if (x == line.getX1() && y >= line.getY1() && y <= line.getY2()) { alreadyChecked = true; break; } } if (alreadyChecked) { lastPixel = currPixel; continue; } int lineY = y + 1; while (lineY < height) { int[] linePixel = r.getPixel(x, lineY, (int[]) null); int[] leftPixel = r.getPixel(x - 1, lineY, (int[]) null); if (Math.abs(linePixel[0] - leftPixel[0]) <= GRAYSCALE_INTENSITY_THRESHOLD || Math.abs(currPixel[0] - linePixel[0]) > GRAYSCALE_INTENSITY_THRESHOLD) { break; } lineY++; } int endY = lineY - 1; int lineLength = endY - y; if (lineLength > 10) { verticalRulings.add(new Line2D.Float(x, y, x, endY)); } } lastPixel = currPixel; } } return verticalRulings; } private void removeText(PDDocument document, PDPage page) throws IOException { PDFStreamParser parser = new PDFStreamParser(page.getContents()); parser.parse(); List tokens = parser.getTokens(); List newTokens = new ArrayList(); for (int i=0; i<tokens.size(); i++) { Object token = tokens.get(i); if (token instanceof PDFOperator) { PDFOperator op = (PDFOperator)token; if (op.getOperation().equals("TJ") || op.getOperation().equals("Tj")) { newTokens.remove(newTokens.size() - 1); continue; } } newTokens.add(token); } PDStream newContents = new PDStream(document); ContentStreamWriter writer = new ContentStreamWriter(newContents.createOutputStream()); writer.writeTokens(newTokens); newContents.addCompression(); page.setContents(newContents); } }
package com.cmput301f17t07.ingroove.HabitStats; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.CalendarView; import android.widget.ProgressBar; import android.widget.TextView; import com.cmput301f17t07.ingroove.DataManagers.Command.DataManagerAPI; import com.cmput301f17t07.ingroove.DataManagers.MockDataManager; import com.cmput301f17t07.ingroove.Model.Day; import com.cmput301f17t07.ingroove.Model.Habit; import com.cmput301f17t07.ingroove.Model.HabitEvent; import com.cmput301f17t07.ingroove.Model.User; import com.cmput301f17t07.ingroove.R; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class HabitStatsActivity extends AppCompatActivity { DataManagerAPI data = new MockDataManager().getInstance(); TextView completedHabits; TextView missedHabits; ProgressBar habitProgress; CalendarView habitCalendar; ArrayList<HabitEvent> habitEvents; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_habit_stats); Habit passedHabit; Bundle bundle = this.getIntent().getExtras(); if (bundle != null){ //if (bundle == null) { // this isn't working properly yet, but it will be // but right noe the other section in else is running anyway, so it's okayish and doesn't break right away //passedHabit = (Habit) bundle.getSerializable("display_stats_for_habit"); // make work for mock data manager data.addUser("test"); User user = data.getUser(); ArrayList<Habit> habits = data.getHabit(user); passedHabit = habits.get(0); // unbundle or something Log.w("TEST TEST TEST","passed bundle != null"); // fill in the habit data // TextView habitTitle = (TextView) findViewById(R.id.habitStatsTitle); // habitTitle.setText("super awesome habit to do"); habitEvents = data.getHabitEvents(passedHabit); // first we get all the data we need // habit doesn't have a start day, so we parse through habit events // find the first start day, use as begining // look at repeat cycle and see how many we habit events we should have between // then and now // difference is missed // use this difference to get the progress bar amount // get the first day of the habit Date startDate = new Date(); for (HabitEvent event : habitEvents) { if (event.getDay() != null && startDate.compareTo(event.getDay()) < 0) { startDate = event.getDay(); } } Log.w("TEST TEST TEST", "the min day is " + String.valueOf(startDate)); // check to see how many habit events we should have int repeatedDays = passedHabit.getRepeatedDays().size(); // get number of days per week that we repeat int weeks = 0; Calendar cal = new GregorianCalendar(); while (cal.getTime().before(new Date())) { cal.add(Calendar.WEEK_OF_YEAR, 1); weeks++; } int totalPossibleDays = repeatedDays * weeks; int completedDays = habitEvents.size(); // then we set the data equal to what we need // give completed habits the number of habit events completedHabits = (TextView) findViewById(R.id.completed_value); completedHabits.setText(String.valueOf(completedDays)); missedHabits = (TextView) findViewById(R.id.missed_value); missedHabits.setText(String.valueOf(totalPossibleDays - completedDays)); habitProgress = (ProgressBar) findViewById(R.id.habitStatsProgressBar); habitProgress.setProgress((completedDays / totalPossibleDays) * 100); habitCalendar = (CalendarView) findViewById(R.id.habitStatsCalendarView); habitCalendar.setFirstDayOfWeek(1); } else { // show blank settings Log.w("TEST TEST TEST","went to else"); // want to include a title for this, but for some reason it's not working // to display right now, will fix later // TextView habitTitle = (TextView) findViewById(R.id.habitStatsTitle); // habitTitle.setText("Habit Stats Unavailable"); completedHabits = (TextView) findViewById(R.id.completed_value); completedHabits.setText("0"); missedHabits = (TextView) findViewById(R.id.missed_value); missedHabits.setText("0"); habitProgress = (ProgressBar) findViewById(R.id.habitStatsProgressBar); habitProgress.setProgress(0); habitCalendar = (CalendarView) findViewById(R.id.habitStatsCalendarView); habitCalendar.setFirstDayOfWeek(1); } } }
package io.spine.gradle.compiler.lookup.valrule; import io.spine.gradle.compiler.GradleProject; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Dictionary; import java.util.List; import java.util.Properties; import static io.spine.gradle.TaskName.FIND_VALIDATION_RULES; import static io.spine.gradle.compiler.Extension.getDefaultMainGenResDir; import static io.spine.util.Exceptions.illegalStateWithCauseOf; import static io.spine.validate.ValidationRules.getValRulesPropsFileName; import static org.junit.Assert.assertEquals; /** * @author Dmytro Grankin */ public class ValidationRulesLookupPluginShould { private static final char DOT = '.'; private static final String PROJECT_NAME = "validation-rules-lookup-plugin-test"; private static final String PROTO_FILE_PACKAGE = "test.valrule"; private static final String OUTER_MESSAGE_TYPE = "Outer"; private static final String VALIDATION_RULE_TYPE = "ValidationRule"; private static final String VALIDATION_TARGET = PROTO_FILE_PACKAGE + DOT + OUTER_MESSAGE_TYPE + DOT + "field_name"; private static final List<String> NESTED_VALIDATION_RULE_PROTO = Arrays.asList("syntax = \"proto3\";", "package " + PROTO_FILE_PACKAGE + ';', "import \"spine/options.proto\";", "message " + OUTER_MESSAGE_TYPE + " {", "message " + VALIDATION_RULE_TYPE + " {", "option (validation_of) = \"" + VALIDATION_TARGET + "\";", "}", "}" ); @Rule public final TemporaryFolder testProjectDir = new TemporaryFolder(); @Test public void findNestedValidationRules() throws Exception { final String file = "nested_validation_rule.proto"; final GradleProject project = newProjectWithFile(file, NESTED_VALIDATION_RULE_PROTO); project.executeTask(FIND_VALIDATION_RULES); final String expectedKey = PROTO_FILE_PACKAGE + DOT + OUTER_MESSAGE_TYPE + DOT + VALIDATION_RULE_TYPE; final String value = (String) getProperties().get(expectedKey); assertEquals(VALIDATION_TARGET, value); } private Dictionary getProperties() { final String projectPath = testProjectDir.getRoot() .getAbsolutePath(); final Path path = Paths.get(projectPath, getDefaultMainGenResDir(), getValRulesPropsFileName()); try { final InputStream inputStream = new FileInputStream(path.toFile()); final Properties properties = new Properties(); properties.load(inputStream); return properties; } catch (IOException e) { throw illegalStateWithCauseOf(e); } } private GradleProject newProjectWithFile(String protoFileName, List<String> protoFileLines) { return GradleProject.newBuilder() .setProjectName(PROJECT_NAME) .setProjectFolder(testProjectDir) .createProto(protoFileName, protoFileLines) .build(); } }
package org.sagebionetworks; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.sagebionetworks.client.SynapseAdminClient; import org.sagebionetworks.client.SynapseAdminClientImpl; import org.sagebionetworks.client.SynapseClient; import org.sagebionetworks.client.SynapseClientImpl; import org.sagebionetworks.client.exceptions.SynapseException; import org.sagebionetworks.repo.model.UserProfile; import org.sagebionetworks.repo.model.auth.NewUser; import org.sagebionetworks.repo.model.auth.Session; import org.sagebionetworks.repo.model.principal.AccountSetupInfo; import org.sagebionetworks.repo.model.principal.AddEmailInfo; import org.sagebionetworks.repo.model.principal.AliasCheckRequest; import org.sagebionetworks.repo.model.principal.AliasCheckResponse; import org.sagebionetworks.repo.model.principal.AliasType; public class IT502SynapseJavaClientAccountTest { private static SynapseAdminClient adminSynapse; private static SynapseAdminClient synapseAnonymous; private static SynapseClient synapseOne; private static Long user1ToDelete; private Long user2ToDelete; @BeforeClass public static void beforeClass() throws Exception { adminSynapse = new SynapseAdminClientImpl(); SynapseClientHelper.setEndpoints(adminSynapse); adminSynapse.setUserName(StackConfiguration.getMigrationAdminUsername()); adminSynapse.setApiKey(StackConfiguration.getMigrationAdminAPIKey()); adminSynapse.clearAllLocks(); synapseOne = new SynapseClientImpl(); user1ToDelete = SynapseClientHelper.createUser(adminSynapse, synapseOne); synapseAnonymous = new SynapseAdminClientImpl(); SynapseClientHelper.setEndpoints(synapseAnonymous); } private File fileToDelete; @Before public void before() throws SynapseException { fileToDelete = null; } @After public void after() throws Exception { if (fileToDelete!=null) { fileToDelete.delete(); fileToDelete=null; } if (user2ToDelete!=null) { try { adminSynapse.deleteUser(user2ToDelete); } catch (SynapseException e) { } } } @AfterClass public static void afterClass() throws Exception { try { adminSynapse.deleteUser(user1ToDelete); } catch (SynapseException e) { } } public static String readFile(File file) throws IOException { ByteArrayOutputStream content = new ByteArrayOutputStream(); InputStream fis = new FileInputStream(file); try { while (true) { int c = fis.read(); if (c<=0) break; content.write(c); } return content.toString(); } finally { fis.close(); } } public static File getFileForEmail(String email) { String tempDir = System.getProperty("java.io.tmpdir"); assertNotNull(tempDir); return new File(tempDir, email+".json"); } private String getTokenFromFile(File file, String endpoint) throws IOException { // the email is written to a local file. Read it and extract the link String body = readFile(file); String startString = "href=\\\""+endpoint; int endpointIndex = body.indexOf(startString); int tokenStart = endpointIndex+startString.length(); assertTrue(tokenStart>=0); int tokenEnd = body.indexOf("\\\">", tokenStart); assertTrue(tokenEnd>=0); String token = body.substring(tokenStart, tokenEnd); return token; } @Ignore @Test public void testCreateNewAccount() throws Exception { String email = UUID.randomUUID().toString()+"@foo.com"; fileToDelete = getFileForEmail(email); assertNotNull(fileToDelete.toString(), fileToDelete); NewUser user = new NewUser(); user.setEmail(email); user.setFirstName("firstName"); user.setLastName("lastName"); String endpoint = "https: synapseAnonymous.newAccountEmailValidation(user, endpoint); //assertTrue(fileToDelete.exists()); String token = getTokenFromFile(fileToDelete, endpoint); AccountSetupInfo accountSetupInfo = new AccountSetupInfo(); accountSetupInfo.setEmailValidationToken(token); accountSetupInfo.setFirstName("firstName"); accountSetupInfo.setLastName("lastName"); accountSetupInfo.setPassword(UUID.randomUUID().toString()); String username = UUID.randomUUID().toString(); accountSetupInfo.setUsername(username); Session session = synapseAnonymous.createNewAccount(accountSetupInfo); assertNotNull(session.getSessionToken()); // need to get the ID of the new user to delete it SynapseClientImpl sc = new SynapseClientImpl(); sc.setSessionToken(session.getSessionToken()); SynapseClientHelper.setEndpoints(sc); sc.setUserName(username); sc.signTermsOfUse(session.getSessionToken(), true); UserProfile up = sc.getMyProfile(); user2ToDelete = Long.parseLong(up.getOwnerId()); } @Ignore @Test public void testAddEmail() throws Exception { // start the email validation process String email = UUID.randomUUID().toString()+"@foo.com"; fileToDelete = getFileForEmail(email); assertNotNull(fileToDelete); assertTrue(fileToDelete.exists()); String endpoint = "https: synapseOne.additionalEmailValidation( Long.parseLong(synapseOne.getMyProfile().getOwnerId()), email, endpoint); // complete the email addition String token = getTokenFromFile(fileToDelete, endpoint); AddEmailInfo addEmailInfo = new AddEmailInfo(); addEmailInfo.setEmailValidationToken(token); // we are _not_ setting it to be the notification email synapseOne.addEmail(addEmailInfo, false); // now remove the email synapseOne.removeEmail(email); } @Test public void testNotificationEmail() throws SynapseException { UserProfile up = synapseOne.getMyProfile(); assertEquals(1, up.getEmails().size()); String myEmail = up.getEmails().get(0); String notificationEmail = synapseOne.getNotificationEmail(); // the current notification email is the one/only email that I have assertEquals(myEmail, notificationEmail); // no-op, just checking that everything's wired up right synapseOne.setNotificationEmail(myEmail); } @Test public void testCheckAliasAvailable() throws SynapseException{ AliasCheckRequest request = new AliasCheckRequest(); // This is valid but already in use request.setAlias("public"); request.setType(AliasType.TEAM_NAME); AliasCheckResponse response = synapseOne.checkAliasAvailable(request); assertNotNull(response); assertTrue(response.getValid()); assertFalse("The 'public' group name should already have this alias so it cannot be available!",response.getAvailable()); } }
package fi.iot.iiframework.controllers; import fi.iot.iiframework.views.ViewParams; import fi.iot.iiframework.views.ViewUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping("/") public String index(Model model) { ViewParams params = new ViewParams("Hello world!", "Tervetuloa ng-Springiin!"); ViewUtils.addViewParamsToModel(model, params); return "ng"; } }
package dk.statsbiblioteket.newspaper.processmonitor.backend; import dk.statsbiblioteket.newspaper.processmonitor.datasources.Batch; import dk.statsbiblioteket.newspaper.processmonitor.datasources.DataSource; import dk.statsbiblioteket.newspaper.processmonitor.datasources.Event; import dk.statsbiblioteket.newspaper.processmonitor.datasources.NotFoundException; import dk.statsbiblioteket.newspaper.processmonitor.datasources.NotWorkingProperlyException; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Component @Scope(value = "request") public class DataSourceCombiner implements DataSource { private List<DataSource> dataSources; public List<DataSource> getDataSources() { return dataSources; } @Resource(name = "dataSourcesList") public void setDataSources(List<DataSource> dataSources) { this.dataSources = dataSources; } @Override public boolean isRunNrInBatchID() { return true; } @Override public List<Batch> getBatches(boolean includeDetails, Map<String, String> filters) { Map<String, Batch> result = new HashMap<>(); for (DataSource dataSource : dataSources) { try { mergeResults(result, dataSource.getBatches(includeDetails, filters)); } catch (NotWorkingProperlyException e) { continue; } } return new ArrayList<>(result.values()); } private void mergeResults(Map<String, Batch> result, List<Batch> batches) { for (Batch batch : batches) { String id = batch.getBatchID(); result.put(id, mergeBatches(result.get(id), batch)); } } private Batch mergeBatches(Batch a, Batch b) { if (a == null) { return b; } if (b == null) { return a; } Batch result = new Batch(); result.setBatchID(a.getBatchID()); HashMap<String, Event> eventMap = new HashMap<String, Event>(); for (Event event : a.getEventList()) { eventMap.put(event.getEventID(), event); } boolean aIsHigher = a.getRunNr() > b.getRunNr(); for (Event event : b.getEventList()) { Event existing = eventMap.get(event.getEventID()); if (existing != null) { if (!aIsHigher) { eventMap.put(event.getEventID(), event); } } } result.setEventList(new ArrayList<>(eventMap.values())); return result; } @Override public Batch getBatch(String batchID, boolean includeDetails) throws NotFoundException { List<Batch> founds = new ArrayList<>(); for (DataSource dataSource : dataSources) { try { founds.add(dataSource.getBatch(batchID, includeDetails)); } catch (NotWorkingProperlyException e) { continue; } } Batch result = null; for (Batch found : founds) { result = mergeBatches(result, found); } if (result == null) { throw new NotFoundException(); } return result; } @Override public Event getBatchEvent(String batchID, String eventID, boolean includeDetails) throws NotFoundException { for (DataSource dataSource : dataSources) { Event result = null; try { result = dataSource.getBatchEvent(batchID, eventID, includeDetails); } catch (NotWorkingProperlyException e) { continue; } return result; } throw new NotFoundException(); } }
package dk.statsbiblioteket.newspaper.processmonitor.backend; import java.sql.SQLException; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import dk.statsbiblioteket.newspaper.mfpakintegration.database.InconsistentDatabaseException; import dk.statsbiblioteket.newspaper.mfpakintegration.database.MfPakDAO; import dk.statsbiblioteket.newspaper.mfpakintegration.database.NewspaperDateRange; @Component public class MfPakBatchEnricher implements BatchEnricher { private MfPakDAO mfpak; private Logger log = LoggerFactory.getLogger(getClass()); public MfPakDAO getMfpak() { return mfpak; } public void setMfpak(MfPakDAO mfpak) { this.mfpak = mfpak; } /** * Enriches the batch objects with 'avisid' and date intervals from the mfpak database. * The returned reference to list of batches is the same as the one taken as input. */ @Override public List<Batch> enrich(List<Batch> batches) { for(Batch b : batches) { String batchID = b.getBatchID(); try { b.setAvisID(mfpak.getNewspaperID(batchID)); enrichWithDateRange(b); } catch (InconsistentDatabaseException | SQLException e) { log.debug("Failed to enrich batch {}", batchID, e); } } return batches; } /** * Enriches the batch with the start and stop dates from mfpak */ private Batch enrichWithDateRange(Batch batch) throws SQLException { List<NewspaperDateRange> ranges = mfpak.getBatchDateRanges(batch.getBatchID()); Date tempStartDate = new Date(); Date tempEndDate = new Date(0); for(NewspaperDateRange range : ranges) { if(range.getFromDate().before(tempStartDate)) { tempStartDate = range.getFromDate(); } if(range.getToDate().after(tempEndDate)) { tempEndDate = range.getToDate(); } } batch.setStartDate(tempStartDate); batch.setEndDate(tempEndDate); return batch; } }
package com.ctrip.xpipe.redis.checker.healthcheck.actions.sentinel; import com.ctrip.xpipe.api.monitor.Task; import com.ctrip.xpipe.api.monitor.TransactionMonitor; import com.ctrip.xpipe.concurrent.AbstractExceptionLogTask; import com.ctrip.xpipe.exception.ExceptionUtils; import com.ctrip.xpipe.redis.checker.Persistence; import com.ctrip.xpipe.redis.checker.config.CheckerDbConfig; import com.ctrip.xpipe.redis.checker.healthcheck.*; import com.ctrip.xpipe.redis.checker.healthcheck.leader.AbstractLeaderAwareHealthCheckAction; import com.ctrip.xpipe.redis.checker.healthcheck.session.RedisSession; import com.ctrip.xpipe.redis.core.entity.ClusterMeta; import com.ctrip.xpipe.redis.core.entity.RedisMeta; import com.ctrip.xpipe.redis.core.entity.ShardMeta; import com.ctrip.xpipe.redis.core.meta.MetaCache; import com.ctrip.xpipe.utils.VisibleForTesting; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @author chen.zhu * <p> * Oct 09, 2018 */ public class SentinelHelloCheckAction extends AbstractLeaderAwareHealthCheckAction<ClusterHealthCheckInstance> { private static final Logger logger = LoggerFactory.getLogger(SentinelHelloCheckAction.class); protected static int SENTINEL_COLLECT_INFO_INTERVAL = 5000; public static final String HELLO_CHANNEL = "__sentinel__:hello"; private Map<RedisHealthCheckInstance, Set<SentinelHello>> hellos = Maps.newConcurrentMap(); private Map<RedisHealthCheckInstance, Throwable> errors = Maps.newConcurrentMap(); private CheckerDbConfig checkerDbConfig; private Persistence persistence; public static final String LOG_TITLE = "SentinelHelloCollect"; private MetaCache metaCache; private HealthCheckInstanceManager instanceManager; private Set<RedisHealthCheckInstance> redisInstancesToCheck = new HashSet<>(); private volatile boolean processing = false; public SentinelHelloCheckAction(ScheduledExecutorService scheduled, ClusterHealthCheckInstance instance, ExecutorService executors, CheckerDbConfig checkerDbConfig, Persistence persistence, MetaCache metaCache, HealthCheckInstanceManager instanceManager) { super(scheduled, instance, executors); this.checkerDbConfig = checkerDbConfig; this.persistence = persistence; this.metaCache = metaCache; this.instanceManager= instanceManager; } @Override protected void doTask() { TransactionMonitor transaction = TransactionMonitor.DEFAULT; transaction.logTransactionSwallowException("sentinel.health.check", instance.getCheckInfo().getClusterId(), new Task() { @Override public void go() throws Exception { redisInstancesToCheck = redisInstancesToCheck(); subAllRedisInstances(redisInstancesToCheck); scheduled.schedule(new AbstractExceptionLogTask() { @Override protected void doRun() throws Exception { processSentinelHellos(); } }, SENTINEL_COLLECT_INFO_INTERVAL, TimeUnit.MILLISECONDS); } @Override public Map<String, Object> getData() { Map<String, Object> transactionData = new HashMap<>(); transactionData.put("checkInterval", getBaseCheckInterval()); transactionData.put("checkRedisInstances", redisInstancesToCheck); return transactionData; } }); } @Override protected int getBaseCheckInterval() { return instance.getHealthCheckConfig().getSentinelCheckIntervalMilli(); } @Override protected int getCheckTimeInterval(int baseInterval) { return Math.abs(random.nextInt(baseInterval) % baseInterval); } @Override protected Logger getHealthCheckLogger() { return logger; } Set<RedisHealthCheckInstance> redisInstancesToCheck() { Set<RedisHealthCheckInstance> redisHealthCheckInstances = new HashSet<>(); try { metaCache.getXpipeMeta().getDcs().forEach((dc, dcMeta) -> { ClusterMeta clusterMeta = dcMeta.getClusters().get(getActionInstance().getCheckInfo().getClusterId()); logger.debug("[{}-{}][{}]found in MetaCache", LOG_TITLE, instance.getCheckInfo().getClusterId(), dc, instance.getCheckInfo().getClusterId()); if (clusterMeta != null) { Map<String, ShardMeta> clusterShards = clusterMeta.getShards(); logger.debug("[{}-{}][{}]shards num:{}, detail info:{}", LOG_TITLE, instance.getCheckInfo().getClusterId(), dc, clusterShards.size(), clusterShards); clusterShards.forEach((shardId, shardMeta) -> { try { List<RedisMeta> redisMetas = shardMeta.getRedises(); logger.debug("[{}-{}+{}][{}]redis num:{}, detail info:{}", LOG_TITLE, instance.getCheckInfo().getClusterId(), shardId, dc, redisMetas.size(), redisMetas); redisMetas.forEach((redisMeta) -> { try { RedisHealthCheckInstance redisInstance = instanceManager.getOrCreate(redisMeta); if (super.shouldCheck(redisInstance)) { redisHealthCheckInstances.add(redisInstance); hellos.put(redisInstance, Sets.newHashSet()); } else { redisInstance.getRedisSession().closeSubscribedChannel(HELLO_CHANNEL); } } catch (Exception e) { logger.warn("[{}-{}+{}]get redis health check instance {}:{} failed", LOG_TITLE, instance.getCheckInfo().getClusterId(), shardId, redisMeta.getIp(), redisMeta.getPort(), e); } }); } catch (Exception e) { logger.warn("[{}-{}+{}]get redis health check instance from shard {} failed", LOG_TITLE, instance.getCheckInfo().getClusterId(), shardId, shardId, e); } }); } }); } catch (Exception e) { logger.warn("[{}-{}]get redis health check instances from cluster {} failed", LOG_TITLE, instance.getCheckInfo().getClusterId(), instance.getCheckInfo().getClusterId(), e); } return redisHealthCheckInstances; } void subAllRedisInstances(Set<RedisHealthCheckInstance> redisInstancesToCheck) { redisInstancesToCheck.forEach(redisInstanceToCheck -> { try { RedisInstanceInfo info = redisInstanceToCheck.getCheckInfo(); if (redisInstanceToCheck.getCheckInfo().isInActiveDc()) { logger.info("[{}-{}+{}]{} instance {} in active dc", LOG_TITLE, info.getClusterShardHostport().getClusterName(), info.getShardId(), info.getDcId(), redisInstanceToCheck.getCheckInfo().getHostPort()); } redisInstanceToCheck.getRedisSession().subscribeIfAbsent(HELLO_CHANNEL, new RedisSession.SubscribeCallback() { @Override public void message(String channel, String message) { executors.execute(new Runnable() { @Override public void run() { if (processing) return; SentinelHello hello = SentinelHello.fromString(message); Set<SentinelHello> currentInstanceHellos = hellos.get(redisInstanceToCheck); if (currentInstanceHellos == null) { hellos.put(redisInstanceToCheck, Sets.newHashSet(hello)); } else { currentInstanceHellos.add(hello); } } }); } @Override public void fail(Throwable e) { if (processing) return; if (ExceptionUtils.isStackTraceUnnecessary(e)) { logger.error("[{}-{}+{}]{} instance {} sub-failed, reason:{}", LOG_TITLE, info.getClusterShardHostport().getClusterName(), info.getShardId(), info.getDcId(), info.getHostPort(), e.getMessage()); } else { logger.error("[{}-{}+{}]{} instance {} sub-failed", LOG_TITLE, info.getClusterShardHostport().getClusterName(), info.getShardId(), info.getDcId(), info.getHostPort(), e); } errors.put(redisInstanceToCheck, e); } }); } catch (Exception e) { logger.warn("[{}-{}]subscribe redis instance {}:{} failed", LOG_TITLE,instance.getCheckInfo().getClusterId(), redisInstanceToCheck.getEndpoint().getHost(), redisInstanceToCheck.getEndpoint().getPort(), e); } }); } @VisibleForTesting protected void processSentinelHellos() { processing = true; if (hellos.size() + errors.size() == 0) { logger.warn("[{}-{}]sub result empty", LOG_TITLE, instance.getCheckInfo().getClusterId()); resetResults(); return; } List<SentinelActionContext> contexts = new ArrayList<>(); for (RedisHealthCheckInstance instance : errors.keySet()) hellos.remove(instance); for (RedisHealthCheckInstance instance : hellos.keySet()) { contexts.add(new SentinelActionContext(instance, hellos.get(instance))); } for (RedisHealthCheckInstance instance : errors.keySet()) { contexts.add(new SentinelActionContext(instance, errors.get(instance))); } resetResults(); contexts.forEach(this::notifyListeners); } @Override protected boolean shouldCheck(HealthCheckInstance checkInstance) { String cluster = checkInstance.getCheckInfo().getClusterId(); if (!checkerDbConfig.shouldSentinelCheck(cluster)) { logger.warn("[{}][BackupDc] cluster {} is in sentinel check whitelist, quit", LOG_TITLE, cluster); return false; } if (persistence.isClusterOnMigration(cluster)) { logger.warn("[{}][{}] in migration, stop check", LOG_TITLE, cluster); return false; } return checkerDbConfig.isSentinelAutoProcess(); } @Override public void doStop() { redisInstancesToCheck.forEach(redisInstance -> { redisInstance.getRedisSession().closeSubscribedChannel(HELLO_CHANNEL); }); resetResults(); super.doStop(); } void resetResults() { hellos.clear(); errors.clear(); processing = false; } @VisibleForTesting Map<RedisHealthCheckInstance, Set<SentinelHello>> getHellos() { return hellos; } @VisibleForTesting void setHellos(Map<RedisHealthCheckInstance, Set<SentinelHello>> hellos) { this.hellos = hellos; } @VisibleForTesting Map<RedisHealthCheckInstance, Throwable> getErrors() { return errors; } @VisibleForTesting void setErrors(Map<RedisHealthCheckInstance, Throwable> errors) { this.errors = errors; } }
package org.apache.derbyTesting.functionTests.tests.jdbcapi; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Statement; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.derbyTesting.junit.BaseJDBCTestCase; import org.apache.derbyTesting.junit.CleanDatabaseTestSetup; import org.apache.derbyTesting.junit.JDBC; import org.apache.derbyTesting.junit.TestConfiguration; /** * Test the new class Savepoint in JDBC 30. Also, test some mix and match of * defining savepoints through JDBC and SQL testing both callable and prepared * statements meta data * */ public class SavepointJdbc30Test extends BaseJDBCTestCase { /** * Create a test * * @param name */ public SavepointJdbc30Test(String name) { super(name); } /** * Set up the test suite for embedded mode, client mode, and embedded mode * with XADataSources * * @return A suite containing embedded, client and embedded with XA suites */ public static Test suite() { TestSuite suite = new TestSuite("SavepointJdbc30_JSR169Test suite"); // Get the tests for embedded TestSuite embedded = new TestSuite( "SavepointJdbc30_JSR169Test:embedded"); embedded.addTestSuite(SavepointJdbc30Test.class); embedded.addTest(getEmbeddedSuite("SavepointJdbc30_JSR169Test:" + "embedded only")); suite.addTest(embedded); // Get the tests for client. TestSuite client = new TestSuite("SavepointJdbc30_JSR169Test:client"); client.addTestSuite(SavepointJdbc30Test.class); suite.addTest(TestConfiguration.clientServerDecorator(client)); // Repeat the embedded tests obtaining a connection from // an XA data source if it is supported. This is not supported // under JSR169 if (JDBC.vmSupportsJDBC3()) { embedded = new TestSuite( "SavepointJdbc30_JSR169Test:embedded XADataSource"); embedded.addTestSuite(SavepointJdbc30Test.class); embedded.addTest(getEmbeddedSuite("SavepointJdbc30_JSR169Test:" + "embedded only XADataSource")); suite.addTest(TestConfiguration.connectionXADecorator(embedded)); } // return suite; return new CleanDatabaseTestSetup(suite) { /** * Creates the database objects used in the test cases. * * @throws SQLException */ protected void decorateSQL(Statement s) throws SQLException { /* Create a table */ s.execute("create table t1 (c11 int, c12 smallint)"); s.execute("create table t2 (c11 int)"); getConnection().commit(); } }; } /** * Create a testsuite containing the tests that can only run in embedded * mode. These tests have names starting with x and are added automatically. */ private static Test getEmbeddedSuite(String name) { TestSuite embedded = new TestSuite(name); Method[] methods = SavepointJdbc30Test.class.getMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (m.getParameterTypes().length > 0 || !m.getReturnType().equals(Void.TYPE)) { continue; } String methodName = m.getName(); if (methodName.startsWith("x")) { embedded.addTest(new SavepointJdbc30Test(methodName)); } } return embedded; } /** * setUp: Just keep AutoCommit off. */ protected void setUp() throws Exception { super.setUp(); // Keep Autocommit off getConnection().setAutoCommit(false); } /** * Test1. It should not be possible to set a savepoint if autocommit is on. */ public void testNoSavepointsIfAutoCommit() throws SQLException { Connection con = getConnection(); con.setAutoCommit(true); try { con.setSavepoint(); // will throw exception because auto commit is // true fail("No unnamed savepoints allowed if autocommit is true"); } catch (SQLException se) { // Expected exception. assertSQLState("XJ010", se); } // Test 1a try { con.setSavepoint("notallowed"); // will throw exception because auto // commit is true fail("No named savepoints allowed if autocommit is true"); } catch (SQLException se) { // Expected exception. assertSQLState("XJ010", se); } } /** * Test2 - After releasing a savepoint, should be able to reuse it. */ public void testReusingSavepoints() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("s1"); con.releaseSavepoint(savepoint1); con.setSavepoint("s1"); con.rollback(); } /** * Test3 - Named savepoints can't pass null for name */ public void testNullName() throws SQLException { Connection con = getConnection(); try { con.setSavepoint(null); fail("FAIL 3 Null savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("XJ011", se); } con.rollback(); } /** * Test4 - Verify names/ids of named/unnamed savepoints named savepoints * don't have an id. unnamed savepoints don't have a name (internally, all * our savepoints have names, but for unnamed savepoint, that is not exposed * through jdbc api) * * @throws SQLException */ public void testNamesAndIds() throws SQLException { Connection con = getConnection(); try { Savepoint savepoint1 = con.setSavepoint(); savepoint1.getSavepointId(); // following should throw exception for unnamed savepoint savepoint1.getSavepointName(); fail("FAIL 4 getSavepointName on id savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("XJ014", se); } con.rollback(); try { Savepoint savepoint1 = con.setSavepoint("s1"); savepoint1.getSavepointName(); // following should throw exception for named savepoint savepoint1.getSavepointId(); fail("FAIL 4 getSavepointId on named savepoint "); } catch (SQLException se) { // Expected exception. assertSQLState("XJ013", se); } con.rollback(); } /** * TEST 5a and 5b for bug 4465 test 5a - create two savepoints in two * different transactions and release the first one in the subsequent * transaction */ public void testBug4465() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("s1"); con.commit(); // The following savepoint was earlier named s1. Changed it to s2 while // working on DRDA support // for savepoints. The reason for that is as follows // The client translates all savepoint jdbc calls to equivalent sql and // hence // if the 2 savepoints in // different connections are named the same, then the release savepoint // below will get converted to // RELEASE TO SAVEPOINT s1 and that succeeds because the 2nd connection // does have a savepoint named s1. // Hence we don't really check what we intended to check which is trying // to release a savepoint created // in a different transaction con.setSavepoint("s2"); Statement s = createStatement(); s.executeUpdate("INSERT INTO T1 VALUES(2,1)"); try { con.releaseSavepoint(savepoint1); fail("FAIL 5a - release savepoint from a different transaction " + "did not raise error"); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } con.commit(); // test 5b - create two savepoints in two different transactions // and rollback the first one in the subsequent transaction savepoint1 = con.setSavepoint("s1"); con.commit(); // The following savepoint was earlier named s1. Changed it to s2 while // working on DRDA support // for savepoints. The reason for that is as follows // The client translates all savepoint jdbc calls to equivalent sql and // hence // if the 2 savepoints in // different connections are named the same, then the rollback savepoint // below will get converted to // ROLLBACK TO SAVEPOINT s1 and that succeeds because the 2nd connection // does have a savepoint named s1. // Hence we don't really check what we intended to check which is trying // to rollback a savepoint created // in a different transaction con.setSavepoint("s2"); s.executeUpdate("INSERT INTO T1 VALUES(2,1)"); try { con.rollback(savepoint1); fail("FAIL 5b - rollback savepoint from a different transaction " + "did not raise error"); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } con.commit(); } /** * test 6a - create a savepoint release it and then create another with the * same name. and release the first one */ public void testReleaseReleasedSavepoint() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("s1"); con.releaseSavepoint(savepoint1); // The following savepoint was earlier named s1. Changed it to s2 while // working on DRDA support // for savepoints. The reason for that is as follows // The client translates all savepoint jdbc calls to equivalent sql and // hence // if the 2 savepoints in // a transaction are named the same, then the release savepoint below // will get converted to // RELEASE TO SAVEPOINT s1 and that succeeds because there is a valid // savepoint named s1. con.setSavepoint("s2"); Statement s = createStatement(); s.executeUpdate("INSERT INTO T1 VALUES(2,1)"); try { con.releaseSavepoint(savepoint1); fail("FAIL 6a - releasing a released savepoint did not raise error"); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } con.commit(); } /** * test 6b - create a savepoints release it and then create another with the * same name. and rollback the first one */ public void testRollbackReleasedSavepoint() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("s1"); con.releaseSavepoint(savepoint1); // The following savepoint was earlier named s1. Changed it to s2 while // working on DRDA support // for savepoints. The reason for that is as follows // The client translates all savepoint jdbc calls to equivalent sql and // hence // if the 2 savepoints in // a transaction are named the same, then the rollback savepoint below // will get converted to // ROLLBACK TO SAVEPOINT s1 and that succeeds because there is a valid // savepoint named s1. con.setSavepoint("s2"); Statement s = createStatement(); s.executeUpdate("INSERT INTO T1 VALUES(2,1)"); try { con.rollback(savepoint1); fail("FAIL 6b - rollback a released savepoint did not raise error"); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } con.commit(); } /** * Test 6c: TEST case just for bug 4467 // Test 10 - create a named * savepoint with the a generated name savepoint1 = * con2.setSavepoint("SAVEPT0"); // what exactly is the correct behaviour * here? try { savepoint2 = con2.setSavepoint(); } catch (SQLException se) { * System.out.println("Expected Exception is " + se.getMessage()); } * con2.commit(); */ public void testReleaseSavepointFromOtherTransaction() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("s1"); Statement s = createStatement(); s.executeUpdate("INSERT INTO T1 VALUES(2,1)"); Connection con2 = openDefaultConnection(); try { con2.releaseSavepoint(savepoint1); fail("FAIL 6c - releasing another transaction's savepoint did " + "not raise error"); } catch (SQLException se) { // Expected exception. if (usingEmbedded()) { assertSQLState("XJ010", se); } else if (usingDerbyNetClient()) { assertSQLState("XJ008", se); } } con.commit(); con2.commit(); } /** * Test 7a: BUG 4468 - should not be able to pass a savepoint from a * different transaction for release/rollback */ public void testSwapSavepointsAcrossConnectionAndRelease() throws SQLException { Connection con = getConnection(); Connection con2 = openDefaultConnection(); con2.setAutoCommit(false); Savepoint savepoint1 = con2.setSavepoint("s1"); Statement s = createStatement(); s.executeUpdate("INSERT INTO T1 VALUES(2,1)"); con.setSavepoint("s1"); try { con.releaseSavepoint(savepoint1); fail("FAIL 7a - releasing a another transaction's savepoint did " + "not raise error"); } catch (SQLException se) { // Expected exception. if (usingEmbedded()) { assertSQLState("3B502", se); } else if (usingDerbyNetClient()) { assertSQLState("XJ097", se); } } con.commit(); con2.commit(); } /** * Test 7b - swap savepoints across connections */ public void testSwapSavepointsAcrossConnectionsAndRollback() throws SQLException { Connection con = getConnection(); Connection con2 = openDefaultConnection(); con2.setAutoCommit(false); Savepoint savepoint1 = con2.setSavepoint("s1"); Statement s = createStatement(); s.executeUpdate("INSERT INTO T1 VALUES(2,1)"); con.setSavepoint("s1"); try { con.rollback(savepoint1); fail("FAIL 7b - rolling back a another transaction's savepoint " + "did not raise error"); } catch (SQLException se) { // Expected exception. if (usingEmbedded()) { assertSQLState("3B502", se); } else if (usingDerbyNetClient()) { assertSQLState("XJ097", se); } } con.commit(); con2.commit(); } /* * following section attempts to call statement in a method to do a negative * test because savepoints are not supported in a trigger however, this * cannot be done because a call is not supported in a trigger. leaving the * test here for later reference for when we support the SQL version // bug * 4507 - Test 8 test all 4 savepoint commands inside the trigger code * System.out.println("Test 8a set savepoint(unnamed) command inside the * trigger code"); s.executeUpdate("create trigger trig1 before insert on t1 * for each statement call * org.apache.derbyTesting.functionTests.tests.jdbcapi.savepointJdbc30::doConnectionSetSavepointUnnamed()"); * try { * * s.executeUpdate("insert into t1 values(1,1)"); System.out.println("FAIL * 8a set savepoint(unnamed) command inside the trigger code"); } catch * (SQLException se) { System.out.println("Expected Exception is " + * se.getMessage()); } s.executeUpdate("drop trigger trig1"); * * System.out.println("Test 8b set savepoint(named) command inside the * trigger code"); s.executeUpdate("create trigger trig2 before insert on t1 * for each statement call * org.apache.derbyTesting.functionTests.tests.jdbcapi.savepointJdbc30::doConnectionSetSavepointNamed()"); * try { s.executeUpdate("insert into t1 values(1,1)"); * System.out.println("FAIL 8b set savepoint(named) command inside the * trigger code"); } catch (SQLException se) { System.out.println("Expected * Exception is " + se.getMessage()); } s.executeUpdate("drop trigger * trig2"); * * System.out.println("Test 8c release savepoint command inside the trigger * code"); s.executeUpdate("create trigger trig3 before insert on t1 for * each statement call * org.apache.derbyTesting.functionTests.tests.jdbcapi.savepointJdbc30::doConnectionReleaseSavepoint()"); * try { s.executeUpdate("insert into t1 values(1,1)"); * System.out.println("FAIL 8c release savepoint command inside the trigger * code"); } catch (SQLException se) { System.out.println("Expected * Exception is " + se.getMessage()); } s.executeUpdate("drop trigger * trig3"); * * System.out.println("Test 8d rollback savepoint command inside the trigger * code"); s.executeUpdate("create trigger trig4 before insert on t1 for * each statement call * org.apache.derbyTesting.functionTests.tests.jdbcapi.savepointJdbc30::doConnectionRollbackSavepoint()"); * try { s.executeUpdate("insert into t1 values(1,1)"); * System.out.println("FAIL 8d rollback savepoint command inside the trigger * code"); } catch (SQLException se) { System.out.println("Expected * Exception is " + se.getMessage()); } s.executeUpdate("drop trigger * trig4"); con.rollback(); */// end commented out test 8 /** * Test 9 test savepoint name and verify case sensitivity */ public void testSavepointName() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("myname"); String savepointName = savepoint1.getSavepointName(); assertEquals(savepointName, "myname"); con.rollback(); } /** * Test 10 test savepoint name case sensitivity */ public void testNameCaseSensitivity() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("MyName"); String savepointName = savepoint1.getSavepointName(); assertEquals(savepointName, "MyName"); con.rollback(); } /** * Test 11 rolling back a savepoint multiple times - should work */ public void testRollbackMultipleTimes() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("MyName"); con.rollback(savepoint1); con.rollback(savepoint1); con.rollback(); } /** * Test 12 releasing a savepoint multiple times - should not work */ public void testReleaseMultipleTimes() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("MyName"); con.releaseSavepoint(savepoint1); try { con.releaseSavepoint(savepoint1); fail("FAIL 12 releasing a savepoint multiple times should fail"); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } con.rollback(); } /** * Test 13 shouldn't be able to use a savepoint from earlier transaction * after setting autocommit on and off */ public void testSavepointFromEarlierTransactionAfterToggleAutocommit() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("MyName"); con.setAutoCommit(true); con.setAutoCommit(false); Savepoint savepoint2 = con.setSavepoint("MyName1"); try {// shouldn't be able to use savepoint from earlier tranasaction // after setting autocommit on and off con.releaseSavepoint(savepoint1); fail("FAIL 13 shouldn't be able to use a savepoint from earlier " + "transaction after setting autocommit on and off"); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } con.releaseSavepoint(savepoint2); con.rollback(); } /** * Test 14 cause a transaction rollback and that should release the internal * savepoint array */ public void testRollbackReleasesSavepointArray() throws SQLException { Connection con = getConnection(); Connection con2 = openDefaultConnection(); con2.setAutoCommit(false); Statement s1, s2; s1 = createStatement(); s1.executeUpdate("insert into t1 values(1,1)"); s1.executeUpdate("insert into t1 values(2,0)"); con.commit(); s1.executeUpdate("update t1 set c11=c11+1 where c12 > 0"); s2 = con2.createStatement(); Savepoint savepoint1 = con2.setSavepoint("MyName"); try {// following will get lock timeout which will rollback // transaction on c2 s2.executeUpdate("update t1 set c11=c11+1 where c12 < 1"); fail("FAIL 14 should have gotten lock time out"); } catch (SQLException se) { // Expected exception. assertSQLState("40XL1", se); } try {// the transaction rollback above should have removed the // savepoint MyName con2.releaseSavepoint(savepoint1); fail("FAIL 14 A non-user initiated transaction rollback should " + "release the internal savepoint array"); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } con.rollback(); con2.rollback(); s1.execute("delete from t1"); con.commit(); } /** Test 15 Check savepoints in batch */ public void testSavepointsInBatch() throws SQLException { Connection con = getConnection(); Statement s = createStatement(); s.execute("delete from t1"); s.addBatch("insert into t1 values(1,1)"); s.addBatch("insert into t1 values(2,2)"); Savepoint savepoint1 = con.setSavepoint(); s.addBatch("insert into t1 values(3,3)"); s.executeBatch(); con.rollback(savepoint1); assertTableRowCount("T1", 0); con.rollback(); } /** Test 16 grammar check for savepoint sq1 */ public void testGrammarCheck() throws SQLException { Statement s = getConnection().createStatement(); try { s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS"); fail("FAIL 16 Should have gotten exception for missing ON ROLLBACK " + "RETAIN CURSORS"); } catch (SQLException se) { // Expected exception. assertSQLState("42X01", se); } try { s.executeUpdate("SAVEPOINT s1 UNIQUE ON ROLLBACK RETAIN CURSORS " + "ON ROLLBACK RETAIN CURSORS"); fail("FAIL 16 Should have gotten exception for multiple ON ROLLBACK " + "RETAIN CURSORS"); } catch (SQLException se) { // Expected exception. assertSQLState("42613", se); } try { s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON ROLLBACK" + " RETAIN LOCKS"); fail("FAIL 16 Should have gotten exception for multiple ON ROLLBACK " + "RETAIN LOCKS"); } catch (SQLException se) { // Expected exception. assertSQLState("42613", se); } try { s.executeUpdate("SAVEPOINT s1 UNIQUE UNIQUE ON ROLLBACK RETAIN " + "LOCKS ON ROLLBACK RETAIN CURSORS"); fail("FAIL 16 Should have gotten exception for multiple UNIQUE keywords"); } catch (SQLException se) { // Expected exception. assertSQLState("42613", se); } s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN CURSORS ON ROLLBACK " + "RETAIN LOCKS"); s.executeUpdate("RELEASE TO SAVEPOINT s1"); getConnection().rollback(); } /** Test 17 */ public void testNoNestedSavepointsWhenUsingSQL() throws SQLException { Statement s = getConnection().createStatement(); s.executeUpdate("SAVEPOINT s1 UNIQUE ON ROLLBACK RETAIN LOCKS ON " + "ROLLBACK RETAIN CURSORS"); try { s.executeUpdate("SAVEPOINT s2 UNIQUE ON ROLLBACK RETAIN " + "LOCKS ON ROLLBACK RETAIN CURSORS"); fail("FAIL 17a Should have gotten exception for nested savepoints"); } catch (SQLException se) { // Expected exception. assertSQLState("3B002", se); } s.executeUpdate("RELEASE TO SAVEPOINT s1"); s.executeUpdate("SAVEPOINT s2 UNIQUE ON ROLLBACK RETAIN LOCKS ON " + "ROLLBACK RETAIN CURSORS"); getConnection().rollback(); s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON ROLLBACK " + "RETAIN CURSORS"); try { s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON " + "ROLLBACK RETAIN CURSORS"); fail("FAIL 17b Should have gotten exception for nested savepoints"); } catch (SQLException se) { // Expected exception. assertSQLState("3B002", se); } getConnection().rollback(); } /** Test 18 */ public void testNoNestedSavepointsInsideJdbcSavepoint() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint(); Statement s = getConnection().createStatement(); // Following SQL savepoint will fail because we are trying to nest it // inside JDBC savepoint try { s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON ROLLBACK" + " RETAIN CURSORS"); fail("FAIL 18 shouldn't be able set SQL savepoint nested inside " + "JDBC savepoints"); } catch (SQLException se) { // Expected exception. assertSQLState("3B002", se); } // rollback the JDBC savepoint. Now since there are no user defined // savepoints, we can define SQL savepoint con.releaseSavepoint(savepoint1); s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON " + "ROLLBACK RETAIN CURSORS"); con.rollback(); } /** Test 19 */ public void testNoNestedSavepointsInsideSqlSavepoint() throws SQLException { Statement s = getConnection().createStatement(); s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON ROLLBACK " + "RETAIN CURSORS"); try { s.executeUpdate("SAVEPOINT s2 ON ROLLBACK RETAIN LOCKS ON ROLLBACK" + " RETAIN CURSORS"); fail("FAIL 19 shouldn't be able set SQL savepoint nested inside " + "SQL savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("3B002", se); } // rollback the SQL savepoint. Now since there are no user defined // savepoints, we can define SQL savepoint s.executeUpdate("RELEASE TO SAVEPOINT s1"); s.executeUpdate("SAVEPOINT s2 ON ROLLBACK RETAIN LOCKS ON ROLLBACK " + "RETAIN CURSORS"); getConnection().rollback(); } /** Test 20 */ public void testRollbackSqlSavepointSameAsJdbc() throws SQLException { Connection con = getConnection(); Statement s = createStatement(); s.executeUpdate("DELETE FROM T1"); con.commit(); s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON ROLLBACK " + "RETAIN CURSORS"); s.executeUpdate("INSERT INTO T1 VALUES(1,1)"); s.executeUpdate("INSERT INTO T1 VALUES(1,1)"); s.executeUpdate("INSERT INTO T1 VALUES(1,1)"); // Rollback to SQL savepoint and should see changes rolledback s.execute("ROLLBACK TO SAVEPOINT s1"); ResultSet rs1 = s.executeQuery("select count(*) from t1"); rs1.next(); assertEquals(rs1.getInt(1), 0); con.rollback(); } /** Test 21 */ public void testReleaseSqlSavepointAndRollback() throws SQLException { Connection con = getConnection(); Statement s = createStatement(); s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON ROLLBACK " + "RETAIN CURSORS"); s.executeUpdate("INSERT INTO T1 VALUES(1,1)"); s.executeUpdate("INSERT INTO T1 VALUES(2,1)"); s.executeUpdate("INSERT INTO T1 VALUES(3,1)"); // Release the SQL savepoint and then rollback the transaction and // should see changes rolledback s.executeUpdate("RELEASE TO SAVEPOINT s1"); con.rollback(); ResultSet rs1 = s.executeQuery("select count(*) from t1"); rs1.next(); assertEquals(rs1.getInt(1), 0); con.rollback(); } /** Test 22 */ public void testNoSqlSavepointStartingWithSYS() throws SQLException { Statement s = createStatement(); try { s.executeUpdate("SAVEPOINT SYSs2 ON ROLLBACK RETAIN LOCKS ON " + "ROLLBACK RETAIN CURSORS"); fail("FAIL 22 shouldn't be able to create a SQL savepoint starting " + "with name SYS"); } catch (SQLException se) { // Expected exception. assertSQLState("42939", se); } getConnection().rollback(); } /** * Test 23 - bug 5817 - make savepoint and release non-reserved keywords */ public void testBug5817() throws SQLException { Statement s = createStatement(); s.execute("create table savepoint (savepoint int, release int)"); ResultSet rs1 = s.executeQuery("select count(*) from savepoint"); rs1.next(); assertEquals(" There should have been 0 rows in the table, but found " + rs1.getInt(1), rs1.getInt(1), 0); s.execute("SAVEPOINT savepoint ON ROLLBACK RETAIN LOCKS ON ROLLBACK " + "RETAIN CURSORS"); s.executeUpdate("INSERT INTO savepoint VALUES(1,1)"); s.execute("RELEASE SAVEPOINT savepoint"); rs1 = s.executeQuery("select count(*) from savepoint"); rs1.next(); assertEquals("There should have been 1 rows in the table, but found " + rs1.getInt(1), rs1.getInt(1), 1); s.execute("SAVEPOINT release ON ROLLBACK RETAIN LOCKS ON ROLLBACK " + "RETAIN CURSORS"); s.executeUpdate("INSERT INTO savepoint VALUES(2,1)"); s.execute("ROLLBACK TO SAVEPOINT release"); rs1 = s.executeQuery("select count(*) from savepoint"); rs1.next(); assertEquals( "ERROR: There should have been 1 rows in the table, but found " + rs1.getInt(1), rs1.getInt(1), 1); s.execute("RELEASE SAVEPOINT release"); getConnection().rollback(); } /** * Test 24 Savepoint name can't exceed 128 characters */ public void testNameLengthMax128Chars() throws SQLException { try { getConnection() .setSavepoint( "MyName12345678901234567890123456789" + "01234567890123456789012345678901234567890123456789012345" + "678901234567890123456789012345678901234567890"); fail("FAIL 24 shouldn't be able to create a SQL savepoint with " + "name exceeding 128 characters"); } catch (SQLException se) { // Expected exception. assertSQLState("42622", se); } getConnection().rollback(); } /** Test 25 */ public void testNoSqlSavepointStartingWithSYSThroughJdbc() throws SQLException { try { getConnection().setSavepoint("SYSs2"); fail("FAIL 25 shouldn't be able to create a SQL savepoint starting with name SYS through jdbc"); } catch (SQLException se) { // Expected exception. assertSQLState("42939", se); } getConnection().rollback(); } /** * bug 4451 - Test 26a pass Null value to rollback bug 5374 - Passing a null * savepoint to rollback or release method used to give a npe in JCC it * should give a SQLException aying "Cannot rollback to a null savepoint" */ public void testRollbackNullSavepoint() throws SQLException { try { getConnection().rollback((Savepoint) null); fail("FAIL 26a rollback of null savepoint did not raise error "); } catch (SQLException se) { // Expected exception. if (usingEmbedded()) { assertSQLState("3B001", se); } else if (usingDerbyNetClient()) { assertSQLState("3B502", se); } } } /** * Test 26b pass Null value to releaseSavepoint */ public void testReleaseNullSavepoint() throws SQLException { try { getConnection().releaseSavepoint((Savepoint) null); fail("FAIL 26b release of null savepoint did not raise error "); } catch (SQLException se) { // Expected exception. if (usingEmbedded()) { assertSQLState("3B001", se); } else if (usingDerbyNetClient()) { assertSQLState("3B502", se); } } } /* * The following tests have nested savepoints through JDBC calls. When * coming through the network client these nested JDBC savepoint calls are * translated into equivalent SQL savepoint statements. But we do not allow * nested savepoints coming through SQL statements and hence these tests * can't be run under DRDA framework. */ /** * Test40 - We internally generate a unique name for unnamed savepoints. If * a named savepoint uses the currently used internal savepoint name, we * won't get an exception thrown for it because we prepend external saves * with "e." to avoid name conflicts. */ public void xtestNoConflictWithGeneratedName() throws SQLException { Connection con = getConnection(); con.setSavepoint(); con.setSavepoint("i.SAVEPT0"); con.rollback(); } /** * Test41 - Rolling back to a savepoint will release all the savepoints * created after that savepoint. */ public void xtestRollbackWillReleaseLaterSavepoints() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint(); Statement s = createStatement(); s.executeUpdate("INSERT INTO T1 VALUES(1,1)"); Savepoint savepoint2 = con.setSavepoint("s1"); s.executeUpdate("INSERT INTO T1 VALUES(2,1)"); Savepoint savepoint3 = con.setSavepoint("s2"); s.executeUpdate("INSERT INTO T1 VALUES(3,1)"); // Rollback to first named savepoint s1. This will internally release // the second named savepoint s2. con.rollback(savepoint2); assertTableRowCount("T1", 1); // Trying to release second named savepoint s2 should throw exception. try { con.releaseSavepoint(savepoint3); fail("FAIL 41a release of rolled back savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } // Trying to rollback second named savepoint s2 should throw exception. try { con.rollback(savepoint3); fail("FAIL 41b release of rolled back savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } // Release the unnamed named savepoint. con.rollback(savepoint1); assertTableRowCount("T1", 0); con.rollback(); } /** * Test42 - Rollback on a connection will release all the savepoints created * for that transaction */ public void xtestRollbackWillReleaseActiveSavepoints() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint(); con.rollback(); try { con.rollback(savepoint1); fail("FAIL 42 release of rolled back savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } } /** * Test42a - Commit on a connection will release all the savepoints created * for that transaction */ public void xtestCommitWillReleaseActiveSavepoints() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint(); con.commit(); try { con.rollback(savepoint1); fail("FAIL 42a Rollback after commit."); } catch (SQLException se) { // Expected exception. assertSQLState("3B001", se); } } /** * Test43 - After releasing a savepoint, should be able to reuse it. */ public void xtestReuseNameAfterRelease() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("s1"); try { con.setSavepoint("s1"); fail("Should not be able to set two savepoints with the same name"); } catch (SQLException se) { // Expected exception. if (usingEmbedded()) { assertSQLState("3B501", se); } else if (usingDerbyNetClient()) { assertSQLState("3B002", se); } } con.releaseSavepoint(savepoint1); con.setSavepoint("s1"); con.rollback(); } /** * Test 45 reuse savepoint name after rollback - should not work */ public void xtestReuseNameAfterRollback() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint("MyName"); con.rollback(savepoint1); try { con.setSavepoint("MyName"); fail("FAIL 45 reuse of savepoint name after rollback should fail"); } catch (SQLException se) { // Expected exception. if (usingEmbedded()) { assertSQLState("3B501", se); } else if (usingDerbyNetClient()) { assertSQLState("3B002", se); } } con.rollback(); } /** * Test 46 bug 5145 Cursors declared before and within the savepoint unit * will be closed when rolling back the savepoint */ public void xtestCursorsCloseOnRollback() throws SQLException { Connection con = getConnection(); Statement sWithHold = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, ResultSet.HOLD_CURSORS_OVER_COMMIT); Statement s = createStatement(); s.executeUpdate("DELETE FROM T1"); s.executeUpdate("INSERT INTO T1 VALUES(19,1)"); s.executeUpdate("INSERT INTO T1 VALUES(19,2)"); s.executeUpdate("INSERT INTO T1 VALUES(19,3)"); ResultSet rs1 = s.executeQuery("select * from t1"); rs1.next(); ResultSet rs1WithHold = sWithHold.executeQuery("select * from t1"); rs1WithHold.next(); Savepoint savepoint1 = con.setSavepoint(); ResultSet rs2 = s.executeQuery("select * from t1"); rs2.next(); ResultSet rs2WithHold = sWithHold.executeQuery("select * from t1"); rs2WithHold.next(); con.rollback(savepoint1); try {// resultset declared outside the savepoint unit should be // closed at this point after the rollback to savepoint rs1.next(); fail("FAIL 46 shouldn't be able to use a resultset (declared " + "before the savepoint unit) after the rollback to savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("XCL16", se); } try {// holdable resultset declared outside the savepoint unit should // be closed at this point after the rollback to savepoint rs1WithHold.next(); fail("FAIL 46 shouldn't be able to use a holdable resultset " + "(declared before the savepoint unit) after the rollback " + "to savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("XCL16", se); } try {// resultset declared within the savepoint unit should be closed // at this point after the rollback to savepoint rs2.next(); fail("FAIL 46 shouldn't be able to use a resultset (declared within " + "the savepoint unit) after the rollback to savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("XCL16", se); } try {// holdable resultset declared within the savepoint unit should // be closed at this point after the rollback to savepoint rs2WithHold.next(); fail("FAIL 46 shouldn't be able to use a holdable resultset " + "(declared within the savepoint unit) after the rollback " + "to savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("XCL16", se); } con.rollback(); } /** * Test 47 multiple tests for getSavepointId() */ public void xtestGetSavepoint() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint(); Savepoint savepoint2 = con.setSavepoint(); savepoint1.getSavepointId(); savepoint2.getSavepointId(); con.releaseSavepoint(savepoint2); savepoint2 = con.setSavepoint(); savepoint2.getSavepointId(); con.commit(); savepoint2 = con.setSavepoint(); savepoint2.getSavepointId(); con.rollback(); savepoint2 = con.setSavepoint(); savepoint2.getSavepointId(); con.rollback(); } /** * Test 48 */ public void xtestNestedSavepoints() throws SQLException { Connection con = getConnection(); Savepoint savepoint1 = con.setSavepoint(); Savepoint savepoint2 = con.setSavepoint(); Statement s = createStatement(); try { s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON ROLLBACK" + " RETAIN CURSORS"); fail("FAIL 48 shouldn't be able set SQL savepoint nested inside " + "JDBC/SQL savepoints"); } catch (SQLException se) { // Expected exception. assertSQLState("3B002", se); } // rollback JDBC savepoint but still can't have SQL savepoint because // there is still one JDBC savepoint con.releaseSavepoint(savepoint2); try { s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON ROLLBACK" + " RETAIN CURSORS"); fail("FAIL 48 Should have gotten exception for nested SQL savepoint"); } catch (SQLException se) { // Expected exception. assertSQLState("3B002", se); } con.releaseSavepoint(savepoint1); // rollback last JDBC savepoint and // now try SQL savepoint again s.executeUpdate("SAVEPOINT s1 ON ROLLBACK RETAIN LOCKS ON ROLLBACK " + "RETAIN CURSORS"); con.rollback(); } }
package com.ge.research.sadl.jena; import java.io.IOException; import java.math.BigDecimal; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.emf.ecore.EObject; import com.ge.research.sadl.model.CircularDefinitionException; import com.ge.research.sadl.model.ConceptIdentifier; import com.ge.research.sadl.model.ConceptName; import com.ge.research.sadl.model.ConceptName.ConceptType; import com.ge.research.sadl.model.ConceptName.RangeValueType; import com.ge.research.sadl.model.DeclarationExtensions; import com.ge.research.sadl.model.OntConceptType; import com.ge.research.sadl.processing.ISadlModelValidator; import com.ge.research.sadl.processing.ValidationAcceptor; import com.ge.research.sadl.reasoner.CircularDependencyException; import com.ge.research.sadl.reasoner.ConfigurationException; import com.ge.research.sadl.reasoner.InvalidNameException; import com.ge.research.sadl.reasoner.TranslationException; import com.ge.research.sadl.reasoner.utils.SadlUtils; import com.ge.research.sadl.sADL.BinaryOperation; import com.ge.research.sadl.sADL.BooleanLiteral; import com.ge.research.sadl.sADL.Constant; import com.ge.research.sadl.sADL.Declaration; import com.ge.research.sadl.sADL.ElementInList; import com.ge.research.sadl.sADL.Expression; import com.ge.research.sadl.sADL.Name; import com.ge.research.sadl.sADL.NumberLiteral; import com.ge.research.sadl.sADL.PropOfSubject; import com.ge.research.sadl.sADL.SadlDataType; import com.ge.research.sadl.sADL.SadlIntersectionType; import com.ge.research.sadl.sADL.SadlPrimitiveDataType; import com.ge.research.sadl.sADL.SadlPropertyCondition; import com.ge.research.sadl.sADL.SadlResource; import com.ge.research.sadl.sADL.SadlSimpleTypeReference; import com.ge.research.sadl.sADL.SadlTypeReference; import com.ge.research.sadl.sADL.SadlUnionType; import com.ge.research.sadl.sADL.StringLiteral; import com.ge.research.sadl.sADL.SubjHasProp; import com.ge.research.sadl.sADL.Sublist; import com.ge.research.sadl.sADL.UnaryExpression; import com.ge.research.sadl.sADL.Unit; import com.ge.research.sadl.sADL.ValueTable; import com.hp.hpl.jena.ontology.AllValuesFromRestriction; import com.hp.hpl.jena.ontology.DatatypeProperty; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.IntersectionClass; import com.hp.hpl.jena.ontology.ObjectProperty; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.ontology.Restriction; import com.hp.hpl.jena.ontology.UnionClass; import com.hp.hpl.jena.rdf.model.NodeIterator; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.OWL2; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; public class JenaBasedSadlModelValidator implements ISadlModelValidator { protected ValidationAcceptor issueAcceptor = null; protected OntModel theJenaModel = null; private DeclarationExtensions declarationExtensions = null; private List<String> comparisonOperators = Arrays.asList(">=",">","<=","<","==","!=","is","=","not","unique","in","contains","does",/*"not",*/"contain"); private List<String> numericOperators = Arrays.asList("*","+","/","-","%"); private EObject defaultContext; protected Map<EObject, TypeCheckInfo> expressionsValidated = new HashMap<EObject,TypeCheckInfo>(); private Map<EObject, Property> impliedPropertiesUsed = null; private IMetricsProcessor metricsProcessor = null; /** * This inner class captures the information about the left or right hand side of an expression that is subject * to type checking, e.g., and assignment, a comparison, etc. * */ public class TypeCheckInfo { private EObject context = null; // the parsetree element from which this is derived, // used to add an error, warning, or info so that a marker can be placed in the editor private ConceptIdentifier expressionType = null; // the identity, type, etc. of the concept that determines the type, // e.g., the property of a "<property> of <subject>" expression private ConceptIdentifier typeCheckType = null; // the type of the TypeCheckInfo which must match the other side of the expression, // e.g., the range of the property of a "<property> of <subject>" expression private RangeValueType rangeValueType = RangeValueType.CLASS_OR_DT; // the range type, one of RangeValueType.CLASS_OR_DT (Class or RDFDataType) // or LIST (a subclass of http://sadl.org/sadllistmodel#List) private List<ConceptName> implicitProperties = null; // Implied properties, if any, that apply to this expressionType private List<TypeCheckInfo> compoundTypes = null; // If this is a disjunction of multiple types, this contains the next // lower level of TypeCheckInfos in the hierarchy, e.g., a property whose // range is a union of classes or which is given range in multiple imports private String typeToExprRelationship = "range"; // the relationship between the typeCheckType and the expressionType, e.g., range (the default) public TypeCheckInfo(ConceptIdentifier eType) { setExpressionType(eType); } /* Constructor for compound types (union, e.g. range) */ public TypeCheckInfo(ConceptIdentifier eType, JenaBasedSadlModelValidator validator, EObject ctx) { setExpressionType(eType); context = ctx; if (ctx != null) { validator.expressionsValidated.put(ctx, this); } } public TypeCheckInfo(ConceptIdentifier eType, ConceptIdentifier tcType, JenaBasedSadlModelValidator validator, EObject ctx) { setExpressionType(eType); setTypeCheckType(tcType); context = ctx; if (ctx != null) { validator.expressionsValidated.put(ctx, this); } } public TypeCheckInfo(ConceptIdentifier eType, ConceptIdentifier tcType, List<ConceptName> impliedProps, JenaBasedSadlModelValidator validator, EObject ctx) { setExpressionType(eType); setTypeCheckType(tcType); if (impliedProps != null) { if (implicitProperties == null) { implicitProperties = impliedProps; } else { implicitProperties.addAll(impliedProps); } } context = ctx; if (ctx != null) { validator.expressionsValidated.put(ctx, this); } } public ConceptIdentifier getExpressionType() { return expressionType; } public void setExpressionType(ConceptIdentifier expressionType) { this.expressionType = expressionType; } private ConceptIdentifier getTypeCheckType() { return typeCheckType; } private void setTypeCheckType(ConceptIdentifier typeCheckType) { this.typeCheckType = typeCheckType; } public RangeValueType getRangeValueType() { return rangeValueType; } protected void setContext(JenaBasedSadlModelValidator validator, EObject ctx) { this.context = ctx; if (ctx != null) { validator.expressionsValidated.put(ctx, this); } } protected void setRangeValueType(RangeValueType rangeValueType) { this.rangeValueType = rangeValueType; } public String toString() { if (compoundTypes != null) { StringBuffer sb = new StringBuffer("Compound TypeCheckInfo(["); for (int i = 0; i < compoundTypes.size(); i++) { if (i > 0) { sb.append(","); } sb.append(compoundTypes.get(i).toString()); } sb.append("]"); return sb.toString(); } else { StringBuffer sb = new StringBuffer("TypeCheckInfo("); if (getRangeValueType() != null && !getRangeValueType().equals(RangeValueType.CLASS_OR_DT)) { sb.append(getRangeValueType().toString()); sb.append(" of values of type, "); } sb.append(expressionType.toString()); sb.append(", "); sb.append(typeCheckType.toString()); sb.append(")"); if (getImplicitProperties() != null) { if (getImplicitProperties().size() > 1) sb.append(" (has implied properties "); else sb.append(" (has implied property "); sb.append(implicitPropertiesToString(getImplicitProperties())); sb.append(")"); } return sb.toString(); } } private Object implicitPropertiesToString(List<ConceptName> iprops) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < iprops.size(); i++) { if (i > 0) sb.append(", "); sb.append(getImplicitProperties().get(0).toFQString()); } return sb.toString(); } public void addImplicitProperty(ConceptName implicitProp) { if (implicitProp != null) { if (implicitProperties == null) { implicitProperties = new ArrayList<ConceptName>(); } if (!implicitProperties.contains(implicitProp)) { implicitProperties.add(implicitProp); } } } public List<ConceptName> getImplicitProperties() { return implicitProperties; } private List<TypeCheckInfo> getCompoundTypes() { return compoundTypes; } private void addCompoundType(TypeCheckInfo additionalType) { if (compoundTypes == null) { compoundTypes= new ArrayList<TypeCheckInfo>(); } if (!compoundTypes.contains(additionalType)) { compoundTypes.add(additionalType); } } private String getTypeToExprRelationship() { return typeToExprRelationship; } private void setTypeToExprRelationship(String typeToExprRelationship) { this.typeToExprRelationship = typeToExprRelationship; } } public JenaBasedSadlModelValidator(ValidationAcceptor issueAcceptor, OntModel theJenaModel, DeclarationExtensions declarationExtensions, IMetricsProcessor metricsProcessor){ this.issueAcceptor = issueAcceptor; this.theJenaModel = theJenaModel; this.declarationExtensions = declarationExtensions; this.metricsProcessor = metricsProcessor; } public boolean validate(Expression expr, String xsdType, String op, StringBuilder errorMessageBuilder) { List<String> operations = Arrays.asList(op.split("\\s+")); TypeCheckInfo exprTypeCheckInfo; try { exprTypeCheckInfo = getType(expr); ConceptName numberLiteralConceptName = new ConceptName(XSD.xint.getURI()); numberLiteralConceptName.setType(ConceptType.RDFDATATYPE); TypeCheckInfo xsdTypeCheckInfo = new TypeCheckInfo(numberLiteralConceptName, numberLiteralConceptName, this, null); if(!compareTypes(operations, expr, null, exprTypeCheckInfo, xsdTypeCheckInfo)){ createErrorMessage(errorMessageBuilder, exprTypeCheckInfo, xsdTypeCheckInfo, op); return false; } } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DontTypeCheckException e) { return true; } return true; } public boolean validate(BinaryOperation expression, StringBuilder errorMessageBuilder) { setDefaultContext(expression); Expression leftExpression = expression.getLeft(); Expression rightExpression = expression.getRight(); List<String> operations = Arrays.asList(expression.getOp().split("\\s+")); if(skipOperations(operations)){ return true; } try { TypeCheckInfo leftTypeCheckInfo = getType(leftExpression); TypeCheckInfo rightTypeCheckInfo = getType(rightExpression); if(!compareTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo)){ createErrorMessage(errorMessageBuilder, leftTypeCheckInfo, rightTypeCheckInfo, expression.getOp()); return false; } return true; } catch (InvalidNameException e) { issueAcceptor.addError("An invalid name exception occurred while type-checking this expression.", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (TranslationException e) { issueAcceptor.addError("A translation exception exception occurred while type-checking this expression.", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (URISyntaxException e) { issueAcceptor.addError("An URI syntax exception occurred while type-checking this expression.", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (IOException e) { issueAcceptor.addError("An IO exception occurred while type-checking this expression.", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (ConfigurationException e) { issueAcceptor.addError("A configuration exception occurred while type-checking this expression.", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (NullPointerException e){ //issueAcceptor.addError("A null pointer exception occurred while type-checking this expression.", expression); } catch (DontTypeCheckException e) { return true; } return false; } public boolean validate(Expression leftExpression, Expression rightExpression, String op, StringBuilder errorMessageBuilder) { List<String> operations = Arrays.asList(op.split("\\s+")); TypeCheckInfo leftTypeCheckInfo = null; TypeCheckInfo rightTypeCheckInfo = null; try { leftTypeCheckInfo = getType(leftExpression); } catch (InvalidNameException e) { issueAcceptor.addError("An invalid name exception occurred while type-checking this expression.", leftExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (TranslationException e) { issueAcceptor.addError("A translation exception exception occurred while type-checking this expression.", leftExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (URISyntaxException e) { if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } issueAcceptor.addError("An URI syntax exception occurred while type-checking this expression.", leftExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (IOException e) { issueAcceptor.addError("An IO exception occurred while type-checking this expression.", leftExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (ConfigurationException e) { issueAcceptor.addError("A configuration exception occurred while type-checking this expression.", leftExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (NullPointerException e){ //issueAcceptor.addError("A null pointer exception occurred while type-checking this expression.", expression); } catch (DontTypeCheckException e) { return true; } try { rightTypeCheckInfo = getType(rightExpression); } catch (InvalidNameException e) { issueAcceptor.addError("An invalid name exception occurred while type-checking this expression.", rightExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (TranslationException e) { issueAcceptor.addError("A translation exception exception occurred while type-checking this expression.", rightExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (URISyntaxException e) { issueAcceptor.addError("An URI syntax exception occurred while type-checking this expression.", rightExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (IOException e) { issueAcceptor.addError("An IO exception occurred while type-checking this expression.", rightExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (ConfigurationException e) { issueAcceptor.addError("A configuration exception occurred while type-checking this expression.", rightExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } e.printStackTrace(); } catch (NullPointerException e){ //issueAcceptor.addError("A null pointer exception occurred while type-checking this expression.", expression); } catch (DontTypeCheckException e) { return true; } try { if(!compareTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo)){ createErrorMessage(errorMessageBuilder, leftTypeCheckInfo, rightTypeCheckInfo, op); return false; } } catch (InvalidNameException e) { issueAcceptor.addError("An invalid name exception occurred while type-checking this expression.", rightExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.INVALID_EXPRESSION_URI); } e.printStackTrace(); } catch (DontTypeCheckException e) { return true; } return true; } private void createErrorMessage(StringBuilder errorMessageBuilder, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo, String operation) { String[] leftDesc = getTypeCheckInfoDescription(leftTypeCheckInfo); String[] rightDesc = getTypeCheckInfoDescription(rightTypeCheckInfo); if (leftDesc == null) { errorMessageBuilder.append("Undetermined left type"); } else { if (leftDesc.length > 0) { errorMessageBuilder.append(leftDesc[0]); } if (leftDesc.length > 1) { errorMessageBuilder.append(" "); errorMessageBuilder.append(leftDesc[1]); } } if (comparisonOperators.contains(operation)) { errorMessageBuilder.append(" cannot be compared (" + operation + ") with "); } else { errorMessageBuilder.append(" cannot operate (" + operation + ") with "); } if (rightDesc == null) { errorMessageBuilder.append("Undetermined right type"); } else { if (rightDesc.length > 0) { errorMessageBuilder.append(rightDesc[0]); } if (rightDesc.length > 1) { errorMessageBuilder.append(" "); errorMessageBuilder.append(rightDesc[1]); } } errorMessageBuilder.append("."); } private String[] getTypeCheckInfoDescription(TypeCheckInfo typeCheckInfo) { if (typeCheckInfo == null) { String[] result = new String[1]; result[0] = "No type check info generated"; return result; } else { StringBuilder sb1 = new StringBuilder();; StringBuilder sb2 = null; ConceptIdentifier typeExpr = typeCheckInfo.getExpressionType(); sb1.append(typeExpr.toString()); if (typeExpr instanceof ConceptName) { ConceptType ct = ((ConceptName)typeExpr).getType(); if (ct.equals(ConceptType.INDIVIDUAL)) { sb1.append(", an instance of type "); sb2 = new StringBuilder(); } else if (ct.equals(ConceptType.ONTCLASS)) { sb1.append(", a class "); } else if (ct.equals(ConceptType.RDFDATATYPE)) { sb1.append(", an RDF datatype "); sb2= new StringBuilder(); } else if (ct.equals(ConceptType.RDFPROPERTY)) { sb1.append(", an RDF property "); if (rdfPropertyTypeCheckInfoHasRange(typeCheckInfo)) { sb1.append("with "); sb1.append(typeCheckInfo.getTypeToExprRelationship()); sb1.append(" "); } sb2= new StringBuilder(); } else if (ct.equals(ConceptType.ANNOTATIONPROPERTY)) { sb1.append(", an annotation property "); } else if (ct.equals(ConceptType.DATATYPEPROPERTY)) { sb1.append(", a datatype property with "); sb1.append(typeCheckInfo.getTypeToExprRelationship()); sb1.append(" "); sb2 = new StringBuilder(); } else if (ct.equals(ConceptType.OBJECTPROPERTY)) { sb1.append(", an object property with "); sb1.append(typeCheckInfo.getTypeToExprRelationship()); sb1.append(" "); sb2= new StringBuilder(); } else if (ct.equals(ConceptType.VARIABLE)) { sb1.append(", a variable of type "); sb2 = new StringBuilder(); } } if (typeCheckInfo.getCompoundTypes() != null) { if (sb2 == null) sb2 = new StringBuilder(); for (int i = 0; i < typeCheckInfo.getCompoundTypes().size(); i++) { TypeCheckInfo tci = typeCheckInfo.getCompoundTypes().get(i); String[] tciresult = getTypeCheckInfoDescription(tci); if (tciresult != null && tciresult.length > 1) { if (i > 0) sb2.append(" or "); sb2.append(tciresult[1]); } } } else { if (typeCheckInfo.getRangeValueType().equals(RangeValueType.LIST)) { sb2.append("a List of values of type "); } if (sb2 != null && typeCheckInfo.getTypeCheckType() != null) { sb2.append(typeCheckInfo.getTypeCheckType().toString()); } } String[] result = sb2 != null ? new String[2] : new String[1]; result[0] = sb1.toString(); if (sb2 != null) { result[1] = sb2.toString(); } return result; } // String leftName = leftTypeCheckInfo != null ? leftTypeCheckInfo.expressionType != null ? leftTypeCheckInfo.expressionType.toString() : "UNIDENTIFIED" : "UNIDENTIFIED"; // String rightName = rightTypeCheckInfo != null ? rightTypeCheckInfo.expressionType != null ? rightTypeCheckInfo.expressionType.toString() : "UNIDENTIFIED" : "UNIDENTIFIED"; // String leftType; // String leftRange; // if (leftTypeCheckInfo == null) { // leftType = "UNIDENTIFIED"; // leftRange = "UNIDENTIFIED"; // else if (leftTypeCheckInfo.compoundTypes == null) { // leftType = leftTypeCheckInfo.typeCheckType != null ? leftTypeCheckInfo.typeCheckType.toString() : "UNIDENTIFIED"; // leftRange = leftTypeCheckInfo.rangeValueType != null ? leftTypeCheckInfo.rangeValueType.toString() : "UNIDENTIFIED"; // else { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < leftTypeCheckInfo.getCompoundType().size(); i++) { // if (i > 0) { // sb.append(" or "); // TypeCheckInfo tic = leftTypeCheckInfo.getCompoundType().get(i); // sb.append(tic != null ? tic.typeCheckType != null ? tic.typeCheckType.toString() : "UNIDENTIFIED" : "UNIDENTIFIED"); // leftType = sb.toString(); // sb = new StringBuilder(); // for (int i = 0; i < leftTypeCheckInfo.getCompoundType().size(); i++) { // if (i > 0) { // sb.append(" or "); // TypeCheckInfo tic = leftTypeCheckInfo.getCompoundType().get(i); // sb.append(tic != null ? tic.rangeValueType != null ? tic.rangeValueType.toString() : "UNIDENTIFIED" : "UNIDENTIFIED"); // leftRange = sb.toString(); // return null; } private boolean rdfPropertyTypeCheckInfoHasRange(TypeCheckInfo typeCheckInfo) { if (typeCheckInfo.getTypeCheckType() != null) { return true; } if (typeCheckInfo.getCompoundTypes() != null) { for (int i = 0; i < typeCheckInfo.getCompoundTypes().size(); i++) { TypeCheckInfo next = typeCheckInfo.getCompoundTypes().get(i); boolean b = rdfPropertyTypeCheckInfoHasRange(next); if (b) { return true; } } } return false; } protected boolean skipOperations(List<String> operations) { if(operations.contains("and") || operations.contains("or")){ return true; } return false; } protected TypeCheckInfo getType(Expression expression) throws InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException{ if (expressionsValidated.containsKey(expression)) { return expressionsValidated.get(expression); } if(expression instanceof Name){ return getType((Name)expression); } else if(expression instanceof Declaration){ SadlTypeReference decltype = ((Declaration)expression).getType(); return getType(decltype); //Need to return passing case for time being // ConceptName declarationConceptName = new ConceptName("TODO"); // return new TypeCheckInfo(declarationConceptName, declarationConceptName); } else if(expression instanceof StringLiteral){ ConceptName stringLiteralConceptName = new ConceptName(XSD.xstring.getURI()); stringLiteralConceptName.setType(ConceptType.RDFDATATYPE); return new TypeCheckInfo(stringLiteralConceptName, stringLiteralConceptName, this, expression); } else if(expression instanceof NumberLiteral || expression instanceof Unit){ BigDecimal value; if (expression instanceof Unit) { value = ((Unit)expression).getValue().getValue(); } else { value = ((NumberLiteral)expression).getValue(); } ConceptName numberLiteralConceptName = null; if (value.stripTrailingZeros().scale() <= 0 || value.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0) { numberLiteralConceptName = new ConceptName(XSD.xint.getURI()); } else { numberLiteralConceptName = new ConceptName(XSD.decimal.getURI()); } numberLiteralConceptName.setType(ConceptType.RDFDATATYPE); return new TypeCheckInfo(numberLiteralConceptName, numberLiteralConceptName, this, expression); } else if(expression instanceof BooleanLiteral){ ConceptName booleanLiteralConceptName = new ConceptName(XSD.xboolean.getURI()); booleanLiteralConceptName.setType(ConceptType.RDFDATATYPE); return new TypeCheckInfo(booleanLiteralConceptName, booleanLiteralConceptName, this, expression); } else if(expression instanceof Constant){ //What do we do about the rest of the constants? /*'--' | 'a'? 'type' ;*/ String constant = ((Constant) expression).getConstant(); if(constant.equals("PI")){ ConceptName constantConceptName = new ConceptName(XSD.decimal.getURI()); constantConceptName.setType(ConceptType.DATATYPEPROPERTY); return new TypeCheckInfo(constantConceptName, constantConceptName, this, expression); } else if(constant.equals("length") || constant.equals("count") || constant.equals("index")){ ConceptName constantConceptName = new ConceptName(XSD.xint.getURI()); constantConceptName.setType(ConceptType.DATATYPEPROPERTY); return new TypeCheckInfo(constantConceptName, constantConceptName, this, expression); } else if(constant.contains("element") && (constant.contains("first") || constant.contains("last"))){ //Handle list types??? ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, declarationConceptName, this, expression); } else if(constant.equals("None")){ ConceptName constantConceptName = new ConceptName(constant); constantConceptName.setType(ConceptType.INDIVIDUAL); return new TypeCheckInfo(constantConceptName, constantConceptName, this, expression); } } else if(expression instanceof ValueTable){ ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, declarationConceptName, this, expression); } else if(expression instanceof PropOfSubject){ return getType((PropOfSubject)expression); } else if(expression instanceof SubjHasProp){ return getType(((SubjHasProp)expression).getLeft()); } else if(expression instanceof UnaryExpression){ return getType(((UnaryExpression) expression).getExpr()); } else if(expression instanceof ElementInList){ Expression el = ((ElementInList)expression).getElement(); if (el instanceof PropOfSubject) { return getType(((PropOfSubject)el).getRight()); } else { issueAcceptor.addError("Unhandled element type in element in list construct: " + el.getClass().getCanonicalName() + "; please report", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } } } else if(expression instanceof BinaryOperation){ List<String> operations = Arrays.asList(((BinaryOperation) expression).getOp().split("\\s+")); TypeCheckInfo leftTypeCheckInfo = getType(((BinaryOperation) expression).getLeft()); TypeCheckInfo rightTypeCheckInfo = getType(((BinaryOperation) expression).getRight()); TypeCheckInfo binopreturn = combineTypes(operations, ((BinaryOperation) expression).getLeft(), ((BinaryOperation) expression).getRight(), leftTypeCheckInfo, rightTypeCheckInfo); if (binopreturn != null) { return binopreturn; } if (numericOperators.contains(((BinaryOperation) expression).getOp())) { ConceptName decimalLiteralConceptName = new ConceptName(XSD.decimal.getURI()); return new TypeCheckInfo(decimalLiteralConceptName, decimalLiteralConceptName, this, expression); } else { // by default assume boolean binary operation ConceptName booleanLiteralConceptName = new ConceptName(XSD.xboolean.getURI()); return new TypeCheckInfo(booleanLiteralConceptName, booleanLiteralConceptName, this, expression); } } else if (expression instanceof Sublist) { // the type is the type of the list return getType((((Sublist)expression).getList())); } issueAcceptor.addError("This expression cannot be decomposed into a known type", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } return null; } private TypeCheckInfo getType(SadlTypeReference expression) throws DontTypeCheckException { if (expression instanceof SadlIntersectionType) { return getType((SadlIntersectionType)expression); } else if (expression instanceof SadlPrimitiveDataType) { return getType((SadlPrimitiveDataType)expression); } else if (expression instanceof SadlPropertyCondition) { return getType((SadlPropertyCondition)expression); } else if (expression instanceof SadlSimpleTypeReference) { return getType((SadlSimpleTypeReference)expression); } else if (expression instanceof SadlUnionType) { return getType((SadlUnionType)expression); } issueAcceptor.addError("Unexpected type reference type: " + expression.getClass().getCanonicalName(), expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, declarationConceptName, this, expression); } private TypeCheckInfo getType(SadlIntersectionType expression) { ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, declarationConceptName, this, expression); } private TypeCheckInfo getType(SadlPrimitiveDataType expression) { TypeCheckInfo tci = getType(expression.getPrimitiveType()); tci.setContext(this, expression); return tci; } private TypeCheckInfo getType(SadlDataType primitiveType) { String nm = primitiveType.getName(); ConceptName cn = new ConceptName(XSD.getURI() + nm); return new TypeCheckInfo(cn, cn, this, null); } private TypeCheckInfo getType(SadlPropertyCondition expression) { ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, declarationConceptName, this, expression); } private TypeCheckInfo getType(SadlSimpleTypeReference expression) throws DontTypeCheckException { return getType(expression.getType()); } private TypeCheckInfo getType(SadlUnionType expression) { ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, declarationConceptName, this, expression); } private TypeCheckInfo getType(PropOfSubject expression) throws InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException{ Expression predicate = expression.getLeft(); Expression subject = expression.getRight(); if (predicate instanceof Constant) { String cnstval = ((Constant)predicate).getConstant(); if (cnstval.equals("length") || cnstval.equals("count") || cnstval.equals("index")) { ConceptName nlcn = new ConceptName(XSD.xint.getURI()); nlcn.setType(ConceptType.RDFDATATYPE); return new TypeCheckInfo(nlcn, nlcn, this, expression); } else if (cnstval.equals("first element")) { } else if (cnstval.equals("last element")) { } else { issueAcceptor.addError("Unhandled constant property", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } } } if (subject instanceof Name) { // check for AllValuesFrom restriction before defaulting to checking property range TypeCheckInfo predicateType = getTypeFromRestriction(subject, predicate); if (predicateType != null) { if (subject instanceof PropOfSubject) { checkEmbeddedPropOfSubject(subject, predicate); } return predicateType; } } TypeCheckInfo predicateType = getType(predicate); if (subject instanceof PropOfSubject) { checkEmbeddedPropOfSubject(subject, predicate); } return predicateType; } private void checkEmbeddedPropOfSubject(Expression subject, Expression predicate) throws InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException { if (predicate instanceof Name) { String propuri = declarationExtensions.getConceptUri(((Name)predicate).getName()); Property prop = theJenaModel.getProperty(propuri); TypeCheckInfo subjType = getType(subject); StmtIterator domainItr = prop.listProperties(RDFS.domain); boolean domainMatched = false; List<Resource> domainList = null; while (domainItr.hasNext()) { RDFNode dmn = domainItr.next().getObject(); if (dmn instanceof Resource) { if (subjType.getTypeCheckType() != null && subjType.getTypeCheckType().toString().equals(((Resource) dmn).getURI())) { domainItr.close(); domainMatched = true; break; } if (domainList == null) domainList = new ArrayList<Resource>(); domainList.add((Resource) dmn); } } if (!domainMatched) { for (int i = 0; domainList != null && i < domainList.size(); i++) { Resource dmn = domainList.get(i); if ((dmn instanceof OntResource || dmn.canAs(OntResource.class)) && subjType.getTypeCheckType() != null) { try { OntClass subj = theJenaModel.getOntClass(subjType.getTypeCheckType().toString()); if (subj != null && SadlUtils.classIsSubclassOf(subj, dmn.as(OntResource.class),true, null)) { domainMatched = true; break; } } catch (CircularDependencyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } if (!domainMatched && domainList != null) { OntConceptType oct; try { oct = declarationExtensions.getOntConceptType(((Name)predicate).getName()); StringBuilder errorMessageBuilder = new StringBuilder(); TypeCheckInfo leftTypeCheckInfo; if (domainList.size() == 1) { ConceptName cn1 = createTypedConceptName(propuri, oct); leftTypeCheckInfo = new TypeCheckInfo(createTypedConceptName(propuri, oct), createTypedConceptName(domainList.get(0).getURI(), OntConceptType.CLASS), this, predicate); leftTypeCheckInfo.setTypeToExprRelationship("domain"); } else { leftTypeCheckInfo = new TypeCheckInfo(createTypedConceptName(propuri, oct), this, predicate); for (int i = 0; i < domainList.size(); i++) { TypeCheckInfo tci = new TypeCheckInfo(createTypedConceptName(propuri, oct), createTypedConceptName(domainList.get(0).getURI(), OntConceptType.CLASS), this, predicate); leftTypeCheckInfo.addCompoundType(tci); leftTypeCheckInfo.setTypeToExprRelationship("domain"); } } createErrorMessage(errorMessageBuilder, leftTypeCheckInfo, subjType, "chained property"); issueAcceptor.addError(errorMessageBuilder.toString(), predicate); } catch (CircularDefinitionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private TypeCheckInfo getTypeFromRestriction(Expression subject, Expression predicate) { if (subject instanceof Name && predicate instanceof Name) { String subjuri = declarationExtensions.getConceptUri(((Name)subject).getName()); Resource subj = theJenaModel.getResource(subjuri); if (subj != null) { if (!(subj instanceof OntClass) && subj.canAs(Individual.class)) { subj = subj.as(Individual.class).getRDFType(true); } if (subj != null && subj.canAs(OntClass.class)){ String propuri = declarationExtensions.getConceptUri(((Name)predicate).getName()); Property prop = theJenaModel.getProperty(propuri); // now look for restrictions on "range" StmtIterator sitr = theJenaModel.listStatements(null, OWL.onProperty, prop); while (sitr.hasNext()) { Statement stmt = sitr.nextStatement(); Resource sr = stmt.getSubject(); if (sr.canAs(OntClass.class) && subj.as(OntClass.class).hasSuperClass(sr.as(OntClass.class))) { if (sr.as(OntClass.class).asRestriction().isAllValuesFromRestriction()) { Resource avf = sr.as(OntClass.class).asRestriction().asAllValuesFromRestriction().getAllValuesFrom(); if (avf.isLiteral()) { return new TypeCheckInfo(new ConceptName(avf.getURI()), new ConceptName(propuri), this, predicate); } else if (avf.isURIResource()){ List<ConceptName> impliedProperties = getImpliedProperties(avf); return new TypeCheckInfo(new ConceptName(propuri), new ConceptName(avf.getURI()), impliedProperties, this, predicate); } } } } } } } return null; } private TypeCheckInfo getType(Name expression) throws InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException { SadlResource qnm =expression.getName(); if (qnm.eIsProxy()) { // this is a proxy so we don't know its type issueAcceptor.addWarning("Function is not defined so return type is unknown, can't do type checking", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.WARNING_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } throw new DontTypeCheckException(); } return getType(qnm); } protected TypeCheckInfo getType(SadlResource qnm) throws DontTypeCheckException{ String conceptUri = declarationExtensions.getConceptUri(qnm); EObject expression = qnm.eContainer(); if (conceptUri == null) { issueAcceptor.addError("Unidentified expression", (expression != null ? expression : qnm)); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } } OntConceptType conceptType; try { conceptType = declarationExtensions.getOntConceptType(qnm); } catch (CircularDefinitionException e) { conceptType = e.getDefinitionType(); issueAcceptor.addError(e.getMessage(), expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } } if(conceptType.equals(OntConceptType.CLASS)){ ConceptName conceptName = createTypedConceptName(conceptUri, conceptType); return new TypeCheckInfo(conceptName, conceptName, this, expression); } else if(conceptType.equals(OntConceptType.DATATYPE_PROPERTY)){ return getNameProperty(ConceptType.DATATYPEPROPERTY, conceptUri, expression); } else if(conceptType.equals(OntConceptType.CLASS_PROPERTY)){ return getNameProperty(ConceptType.OBJECTPROPERTY, conceptUri, expression); } else if (conceptType.equals(OntConceptType.RDF_PROPERTY)) { TypeCheckInfo rdfpropcheckinfo = getNameProperty(ConceptType.RDFPROPERTY, conceptUri, expression); if (rdfpropcheckinfo != null) { return rdfpropcheckinfo; } throw new DontTypeCheckException(); } else if(conceptType.equals(OntConceptType.INSTANCE)){ //Direct type to which the instance belongs Individual individual = theJenaModel.getIndividual(conceptUri); if(individual == null){ issueAcceptor.addError("Unidentified expression", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } return null; } ConceptName instConceptName = new ConceptName(conceptUri); instConceptName.setType(ConceptType.INDIVIDUAL); // TODO could belong to multiple classes ExtendedIterator<Resource> typeitr = individual.listRDFTypes(true); TypeCheckInfo compoundTci = null; TypeCheckInfo tci = null; while (typeitr.hasNext()) { Resource ontResource = typeitr.next(); if(!ontResource.isURIResource()){ if (isSadlTypedList(ontResource) && ontResource.canAs(OntClass.class)) { tci = getSadlTypedListTypeCheckInfo(ontResource.as(OntClass.class), null, expression, null); } else { ConceptName declarationConceptName = new ConceptName("TODO"); declarationConceptName.setType(ConceptType.ONTCLASS); tci = new TypeCheckInfo(instConceptName, instConceptName, this, expression); } } else { String uriOfTypeToBeReturned = ontResource.getURI(); ConceptName conceptName = new ConceptName(uriOfTypeToBeReturned); conceptName.setType(ConceptType.ONTCLASS); tci = new TypeCheckInfo(instConceptName, conceptName, this, expression); } if (typeitr.hasNext() && compoundTci == null) { compoundTci = new TypeCheckInfo(instConceptName, this, expression); } if (compoundTci != null) { if (!compoundTci.getCompoundTypes().contains(tci)) { compoundTci.addCompoundType(tci); } } } if (compoundTci != null) { return compoundTci; } return tci; } else if(conceptType.equals(OntConceptType.VARIABLE)){ String nm = declarationExtensions.getConcreteName(qnm); return getVariableType(ConceptType.VARIABLE, nm, expression); } else if(conceptType.equals(OntConceptType.ANNOTATION_PROPERTY)){ //This matches any type. ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, declarationConceptName, this, expression); } ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, declarationConceptName, this, expression); } private ConceptName createTypedConceptName(String conceptUri, OntConceptType conceptType) { ConceptName cn = new ConceptName(conceptUri); if (conceptType.equals(OntConceptType.CLASS)) { cn.setType(ConceptType.ONTCLASS); } else if (conceptType.equals(OntConceptType.ANNOTATION_PROPERTY)) { cn.setType(ConceptType.ANNOTATIONPROPERTY); } else if (conceptType.equals(OntConceptType.DATATYPE_PROPERTY)) { cn.setType(ConceptType.DATATYPEPROPERTY); } else if (conceptType.equals(OntConceptType.INSTANCE)) { cn.setType(ConceptType.INDIVIDUAL); } else if (conceptType.equals(OntConceptType.CLASS_PROPERTY)) { cn.setType(ConceptType.OBJECTPROPERTY); } else if (conceptType.equals(OntConceptType.DATATYPE)) { cn.setType(ConceptType.RDFDATATYPE); } else if (conceptType.equals(OntConceptType.RDF_PROPERTY)) { cn.setType(ConceptType.RDFPROPERTY); } else if (conceptType.equals(OntConceptType.VARIABLE)) { cn.setType(ConceptType.VARIABLE); } return cn; } protected TypeCheckInfo getNameProperty(ConceptType propertyType, String conceptUri, EObject expression) throws DontTypeCheckException { OntProperty property = theJenaModel.getOntProperty(conceptUri); if(property == null){ issueAcceptor.addError("Unidentified expression", expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } return null; } ConceptName propConceptName = new ConceptName(conceptUri); propConceptName.setType(propertyType); return getTypeInfoFromRange(propConceptName, property, expression); } private TypeCheckInfo getTypeInfoFromRange(ConceptName propConceptName, Property property, EObject expression) throws DontTypeCheckException { ConceptType propertyType = propConceptName.getType(); StmtIterator sitr = theJenaModel.listStatements(property, RDFS.range, (RDFNode)null); if (sitr.hasNext()) { TypeCheckInfo compoundTci = null; TypeCheckInfo tci = null; while (sitr.hasNext()) { RDFNode first = sitr.next().getObject(); if(first.isURIResource()){ tci = createTypeCheckInfoForPropertyRange(first, propConceptName, expression, propertyType); } else if (isSadlTypedList(first)) { // get type restriction on "first" property--this is the type tci = getSadlTypedListTypeCheckInfo(first.as(OntClass.class), propConceptName, expression, propertyType); } else { tci = createTypeCheckInfoForNonUriPropertyRange(first, propConceptName, expression, propertyType); } if (tci != null) { if (sitr.hasNext() && compoundTci == null) { compoundTci = new TypeCheckInfo(propConceptName, this, expression); } if (compoundTci != null) { compoundTci.addCompoundType(tci); } } } sitr.close(); if (compoundTci != null) { return compoundTci; } return tci; } else { // no range on this property, check super properties StmtIterator sitr2 = theJenaModel.listStatements(property, RDFS.subPropertyOf, (RDFNode)null); while (sitr2.hasNext()) { RDFNode psuper = sitr2.next().getObject(); if (psuper.isLiteral()) { TypeCheckInfo superTCInfo = getNameProperty(propertyType, psuper.asResource().getURI(), expression); if (superTCInfo != null) { sitr2.close(); return superTCInfo; } } } } return null; } private TypeCheckInfo createTypeCheckInfoForNonUriPropertyRange(RDFNode rng, ConceptName propConceptName, EObject expression, ConceptType propertyType) { TypeCheckInfo tci = null; if (isSadlTypedList(rng)) { // get type restriction on "first" property--this is the type tci = getSadlTypedListTypeCheckInfo(rng.as(OntClass.class), propConceptName, expression, propertyType); } else if (rng.canAs(UnionClass.class)){ UnionClass ucls = rng.as(UnionClass.class); try { ExtendedIterator<? extends OntClass> eitr = ucls.listOperands(); if (eitr.hasNext()) { tci = new TypeCheckInfo(propConceptName, this, expression); while (eitr.hasNext()) { OntClass uclsmember = eitr.next(); if (uclsmember.isURIResource()) { TypeCheckInfo utci = createTypeCheckInfoForPropertyRange(uclsmember, propConceptName, expression, propertyType); tci.addCompoundType(utci); } else { TypeCheckInfo utci = createTypeCheckInfoForNonUriPropertyRange(uclsmember, propConceptName, expression, propertyType); tci.addCompoundType(utci); } } } } catch (Exception e) { issueAcceptor.addError("Unexpected error processing type check for union range: " + e.getMessage(), getDefaultContext()); } } else if (rng.canAs(IntersectionClass.class)){ issueAcceptor.addWarning("type checking doesn't handle intersection", expression); } else if (rng.canAs(Restriction.class)){ issueAcceptor.addWarning("type checking doesn't handle restrictions", expression); } return tci; } private TypeCheckInfo getSadlTypedListTypeCheckInfo(OntClass lst, ConceptName propConceptName, EObject expression, ConceptType propertyType) { ExtendedIterator<OntClass> eitr = ((OntClass)lst.as(OntClass.class)).listSuperClasses(true); while (eitr.hasNext()) { OntClass cls = eitr.next(); if (cls.isRestriction()) { if (cls.canAs(AllValuesFromRestriction.class)) { if (((AllValuesFromRestriction)cls.as(AllValuesFromRestriction.class)).onProperty(theJenaModel.getProperty(JenaBasedSadlModelProcessor.SADL_LIST_MODEL_FIRST_URI))) { Resource avf = ((AllValuesFromRestriction)cls.as(AllValuesFromRestriction.class)).getAllValuesFrom(); eitr.close(); if (avf.isURIResource()) { List<ConceptName> impliedProperties = getImpliedProperties(avf.asResource()); ConceptName rangeConceptName = new ConceptName(avf.getURI()); if (propertyType != null && propertyType.equals(ConceptType.DATATYPEPROPERTY)) { rangeConceptName.setType(ConceptType.RDFDATATYPE); rangeConceptName.setRangeValueType(propConceptName.getRangeValueType()); } else { rangeConceptName.setType(ConceptType.ONTCLASS); } TypeCheckInfo tci = new TypeCheckInfo(propConceptName, rangeConceptName, impliedProperties, this, expression); tci.setRangeValueType(RangeValueType.LIST); return tci; } } } } } return null; } private boolean isSadlTypedList(RDFNode node) { if (node instanceof Resource && ((Resource)node).canAs(OntClass.class)) { OntClass cls = ((Resource)node).as(OntClass.class); if (cls.hasSuperClass(theJenaModel.getOntResource(JenaBasedSadlModelProcessor.SADL_LIST_MODEL_LIST_URI))) { return true; } } return false; } private TypeCheckInfo createTypeCheckInfoForPropertyRange(RDFNode first, ConceptName propConceptName, EObject expression, ConceptType propertyType) { TypeCheckInfo tci; ConceptName rangeConceptName = new ConceptName(first.asResource().getURI()); if (propertyType.equals(ConceptType.DATATYPEPROPERTY)) { rangeConceptName.setType(ConceptType.RDFDATATYPE); OntResource range; try { range = theJenaModel.getOntResource(rangeConceptName.getUri()); if (theJenaModel.listStatements(range, RDF.type, RDFS.Datatype).hasNext()) { // this is a user-defined datatype RDFNode rngEC = range.listPropertyValues(OWL.equivalentClass).next(); if (rngEC != null && rngEC.canAs(OntResource.class)) { RDFNode baseType = rngEC.as(OntResource.class).listPropertyValues(OWL2.onDatatype).next(); if (baseType != null && baseType.isURIResource()) { ConceptName baseTypeConceptName = new ConceptName(baseType.asResource().getURI()); baseTypeConceptName.setType(ConceptType.RDFDATATYPE); tci = new TypeCheckInfo(propConceptName, baseTypeConceptName, this, expression); } } } else { rangeConceptName.setRangeValueType(propConceptName.getRangeValueType()); } } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { rangeConceptName.setType(ConceptType.ONTCLASS); } List<ConceptName> impliedProperties = getImpliedProperties(first.asResource()); tci = new TypeCheckInfo(propConceptName, rangeConceptName, impliedProperties, this, expression); return tci; } private List<ConceptName> getImpliedProperties(Resource first) { List<ConceptName> retlst = null; // check superclasses if (first.canAs(OntClass.class)) { OntClass ontcls = first.as(OntClass.class); ExtendedIterator<OntClass> eitr = ontcls.listSuperClasses(); while (eitr.hasNext()) { OntClass supercls = eitr.next(); List<ConceptName> scips = getImpliedProperties(supercls); if (retlst == null) { retlst = scips; } else { retlst.addAll(scips); } } } StmtIterator sitr = theJenaModel.listStatements(first, theJenaModel.getProperty(JenaBasedSadlModelProcessor.SADL_IMPLICIT_MODEL_IMPLIED_PROPERTY_URI), (RDFNode)null); if (sitr.hasNext()) { if (retlst == null) { retlst = new ArrayList<ConceptName>(); } while (sitr.hasNext()) { RDFNode obj = sitr.nextStatement().getObject(); if (obj.isURIResource()) { retlst.add(new ConceptName(obj.asResource().getURI())); } } return retlst; } return retlst; } private boolean isRangeKlugyDATASubclass(OntResource rsrc) { if (rsrc.getURI().endsWith("#DATA")) { return true; } if (rsrc.canAs(OntClass.class)){ ExtendedIterator<OntClass> itr = rsrc.as(OntClass.class).listSuperClasses(); while (itr.hasNext()) { OntClass spr = itr.next(); if (spr.isURIResource() && spr.getURI().endsWith("#DATA")) { return true; } } } return false; } protected TypeCheckInfo getVariableType(ConceptType variable, String conceptUri, EObject expression) throws DontTypeCheckException { //Needs filled in for Requirements extension ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, declarationConceptName, this, expression); } private TypeCheckInfo combineTypes(List<String> operations, Expression leftExpression, Expression rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) throws InvalidNameException, DontTypeCheckException { if(!compareTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo)){ return null; } if (isBooleanComparison(operations)) { ConceptName booleanLiteralConceptName = new ConceptName(XSD.xboolean.getURI()); booleanLiteralConceptName.setType(ConceptType.DATATYPEPROPERTY); return new TypeCheckInfo(booleanLiteralConceptName, booleanLiteralConceptName, this, leftExpression.eContainer()); } else{ return leftTypeCheckInfo; } } protected boolean isBooleanComparison(List<String> operations) { if(comparisonOperators.containsAll(operations)){ return true; } return false; } /** * Compare two TypeCheckInfo structures * @param operations * @param leftExpression * @param rightExpression * @param leftTypeCheckInfo * @param rightTypeCheckInfo * @return return true if they pass type check comparison else false * @throws InvalidNameException * @throws DontTypeCheckException */ private boolean compareTypes(List<String> operations, Expression leftExpression, Expression rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) throws InvalidNameException, DontTypeCheckException { List<TypeCheckInfo> ltciCompound = (leftTypeCheckInfo != null) ? leftTypeCheckInfo.getCompoundTypes() : null; if (ltciCompound != null) { for (int i = 0; i < ltciCompound.size(); i++) { boolean thisResult = compareTypes(operations, leftExpression, rightExpression, ltciCompound.get(i), rightTypeCheckInfo); if (thisResult) { return true; } } return false; } List<TypeCheckInfo> rtciCompound = (rightTypeCheckInfo != null) ? rightTypeCheckInfo.getCompoundTypes() : null; if (rtciCompound != null) { for (int i = 0; i < rtciCompound.size(); i++) { boolean thisResult = compareTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rtciCompound.get(i)); if (thisResult) { return true; } } return false; } ConceptIdentifier leftConceptIdentifier = leftTypeCheckInfo != null ? leftTypeCheckInfo.getTypeCheckType(): null; ConceptIdentifier rightConceptIdentifier = rightTypeCheckInfo != null ? rightTypeCheckInfo.getTypeCheckType() : null; if (leftConceptIdentifier == null) { issueAcceptor.addError("Type comparison not possible", leftExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } return false; } else if(rightConceptIdentifier == null){ issueAcceptor.addError("Type comparison not possible", rightExpression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } return false; } else if (leftConceptIdentifier.toString().equals("None") || rightConceptIdentifier.toString().equals("None") || leftConceptIdentifier.toString().equals("TODO") || rightConceptIdentifier.toString().equals("TODO")) { // Can't type-check on "None" as it represents that it doesn't exist. //TODO return true; } else if (!compatibleTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo)) { if (leftTypeCheckInfo.getImplicitProperties() != null || rightTypeCheckInfo.getImplicitProperties() != null) { return compareTypesUsingImpliedProperties(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo); } return false; } return true; } private boolean compareTypesUsingImpliedProperties(List<String> operations, Expression leftExpression, Expression rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) throws InvalidNameException, DontTypeCheckException { if (leftTypeCheckInfo.getImplicitProperties() != null) { Iterator<ConceptName> litr = leftTypeCheckInfo.getImplicitProperties().iterator(); while (litr.hasNext()) { ConceptName cn = litr.next(); Property prop = theJenaModel.getProperty(cn.getUri()); if (prop.canAs(ObjectProperty.class)) { cn.setType(ConceptType.OBJECTPROPERTY); } else if (prop.canAs(DatatypeProperty.class)) { cn.setType(ConceptType.DATATYPEPROPERTY); } else { cn.setType(ConceptType.RDFPROPERTY); } TypeCheckInfo newltci = getTypeInfoFromRange(cn, prop, leftExpression); if (compareTypes(operations, leftExpression, rightExpression, newltci, rightTypeCheckInfo)) { issueAcceptor.addInfo("Implied property '" + cn.getUri() + "' used (left side) to pass type check", leftExpression); addImpliedPropertiesUsed(leftExpression, prop); return true; } } } else if (rightTypeCheckInfo.getImplicitProperties() != null) { Iterator<ConceptName> ritr = rightTypeCheckInfo.getImplicitProperties().iterator(); while (ritr.hasNext()) { ConceptName cn = ritr.next(); Property prop = theJenaModel.getProperty(cn.getUri()); if (prop.canAs(ObjectProperty.class)) { cn.setType(ConceptType.OBJECTPROPERTY); } else if (prop.canAs(DatatypeProperty.class)) { cn.setType(ConceptType.DATATYPEPROPERTY); } else { cn.setType(ConceptType.RDFPROPERTY); } TypeCheckInfo newrtci = getTypeInfoFromRange(cn, prop, rightExpression); if (compareTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, newrtci)) { issueAcceptor.addInfo("Implied property '" + cn.getUri() + "' used (right side) to pass type check", rightExpression); addImpliedPropertiesUsed(rightExpression, prop); return true; } } } return false; } private boolean compatibleTypes(List<String> operations, Expression leftExpression, Expression rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) throws InvalidNameException{ if ((leftTypeCheckInfo.getRangeValueType() == null && rightTypeCheckInfo.getRangeValueType() != null && !rightTypeCheckInfo.getRangeValueType().equals(RangeValueType.CLASS_OR_DT)) || (leftTypeCheckInfo.getRangeValueType() != null && !leftTypeCheckInfo.getRangeValueType().equals(RangeValueType.CLASS_OR_DT) && rightTypeCheckInfo.getRangeValueType() == null) || (leftTypeCheckInfo.getRangeValueType() != null && rightTypeCheckInfo.getRangeValueType() != null && !(leftTypeCheckInfo.getRangeValueType().equals(rightTypeCheckInfo.getRangeValueType())))) { if (!isQualifyingListOperation(operations, leftTypeCheckInfo, rightTypeCheckInfo)) { return false; } } ConceptIdentifier leftConceptIdentifier = leftTypeCheckInfo.getTypeCheckType(); ConceptIdentifier rightConceptIdentifier = rightTypeCheckInfo.getTypeCheckType(); if (leftConceptIdentifier == null || rightConceptIdentifier == null) { return false; } if (leftConceptIdentifier instanceof ConceptName && rightConceptIdentifier instanceof ConceptName) { ConceptName leftConceptName = (ConceptName) leftConceptIdentifier; ConceptName rightConceptName = (ConceptName) rightConceptIdentifier; if (leftConceptName.equals(rightConceptName)) { return true; } else if (leftConceptName.getType() == null || rightConceptName.getType() == null) { if (rightConceptName.getType() == null && leftConceptName.getType() == null) { return true; } else { return false; } } else if (leftConceptName.getType().equals(ConceptType.RDFDATATYPE) && rightConceptName.getType().equals(ConceptType.RDFDATATYPE)) { if(leftConceptName.getUri().equals(rightConceptName.getUri())){ return true; } else if (isInteger(leftConceptName) && isInteger(rightConceptName)) { return true; } else if(isDecimal(leftConceptName) && isInteger(rightConceptName)){ return true; } else if(isInteger(leftConceptName) && isDecimal(rightConceptName)){ // TODO does this need to be restricted to certain operators? This should work for numerical comparison... return true; } else if(isDecimal(leftConceptName) && isDecimal(rightConceptName)){ return true; } } else if (leftConceptName.getType().equals(ConceptType.DATATYPEPROPERTY) && rightConceptName.getType().equals(ConceptType.DATATYPEPROPERTY)) { if(leftConceptName.getUri().equals(rightConceptName.getUri())){ return true; } } else if(leftConceptName.getType().equals(ConceptType.OBJECTPROPERTY) && rightConceptName.getType().equals(ConceptType.OBJECTPROPERTY)){ if(leftConceptName.getUri().equals(rightConceptName.getUri())){ return true; } } else if (leftConceptName.getType().equals(ConceptType.ONTCLASS) && rightConceptName.getType().equals(ConceptType.ONTCLASS)) { //How do we determine if either is a sub/super class of the other? if(leftConceptName.getUri().equals(rightConceptName.getUri())){ return true; } // these next two ifs are a little loose, but not clear how to determine which way the comparison should be? May need tightening... AWC 5/11/2016 try { if (SadlUtils.classIsSubclassOf(theJenaModel.getOntClass(leftConceptName.getUri()), theJenaModel.getOntResource(rightConceptName.getUri()), true, null)) { return true; } if (SadlUtils.classIsSubclassOf(theJenaModel.getOntClass(rightConceptName.getUri()), theJenaModel.getOntResource(leftConceptName.getUri()), true, null)) { return true; } } catch (CircularDependencyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if ((leftConceptName.getType().equals(ConceptType.INDIVIDUAL) && rightConceptName.getType().equals(ConceptType.ONTCLASS))) { return instanceBelongsToClass(theJenaModel.getIndividual(leftConceptName.getUri()), theJenaModel.getOntClass(rightConceptName.getUri())); } else if ((leftConceptName.getType().equals(ConceptType.ONTCLASS) && rightConceptName.getType().equals(ConceptType.INDIVIDUAL))){ return instanceBelongsToClass(theJenaModel.getIndividual(rightConceptName.getUri()), theJenaModel.getOntClass(leftConceptName.getUri())); } else if ((leftConceptName.getType().equals(ConceptType.INDIVIDUAL) && rightConceptName.getType().equals(ConceptType.INDIVIDUAL))){ // TODO Is this the right way to compare for two individuals? return instancesHaveCommonType(theJenaModel.getIndividual(leftConceptName.getUri()), theJenaModel.getIndividual(rightConceptName.getUri())); } } return false; } protected boolean isQualifyingListOperation(List<String> operations, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) { if (operations.contains("contain") || operations.contains("contains") && leftTypeCheckInfo != null && leftTypeCheckInfo.getRangeValueType().equals(RangeValueType.LIST)) { return true; } if (operations.contains("unique") && operations.contains("in") && rightTypeCheckInfo != null && rightTypeCheckInfo.getRangeValueType().equals(RangeValueType.LIST)) { return true; } return false; } private boolean instancesHaveCommonType(Individual individualL, Individual individualR) { ExtendedIterator<Resource> lcitr = individualL.listRDFTypes(true); ExtendedIterator<Resource> rcitr = individualR.listRDFTypes(true); while (lcitr.hasNext()) { Resource lr = lcitr.next(); while (rcitr.hasNext()) { Resource rr = rcitr.next(); if (lr.equals(rr)) { lcitr.close(); rcitr.close(); return true; } } } return false; } private boolean instanceBelongsToClass(Individual individual, OntClass ontClass) { ExtendedIterator<Resource> citr = individual.listRDFTypes(false); while (citr.hasNext()) { Resource cls = citr.next(); if (cls.isURIResource() && cls.getURI().equals(ontClass.getURI())) { return true; } else { // this may be a union or intersection class; how should this be handled? // TODO } } return false; } /** * return true if the first argument class is a subclass of the second * argument class * * @param subcls * @param cls * @return * @throws JenaProcessorException * @throws CircularDependencyException */ // public boolean classIsSubclassOf(OntClass subcls, OntResource cls, boolean rootCall) throws JenaProcessorException, CircularDependencyException { // return SadlUtils.classIsSubclassOf(subcls, cls, rootCall, null); // if (subcls == null || cls == null) { // return false; // if (cls.isURIResource() && subcls.isURIResource() // && cls.getURI().equals(subcls.getURI())) { // return true; // if (cls.isAnon()) { // if (cls.canAs(OntClass.class)) { // OntClass ocls = cls.as(OntClass.class); // if (ocls.isUnionClass()) { // UnionClass ucls = cls.as(UnionClass.class); // try { // ExtendedIterator<? extends OntClass> eitr = ucls // .listOperands(); // while (eitr.hasNext()) { // OntClass uclsmember = eitr.next(); // if (classIsSubclassOf(subcls, uclsmember, false)) { // eitr.close(); // return true; // catch (Exception e) { // issueAcceptor.addError("Unexpected error during deep validation: apparent Union Class does not return operands.", getDefaultContext()); // try { // if (cls.canAs(OntClass.class)) { // ExtendedIterator<OntClass> eitr = cls.as(OntClass.class).listSubClasses(); // while (eitr.hasNext()) { // OntClass subClsOfCls = eitr.next(); // if (subClsOfCls.equals(subcls)) { // eitr.close(); // return true; // else { // if (classIsSubclassOf(subcls, subClsOfCls, false)) { // eitr.close(); // return true; // eitr.close(); //// if (rootCall && classIsSuperClassOf(cls.as(OntClass.class), subcls)) { //// return true; // if (subcls.isAnon()) { // if (subcls.isIntersectionClass()) { // IntersectionClass icls = subcls.asIntersectionClass(); // try { // ExtendedIterator<? extends OntClass> eitr = icls.listOperands(); // while (eitr.hasNext()) { // OntClass iclsmember = eitr.next(); // if (classIsSubclassOf(cls.as(OntClass.class), iclsmember, false)) { // eitr.close(); // return true; // catch (Exception e) { // issueAcceptor.addError("Unexpected error during deep validation: apparent Intersection Class does not return operands.", getDefaultContext()); //// TODO We need to look for equivalent classes that provide a definition for a subclass, //// e.g. Component is equivalent to System is class, (System and connectedTo someValueFrom Network) => Component subclass of System. // if (cls.canAs(OntClass.class)) { //// SELECT ?eqClass //// WHERE {?class owl:equivalentClass ?eqClass} // ExtendedIterator<OntClass> eqitr = cls.as(OntClass.class).listEquivalentClasses(); // while (eqitr.hasNext()) { // OntClass eqcls = eqitr.next(); // if (classIsSubclassOf(subcls, eqcls, false)) { // return true; //// if (subcls.hasSuperClass(cls, false)) { // this doesn't work, don't know why awc 6/8/2012 //// return true; //// else { //// if (subcls.canAs(OntClass.class)) { //// ExtendedIterator<OntClass> eitr = subcls.as(OntClass.class).listSuperClasses(false); //// while (eitr.hasNext()) { //// OntClass sprcls = eitr.next(); //// if (sprcls.equals(cls)) { //// return true; // } catch (Throwable t) { // t.printStackTrace(); // return false; private boolean isInteger(ConceptIdentifier type) throws InvalidNameException { if (type instanceof ConceptName) { String uri = ((ConceptName)type).getUri(); if (uri.equals(XSD.integer.getURI())) { return true; } else if (uri.equals(XSD.xint.getURI())) { return true; } } return false; } private boolean isDecimal(ConceptIdentifier type) throws InvalidNameException { if (type instanceof ConceptName) { String uri = ((ConceptName)type).getUri(); if (uri.equals(XSD.xfloat.getURI()) || uri.equals(XSD.xdouble.getURI()) || uri.equals(XSD.decimal.getURI())) { return true; } } return false; } private EObject getDefaultContext() { return defaultContext; } private void setDefaultContext(EObject defaultContext) { this.defaultContext = defaultContext; } public Map<EObject, Property> getImpliedPropertiesUsed() { return impliedPropertiesUsed; } protected boolean addImpliedPropertiesUsed(EObject context, Property impliedPropertyUsed) { if (impliedPropertiesUsed == null) { impliedPropertiesUsed = new HashMap<EObject, Property>(); impliedPropertiesUsed.put(context, impliedPropertyUsed); return true; } else { if (!impliedPropertiesUsed.containsKey(context)) { impliedPropertiesUsed.put(context, impliedPropertyUsed); return true; } } return false; } }
package com.ge.research.sadl.jena; import java.io.IOException; import java.math.BigDecimal; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.diagnostics.Severity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ge.research.sadl.errorgenerator.generator.SadlErrorMessages; import com.ge.research.sadl.model.CircularDefinitionException; import com.ge.research.sadl.model.ConceptIdentifier; import com.ge.research.sadl.model.ConceptName; import com.ge.research.sadl.model.ConceptName.ConceptType; import com.ge.research.sadl.model.ConceptName.RangeValueType; import com.ge.research.sadl.model.DeclarationExtensions; import com.ge.research.sadl.model.OntConceptType; import com.ge.research.sadl.model.PrefixNotFoundException; import com.ge.research.sadl.model.SadlUnionClass; import com.ge.research.sadl.model.gp.ConstantNode; import com.ge.research.sadl.model.gp.Junction; import com.ge.research.sadl.model.gp.NamedNode; import com.ge.research.sadl.model.gp.NamedNode.NodeType; import com.ge.research.sadl.model.gp.Node; import com.ge.research.sadl.model.gp.ProxyNode; import com.ge.research.sadl.model.gp.Rule; import com.ge.research.sadl.model.gp.TripleElement; import com.ge.research.sadl.model.gp.VariableNode; import com.ge.research.sadl.processing.ISadlModelValidator; import com.ge.research.sadl.processing.SadlConstants; import com.ge.research.sadl.processing.SadlModelProcessor; import com.ge.research.sadl.processing.ValidationAcceptor; import com.ge.research.sadl.reasoner.CircularDependencyException; import com.ge.research.sadl.reasoner.ConfigurationException; import com.ge.research.sadl.reasoner.ITranslator; import com.ge.research.sadl.reasoner.InvalidNameException; import com.ge.research.sadl.reasoner.InvalidTypeException; import com.ge.research.sadl.reasoner.TranslationException; import com.ge.research.sadl.reasoner.utils.SadlUtils; import com.ge.research.sadl.sADL.AskExpression; import com.ge.research.sadl.sADL.BinaryOperation; import com.ge.research.sadl.sADL.BooleanLiteral; import com.ge.research.sadl.sADL.Constant; import com.ge.research.sadl.sADL.ConstructExpression; import com.ge.research.sadl.sADL.Declaration; import com.ge.research.sadl.sADL.ElementInList; import com.ge.research.sadl.sADL.EquationStatement; import com.ge.research.sadl.sADL.Expression; import com.ge.research.sadl.sADL.ExternalEquationStatement; import com.ge.research.sadl.sADL.Name; import com.ge.research.sadl.sADL.NumberLiteral; import com.ge.research.sadl.sADL.PropOfSubject; import com.ge.research.sadl.sADL.QueryStatement; import com.ge.research.sadl.sADL.SadlBooleanLiteral; import com.ge.research.sadl.sADL.SadlClassOrPropertyDeclaration; import com.ge.research.sadl.sADL.SadlConstantLiteral; import com.ge.research.sadl.sADL.SadlDataType; import com.ge.research.sadl.sADL.SadlInstance; import com.ge.research.sadl.sADL.SadlIntersectionType; import com.ge.research.sadl.sADL.SadlModel; import com.ge.research.sadl.sADL.SadlModelElement; import com.ge.research.sadl.sADL.SadlMustBeOneOf; import com.ge.research.sadl.sADL.SadlNestedInstance; import com.ge.research.sadl.sADL.SadlNumberLiteral; import com.ge.research.sadl.sADL.SadlParameterDeclaration; import com.ge.research.sadl.sADL.SadlPrimitiveDataType; import com.ge.research.sadl.sADL.SadlProperty; import com.ge.research.sadl.sADL.SadlPropertyCondition; import com.ge.research.sadl.sADL.SadlPropertyInitializer; import com.ge.research.sadl.sADL.SadlResource; import com.ge.research.sadl.sADL.SadlSimpleTypeReference; import com.ge.research.sadl.sADL.SadlStringLiteral; import com.ge.research.sadl.sADL.SadlTypeReference; import com.ge.research.sadl.sADL.SadlUnaryExpression; import com.ge.research.sadl.sADL.SadlUnionType; import com.ge.research.sadl.sADL.SelectExpression; import com.ge.research.sadl.sADL.StringLiteral; import com.ge.research.sadl.sADL.SubjHasProp; import com.ge.research.sadl.sADL.Sublist; import com.ge.research.sadl.sADL.TestStatement; import com.ge.research.sadl.sADL.UnaryExpression; import com.ge.research.sadl.sADL.UnitExpression; import com.ge.research.sadl.sADL.ValueTable; import com.ge.research.sadl.sADL.impl.ExternalEquationStatementImpl; import com.ge.research.sadl.sADL.impl.TestStatementImpl; import com.ge.research.sadl.utils.SadlASTUtils; import com.hp.hpl.jena.datatypes.DatatypeFormatException; import com.hp.hpl.jena.datatypes.RDFDatatype; import com.hp.hpl.jena.ontology.AllValuesFromRestriction; import com.hp.hpl.jena.ontology.AnnotationProperty; import com.hp.hpl.jena.ontology.DatatypeProperty; import com.hp.hpl.jena.ontology.HasValueRestriction; import com.hp.hpl.jena.ontology.Individual; import com.hp.hpl.jena.ontology.IntersectionClass; import com.hp.hpl.jena.ontology.ObjectProperty; import com.hp.hpl.jena.ontology.OntClass; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.ontology.Restriction; import com.hp.hpl.jena.ontology.UnionClass; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFList; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.rdf.model.Statement; import com.hp.hpl.jena.rdf.model.StmtIterator; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.vocabulary.OWL; import com.hp.hpl.jena.vocabulary.OWL2; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; import com.hp.hpl.jena.vocabulary.XSD; public class JenaBasedSadlModelValidator implements ISadlModelValidator { public static final String RANGE = "range"; public static final String RESTRICTED_TO = "restriction to"; private static final int MIN_INT = -2147483648; private static final int MAX_INT = 2147483647; private static final long MIN_LONG = -9223372036854775808L; private static final long MAX_LONG = 9223372036854775807L; protected ValidationAcceptor issueAcceptor = null; protected OntModel theJenaModel = null; protected DeclarationExtensions declarationExtensions = null; private EObject defaultContext; protected Map<EObject, TypeCheckInfo> expressionsTypeCheckCache = new HashMap<EObject,TypeCheckInfo>(); private Map<EObject, Property> impliedPropertiesUsed = null; private Map<EObject, List<String>> applicableExpandedProperties = null; private IMetricsProcessor metricsProcessor = null; protected JenaBasedSadlModelProcessor modelProcessor = null; private List<ConceptName> binaryOpLeftImpliedProperties; private List<ConceptName> binaryOpRightImpliedProperties; protected Object lastSuperCallExpression = null; private List<EObject> eObjectsValidated = null; public enum ExplicitValueType {RESTRICTION, VALUE} public enum ImplicitPropertySide {LEFT, RIGHT, NONE, BOTH} private static final Logger logger = LoggerFactory.getLogger(JenaBasedSadlModelValidator.class); /** * This inner class captures the information about the left or right hand side of an expression that is subject * to type checking, e.g., and assignment, a comparison, etc. * */ public class TypeCheckInfo { private EObject context = null; // the parsetree element from which this is derived, // used to add an error, warning, or info so that a marker can be placed in the editor private ConceptIdentifier expressionType = null; // the identity, type, etc. of the concept that determines the type, // e.g., the property of a "<property> of <subject>" expression private Node typeCheckType = null; // the type of the TypeCheckInfo which must match the other side of the expression, // e.g., the range of the property of a "<property> of <subject>" expression // Note: this is a ProxyNode can be used for Unions and Intersections private RDFNode explicitValue = null; // the explicit value that is allowed, as in a hasValue restriction private ExplicitValueType explicitValueType; // The type of the explicit value private RangeValueType rangeValueType = RangeValueType.CLASS_OR_DT; // the range type, one of RangeValueType.CLASS_OR_DT (Class or RDFDataType) // or LIST (a subclass of http://sadl.org/sadllistmodel#List) private List<ConceptName> implicitProperties = null; // Implied properties, if any, that apply to this expressionType private List<TypeCheckInfo> compoundTypes = null; // If this is a disjunction of multiple types, this contains the next // lower level of TypeCheckInfos in the hierarchy, e.g., a property whose // range is a union of classes or which is given range in multiple imports private String typeToExprRelationship = RANGE; // the relationship between the typeCheckType and the expressionType, e.g., range (the default) // for explicit UnittedQuantity this will be the units private String additionalInformation = null; // any additional information to explain the contents of the instance of the class. private Severity severity = null; // Guidance offered on the severity of any type mismatch involving this instance of the class. public TypeCheckInfo(ConceptIdentifier eType) { setExpressionType(eType); } /* Constructor for compound types (union, e.g. range) */ public TypeCheckInfo(ConceptIdentifier eType, JenaBasedSadlModelValidator validator, EObject ctx) { setExpressionType(eType); setContext(validator, ctx); } /** * Constructor * @param eType Expression type, e.g., the property * @param tcType the type of the values which are valid * @param validator the model validator * @param ctx the EObject from which this is generated */ public TypeCheckInfo(ConceptIdentifier eType, Node tcType, JenaBasedSadlModelValidator validator, EObject ctx) { setExpressionType(eType); setTypeCheckType(tcType); setContext(validator, ctx); } public TypeCheckInfo(ConceptIdentifier eType, Node tcType, JenaBasedSadlModelValidator validator, List<ConceptName> impliedProps, EObject ctx) { this(eType, tcType, validator, ctx); if (impliedProps != null) { implicitProperties = impliedProps; } } public TypeCheckInfo(ConceptName eType, RDFNode valueRestriction, ExplicitValueType valueType, JenaBasedSadlModelValidator validator, EObject ctx) { setExpressionType(eType); setExplicitValueType(valueType); setContext(validator, ctx); setExplicitValue(valueRestriction); if (valueType.equals(ExplicitValueType.RESTRICTION)) { setTypeToExprRelationship(RESTRICTED_TO); } else { setTypeToExprRelationship("explicit value"); } } public TypeCheckInfo(ConceptIdentifier eType, Node tcType, List<ConceptName> impliedProps, JenaBasedSadlModelValidator validator, EObject ctx) { setExpressionType(eType); setTypeCheckType(tcType); implicitProperties = impliedProps; setContext(validator, ctx); } public boolean equals(Object o) { if (o instanceof TypeCheckInfo) { TypeCheckInfo other = (TypeCheckInfo) o; return context == other.context // Identity check should be fine for EObjects && Objects.equals(getExpressionType(), other.getExpressionType()) && Objects.equals(getRangeValueType(), other.getRangeValueType()) && Objects.equals(getTypeCheckType(), other.getTypeCheckType()); } return false; } @Override public int hashCode() { return Objects.hash(context, getExpressionType(), getRangeValueType(), getTypeCheckType()); } public ConceptIdentifier getExpressionType() { return expressionType; } public void setExpressionType(ConceptIdentifier expressionType) { this.expressionType = expressionType; } public Node getTypeCheckType() { return typeCheckType; } public void setTypeCheckType(Node typeCheckType) { this.typeCheckType = typeCheckType; if (typeCheckType instanceof NamedNode && ((NamedNode)typeCheckType).isList()) { setRangeValueType(RangeValueType.LIST); } } public RangeValueType getRangeValueType() { if(this.getCompoundTypes() != null){ return getCompoundRangeValueType(this); }else{ return rangeValueType; } } private RangeValueType getCompoundRangeValueType(TypeCheckInfo tci){ List<TypeCheckInfo> types = tci.getCompoundTypes(); Iterator<TypeCheckInfo> iter = types.iterator(); RangeValueType rvt = null; while(iter.hasNext()){ TypeCheckInfo type = iter.next(); RangeValueType rvt2 = null; if(type.getCompoundTypes() != null){ rvt2 = getCompoundRangeValueType(type); }else{ rvt2 = type.getRangeValueType(); } if(rvt != null){ if(rvt != rvt2){ issueAcceptor.addError("Property '" + tci.getExpressionType() + "' has incompatable Range Types, '" + rvt.toString() + "' and '" + rvt2.toString() + "'", tci.context); //TODO add new error message } }else{ rvt = rvt2; } } return rvt; } protected void setContext(JenaBasedSadlModelValidator validator, EObject ctx) { this.context = ctx; } public void setRangeValueType(RangeValueType rangeValueType) { this.rangeValueType = rangeValueType; } public String toString() { if (compoundTypes != null) { StringBuffer sb = new StringBuffer("Compound TypeCheckInfo(["); for (int i = 0; i < compoundTypes.size(); i++) { if (i > 0) { sb.append(","); } sb.append(compoundTypes.get(i).toString()); } sb.append("]"); return sb.toString(); } else { StringBuffer sb = new StringBuffer("TypeCheckInfo("); if (getRangeValueType() != null && !getRangeValueType().equals(RangeValueType.CLASS_OR_DT)) { sb.append(getRangeValueType().toString()); sb.append(" of values of type, "); } sb.append(expressionType.toString()); sb.append(", "); sb.append(typeCheckType != null ? typeCheckType.toString() : "unknown type"); if (getExplicitValue() != null) { if (getExplicitValueType().equals(ExplicitValueType.RESTRICTION)) { sb.append(", restricted to explicit value '"); } else { sb.append(", is the explicit value '"); } sb.append(getExplicitValue().toString()); sb.append("'"); } sb.append(")"); if (getImplicitProperties() != null) { if (getImplicitProperties().size() > 1) sb.append(" (has implied properties "); else sb.append(" (has implied property "); sb.append(implicitPropertiesToString(getImplicitProperties())); sb.append(")"); } return sb.toString(); } } private Object implicitPropertiesToString(List<ConceptName> iprops) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < iprops.size(); i++) { if (i > 0) sb.append(", "); sb.append(getImplicitProperties().get(i).toFQString()); } return sb.toString(); } public void addImplicitProperty(ConceptName implicitProp) { if (implicitProp != null) { if (implicitProperties == null) { implicitProperties = new ArrayList<ConceptName>(); } if (!implicitProperties.contains(implicitProp)) { implicitProperties.add(implicitProp); } } } public void addImplicitProperties(List<ConceptName> implicitProps) { if (implicitProperties == null) { implicitProperties = implicitProps; } else { implicitProperties.addAll(implicitProps); } } public List<ConceptName> getImplicitProperties() { return implicitProperties; } public List<TypeCheckInfo> getCompoundTypes() { return compoundTypes; } private void addCompoundType(TypeCheckInfo additionalType) { if (compoundTypes == null) { compoundTypes= new ArrayList<TypeCheckInfo>(); } if (!compoundTypes.contains(additionalType)) { compoundTypes.add(additionalType); } } private String getTypeToExprRelationship() { return typeToExprRelationship; } public void setTypeToExprRelationship(String typeToExprRelationship) { this.typeToExprRelationship = typeToExprRelationship; } public RDFNode getExplicitValue() { return explicitValue; } public void setExplicitValue(RDFNode explicitValue) { this.explicitValue = explicitValue; } public ExplicitValueType getExplicitValueType() { return explicitValueType; } public void setExplicitValueType(ExplicitValueType explicitValueType) { this.explicitValueType = explicitValueType; } private String getAdditionalInformation() { return additionalInformation; } private void setAdditionalInformation(String additionalInformation) { this.additionalInformation = additionalInformation; } public Severity getSeverity() { return severity; } public void setSeverity(Severity severity) { this.severity = severity; } public boolean isList() { return getRangeValueType().equals(RangeValueType.LIST); } } public JenaBasedSadlModelValidator(ValidationAcceptor issueAcceptor, OntModel theJenaModel, JenaBasedSadlModelProcessor processor) { this(issueAcceptor, theJenaModel, new DeclarationExtensions(), processor, null); } public JenaBasedSadlModelValidator(ValidationAcceptor issueAcceptor, OntModel theJenaModel, DeclarationExtensions declarationExtensions, JenaBasedSadlModelProcessor processor, IMetricsProcessor metricsProcessor){ this.issueAcceptor = issueAcceptor; this.theJenaModel = theJenaModel; this.declarationExtensions = declarationExtensions; this.setModelProcessor(processor) ; this.metricsProcessor = metricsProcessor; } public boolean validate(Expression expr, String xsdType, String op, StringBuilder errorMessageBuilder) { List<String> operations = Arrays.asList(op.split("\\s+")); TypeCheckInfo exprTypeCheckInfo; try { exprTypeCheckInfo = getType(expr); NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.xint.getURI(), NodeType.DataTypeNode)); ConceptName numberLiteralConceptName = getModelProcessor().namedNodeToConceptName(tctype); numberLiteralConceptName.setType(ConceptType.RDFDATATYPE); TypeCheckInfo xsdTypeCheckInfo = new TypeCheckInfo(numberLiteralConceptName, tctype, this, null); if(!compareTypes(operations, expr, null, exprTypeCheckInfo, xsdTypeCheckInfo, ImplicitPropertySide.NONE)){ if (createErrorMessage(errorMessageBuilder, exprTypeCheckInfo, xsdTypeCheckInfo, op, true, expr)) { return false; } } } catch (Throwable t) { return handleValidationException(expr, t); } return true; } public boolean validate(BinaryOperation expression, StringBuilder errorMessageBuilder) { setDefaultContext(expression); Expression leftExpression = expression.getLeft(); Expression rightExpression = expression.getRight(); String op = expression.getOp(); return validateBinaryOperationByParts(expression, leftExpression, rightExpression, op, errorMessageBuilder, false); } public boolean validateBinaryOperationByParts(EObject expression, EObject leftExpression, EObject rightExpression, String op, StringBuilder errorMessageBuilder, boolean forceValidation) { List<String> operations = Arrays.asList(op.split("\\s+")); boolean errorsFound = false; if (!forceValidation && !registerEObjectValidateCalled(expression)) { // if there were errors they were reported on the first call return !errorsFound; } if(skipOperations(operations)){ return true; } if (skipNonCheckedExpressions(leftExpression, rightExpression)) { return true; } if (!passLiteralConstantComparisonCheck(expression, leftExpression, rightExpression, op, errorMessageBuilder)) { errorsFound = true; } try { boolean dontTypeCheck = false; TypeCheckInfo leftTypeCheckInfo = null; try { leftTypeCheckInfo = getType(leftExpression); if (getModelProcessor().isConjunction(op)) { // this can be treated as a boolean only (maybe even larger criteria?) leftTypeCheckInfo = createBooleanTypeCheckInfo(leftExpression); } else if (getModelProcessor().elementIdentificationOperation(op)) { leftTypeCheckInfo = convertListTypeToElementOfListType(leftTypeCheckInfo); } } catch (DontTypeCheckException e) { dontTypeCheck = true; } if (useImpliedProperties(op)) { setBinaryOpLeftImpliedProperties(leftTypeCheckInfo != null ? leftTypeCheckInfo.getImplicitProperties() : null); } TypeCheckInfo rightTypeCheckInfo = null; try { rightTypeCheckInfo = getType(rightExpression); if (getModelProcessor().isConjunction(op)) { // this can be treated as a boolean only (maybe even larger criteria?) rightTypeCheckInfo = createBooleanTypeCheckInfo(leftExpression); } else if (getModelProcessor().elementIdentificationOperation(op)) { rightTypeCheckInfo = convertListTypeToElementOfListType(rightTypeCheckInfo); } } catch (DontTypeCheckException e) { dontTypeCheck = true; } if (useImpliedProperties(op)) { setBinaryOpRightImpliedProperties(rightTypeCheckInfo != null ? rightTypeCheckInfo.getImplicitProperties() : null); } if (leftTypeCheckInfo == null && rightTypeCheckInfo == null) { // this condition happens when a file is loaded in the editor and clean/build is invoked return true; } if (modelProcessor.isComparisonOperator(op) && (rightExpression instanceof NumberLiteral || rightExpression instanceof UnaryExpression && ((UnaryExpression)rightExpression).getExpr() instanceof NumberLiteral)) { checkNumericRangeLimits(op, leftTypeCheckInfo, rightTypeCheckInfo); } if(!dontTypeCheck && !compareTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo, ImplicitPropertySide.NONE)){ if (expression.eContainer() instanceof TestStatement && isQuery(leftExpression)) { // you can't tell what type a query will return return !errorsFound; } if (!rulePremiseVariableAssignment(operations, leftTypeCheckInfo,rightTypeCheckInfo)) { String effectiveOp = op; if (leftExpression instanceof Constant && ((Constant)leftExpression).getConstant().equals("value")) { effectiveOp = "matching value"; // leftTypeCheckInfo.setRangeValueType(RangeValueType.CLASS_OR_DT); } if (createErrorMessage(errorMessageBuilder, leftTypeCheckInfo, rightTypeCheckInfo, effectiveOp, false, null)) { return false; } } } //It's possible there may be a local type restriction if (isLocalTypeRestriction(op, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo)) { TypeCheckInfo tciSubjSubj = getType(((PropOfSubject)leftExpression).getRight()); Node propOfSubjSubj = tciSubjSubj.getTypeCheckType(); NamedNode propnn = getModelProcessor().conceptNameToNamedNode((ConceptName) leftTypeCheckInfo.getExpressionType()); NamedNode restrictedTo = (NamedNode) rightTypeCheckInfo.getTypeCheckType(); TripleElement tr = new TripleElement(propOfSubjSubj, propnn, restrictedTo); getModelProcessor().handleLocalRestriction(expression, tr); } if (getModelProcessor().isEqualityInequalityComparisonOperator(op) && !errorsFound) { checkForApplicableExpandedProperties(expression, leftTypeCheckInfo, rightTypeCheckInfo); } TypeCheckInfo binopTci = combineBinaryOperationTypes(operations, expression, leftTypeCheckInfo, rightTypeCheckInfo); expressionsTypeCheckCache.put(expression, binopTci); return !errorsFound; } catch (Throwable t) { return handleValidationException(expression, t); } } private boolean isLocalTypeRestriction(String op, EObject leftExpression, EObject rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) throws InvalidTypeException { if (getModelProcessor().isEqualOperator(op) && leftExpression instanceof PropOfSubject && rightExpression instanceof Declaration) { if (leftTypeCheckInfo.getExpressionType() instanceof ConceptName && rightTypeCheckInfo.getTypeCheckType() instanceof NamedNode) { return true; } } return false; } private void checkForApplicableExpandedProperties(EObject expression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) { Node type = null; // since type checking has passed to get to this point: // if either side has no impliedProperties then the type can come from either side if (leftTypeCheckInfo != null && leftTypeCheckInfo.getImplicitProperties() == null && leftTypeCheckInfo.getTypeCheckType() != null) { type = leftTypeCheckInfo.getTypeCheckType(); } else if (rightTypeCheckInfo != null && rightTypeCheckInfo.getImplicitProperties() == null && rightTypeCheckInfo.getTypeCheckType() != null) { type = rightTypeCheckInfo.getTypeCheckType(); } // the other possibility is that both sides have implied properties (which should be the same) so the type is the common type else if (leftTypeCheckInfo != null && leftTypeCheckInfo.getTypeCheckType() != null && rightTypeCheckInfo != null && rightTypeCheckInfo.getTypeCheckType() != null && leftTypeCheckInfo.getTypeCheckType().equals(rightTypeCheckInfo.getTypeCheckType())) { type = leftTypeCheckInfo.getTypeCheckType(); } else { try { throw new TranslationException("Unexpected failure to find binary operation type"); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (type != null && type instanceof NamedNode && (((NamedNode)type).getNodeType().equals(NodeType.ClassNode) || ((NamedNode)type).getNodeType().equals(NodeType.ClassListNode))) { // expanded properties only apply to classes Resource rsrc = theJenaModel.getResource(((NamedNode)type).toFullyQualifiedString()); try { List<String> expProps = getModelProcessor().getExpandedProperties(rsrc); if (expProps != null) { addApplicableExpandedProperties(expression, expProps); } } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private void addApplicableExpandedProperties(EObject expression, List<String> expProps) { if (applicableExpandedProperties == null) { applicableExpandedProperties = new HashMap<EObject, List<String>>(); } applicableExpandedProperties.put(expression, expProps); } public Map<EObject, List<String>> getApplicableExpandedProperties() { return applicableExpandedProperties; } public void clearApplicableExpandedProperties() { if (applicableExpandedProperties != null) { applicableExpandedProperties.clear(); } } private boolean registerEObjectValidateCalled(EObject expression) { if (expression == null) return true; // for ease in debugging--set expression to null to allow multiple passes in debugger if (eObjectsValidated == null) { eObjectsValidated = new ArrayList<EObject>(); eObjectsValidated.add(expression); return true; } if (eObjectsValidated.contains(expression)) { return false; } eObjectsValidated.add(expression); return true; } private boolean passLiteralConstantComparisonCheck(EObject expression, EObject leftExpression, EObject rightExpression, String op, StringBuilder errorMessageBuilder) { if (modelProcessor.canBeNumericOperator(op)) { if (isLiteralOrConstant(leftExpression) && isLiteralOrConstant(rightExpression)) { errorMessageBuilder.append(SadlErrorMessages.COMPARISON_LITERALS_CONSTANTS.get(op)); return false; } } return true; } private boolean isLiteralOrConstant(EObject expr) { if ((expr instanceof Constant && (((Constant)expr).getConstant().equals(SadlConstants.CONSTANT_PI) || ((Constant)expr).getConstant().equals(SadlConstants.CONSTANT_E))) || expr instanceof NumberLiteral) { return true; } return false; } private boolean skipNonCheckedExpressions(EObject leftExpression, EObject rightExpression) { EObject rExpr = rightExpression; if (rightExpression instanceof UnaryExpression && ((UnaryExpression)rightExpression).getOp().equals("not")) { rExpr = ((UnaryExpression)rightExpression).getExpr(); } if (rExpr instanceof Constant && isSkippedConstant((Constant)rExpr)) { return true; } return false; } @Override public boolean isSkippedConstant(Constant expr) { if (expr.getConstant().equals(SadlConstants.CONSTANT_KNOWN)) { return true; } return false; } private boolean useImpliedProperties(String op) { if (op.equals("contains") || op.equals("does not contain")) { return false; } return true; } private boolean rulePremiseVariableAssignment(List<String> operations, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) throws InvalidTypeException { if (possibleAssignment(operations)) { if (getModelProcessor().getRulePart().equals(SadlModelProcessor.RulePart.PREMISE)) { if (isVariable(leftTypeCheckInfo)) { if (!isAlreadyReferenced(leftTypeCheckInfo.getExpressionType())) { return true; } } else if (isVariable(rightTypeCheckInfo)) { if (!isAlreadyReferenced(rightTypeCheckInfo.getExpressionType())) { return true; } } } } return false; } private boolean isAlreadyReferenced(ConceptIdentifier expressionType) { // TODO Auto-generated method stub return false; } private boolean possibleAssignment(List<String> operations) { if (operations.contains("is") || operations.contains("=")) { return true; } return false; } private boolean isQuery(EObject expr) { if (expr instanceof StringLiteral) { String val = ((StringLiteral)expr).getValue(); if (val.contains("select") && val.contains("where")) { return true; } } return false; } protected boolean handleValidationException(EObject expr, Throwable t) { try { if (t instanceof InvalidNameException) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_CHECK_EXCEPTION.get("Invalid Name"), expr); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } t.printStackTrace(); } else if (t instanceof TranslationException) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_CHECK_EXCEPTION.get("Translation"), expr); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } t.printStackTrace(); } else if (t instanceof URISyntaxException) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_CHECK_EXCEPTION.get("URI Syntax"), expr); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } t.printStackTrace(); } else if (t instanceof IOException) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_CHECK_EXCEPTION.get("IO"), expr); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } t.printStackTrace(); } else if (t instanceof ConfigurationException) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_CHECK_EXCEPTION.get("Configuration"), expr); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } t.printStackTrace(); } else if (t instanceof NullPointerException){ getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_CHECK_EXCEPTION.get("Null Pointer"), expr); } else if (t instanceof DontTypeCheckException) { return true; } else if (t instanceof PropertyWithoutRangeException) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.PROPERTY_WITHOUT_RANGE.get(((PropertyWithoutRangeException)t).getPropID()), expr); return true; } else if (t instanceof CircularDefinitionException) { t.printStackTrace(); } else { t.printStackTrace(); } } catch (Throwable t2) { issueAcceptor.addError("Unexpected exception (" + t.getClass().getCanonicalName() + ": " + t2.getMessage() + ") displaying validation error : " + t.getMessage(), expr); } return false; } protected boolean createErrorMessage(StringBuilder errorMessageBuilder, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo, String operation, boolean addToIssueAcceptor, EObject expr) throws InvalidTypeException { Severity specifiedSeverity = null; if (leftTypeCheckInfo != null && leftTypeCheckInfo.getSeverity() != null) { if (leftTypeCheckInfo.getSeverity().equals(Severity.IGNORE)) { return false; } else { specifiedSeverity = leftTypeCheckInfo.getSeverity(); } } if (rightTypeCheckInfo != null && rightTypeCheckInfo.getSeverity() != null) { if (rightTypeCheckInfo.getSeverity().equals(Severity.IGNORE)) { return false; } else { if (specifiedSeverity == null) { specifiedSeverity = rightTypeCheckInfo.getSeverity(); } else if (rightTypeCheckInfo.getSeverity().compareTo(specifiedSeverity) > 0) { specifiedSeverity = rightTypeCheckInfo.getSeverity(); } } } String[] leftDesc = getTypeCheckInfoDescription(leftTypeCheckInfo); String[] rightDesc = getTypeCheckInfoDescription(rightTypeCheckInfo); String leftSide = ""; String rightSide = ""; String op = ""; if (leftDesc == null) { leftSide = "Undetermined left type"; } else { if (leftDesc.length > 0) { leftSide = leftDesc[0]; } if (leftDesc.length > 1) { leftSide = leftSide + " " + leftDesc[1]; } } if (getModelProcessor().isComparisonOperator(operation)) { op = "be compared (" + operation + ")"; } else { op = "operate (" + operation + ")"; } if (rightDesc == null) { rightSide = "Undetermined right type"; } else { if (rightDesc.length > 0) { rightSide = rightDesc[0]; } if (rightDesc.length > 1) { rightSide = rightSide + " " + rightDesc[1]; } } if (leftSide.contains(",")) leftSide = leftSide + ","; errorMessageBuilder.append(SadlErrorMessages.VALIDATE_BIN_OP_ERROR.get(leftSide, op, rightSide)); if (addToIssueAcceptor) { if (specifiedSeverity != null) { getModelProcessor().addIssueToAcceptor(errorMessageBuilder.toString(), specifiedSeverity, expr); } else { getModelProcessor().addIssueToAcceptor(errorMessageBuilder.toString(), expr); } } return true; } private String[] getTypeCheckInfoDescription(TypeCheckInfo typeCheckInfo) throws InvalidTypeException { if (typeCheckInfo == null) { String[] result = new String[1]; result[0] = "No type check info generated"; return result; } else { StringBuilder sb1 = new StringBuilder();; StringBuilder sb2 = null; ConceptIdentifier typeExpr = typeCheckInfo.getExpressionType(); if (typeExpr != null) { if (typeCheckInfo.getAdditionalInformation() != null) { sb1.append(" "); sb1.append(typeCheckInfo.getAdditionalInformation()); sb1.append(" "); } sb1.append(getModelProcessor().conceptIdentifierToString(typeExpr)); } if (typeExpr instanceof ConceptName) { ConceptType ct = ((ConceptName)typeExpr).getType(); if (ct == null) { sb1.append(", type unknown "); } else if (ct.equals(ConceptType.INDIVIDUAL)) { sb1.append(", an instance of type "); sb2 = new StringBuilder(); } else if (ct.equals(ConceptType.ONTCLASS)) { sb1.append(", a class "); } else if (ct.equals(ConceptType.RDFDATATYPE)) { sb1.append(", an RDF datatype "); sb2= new StringBuilder(); } else if (ct.equals(ConceptType.RDFPROPERTY)) { sb1.append(", an RDF property "); if (rdfPropertyTypeCheckInfoHasRange(typeCheckInfo)) { sb1.append("with "); sb1.append(typeCheckInfo.getTypeToExprRelationship()); sb1.append(" "); } sb2= new StringBuilder(); } else if (ct.equals(ConceptType.ANNOTATIONPROPERTY)) { sb1.append(", an annotation property "); } else if (ct.equals(ConceptType.DATATYPEPROPERTY)) { sb1.append(", a datatype property with "); sb1.append(typeCheckInfo.getTypeToExprRelationship()); sb1.append(" "); sb2 = new StringBuilder(); } else if (ct.equals(ConceptType.OBJECTPROPERTY)) { sb1.append(", an object property with "); sb1.append(typeCheckInfo.getTypeToExprRelationship()); sb1.append(" "); sb2= new StringBuilder(); } else if (ct.equals(ConceptType.VARIABLE)) { sb1.append(", a variable of type "); sb2 = new StringBuilder(); } } if (typeCheckInfo.getCompoundTypes() != null) { List<String> compoundTypeList = new ArrayList<String>(); for (int i = 0; i < typeCheckInfo.getCompoundTypes().size(); i++) { TypeCheckInfo tci = typeCheckInfo.getCompoundTypes().get(i); String[] tciresult = getTypeCheckInfoDescription(tci); if (tciresult != null && tciresult.length > 1 && !compoundTypeList.toString().contains(tciresult[1])) { compoundTypeList.add(tciresult[1]); } } if (sb2 == null) sb2 = new StringBuilder(); for (int i = 0; i < compoundTypeList.size(); i++) { if (i > 0) sb2.append(" or "); sb2.append(compoundTypeList.get(i)); } } else { if (typeCheckInfo.getRangeValueType().equals(RangeValueType.LIST) || (typeCheckInfo.getTypeCheckType() instanceof NamedNode && ((NamedNode)typeCheckInfo.getTypeCheckType()).isList())) { if (sb2 == null) sb2 = new StringBuilder(); String lengthOrRange = getListLengthAsString((NamedNode)typeCheckInfo.getTypeCheckType()); sb2.append("a List " + lengthOrRange + "of values of type "); } if (sb2 != null && typeCheckInfo.getTypeCheckType() != null) { sb2.append(getModelProcessor().nodeToString(typeCheckInfo.getTypeCheckType())); } else if (typeCheckInfo.getExplicitValue() != null) { RDFNode ev = typeCheckInfo.getExplicitValue(); if (typeCheckInfo.getExplicitValueType().equals(ExplicitValueType.VALUE)) { sb1.replace(0, sb1.length(), "explicit value "); } if (ev.isLiteral()) { try { sb2.append(getModelProcessor().rdfNodeToString(ev.asLiteral())); } catch (DatatypeFormatException e) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_CHECK_EXCEPTION.get("Datatype Format"), typeCheckInfo.context); //addError(e.getMessage(), typeCheckInfo.context); } } else { sb2.append(getModelProcessor().rdfNodeToString(ev)); } } } String[] result = sb2 != null ? new String[2] : new String[1]; result[0] = sb1.toString(); if (sb2 != null) { result[1] = sb2.toString(); } return result; } // String leftName = leftTypeCheckInfo != null ? leftTypeCheckInfo.expressionType != null ? leftTypeCheckInfo.expressionType.toString() : "UNIDENTIFIED" : "UNIDENTIFIED"; // String rightName = rightTypeCheckInfo != null ? rightTypeCheckInfo.expressionType != null ? rightTypeCheckInfo.expressionType.toString() : "UNIDENTIFIED" : "UNIDENTIFIED"; // String leftType; // String leftRange; // if (leftTypeCheckInfo == null) { // leftType = "UNIDENTIFIED"; // leftRange = "UNIDENTIFIED"; // else if (leftTypeCheckInfo.compoundTypes == null) { // leftType = leftTypeCheckInfo.typeCheckType != null ? leftTypeCheckInfo.typeCheckType.toString() : "UNIDENTIFIED"; // leftRange = leftTypeCheckInfo.rangeValueType != null ? leftTypeCheckInfo.rangeValueType.toString() : "UNIDENTIFIED"; // else { // StringBuilder sb = new StringBuilder(); // for (int i = 0; i < leftTypeCheckInfo.getCompoundType().size(); i++) { // if (i > 0) { // sb.append(" or "); // TypeCheckInfo tic = leftTypeCheckInfo.getCompoundType().get(i); // sb.append(tic != null ? tic.typeCheckType != null ? tic.typeCheckType.toString() : "UNIDENTIFIED" : "UNIDENTIFIED"); // leftType = sb.toString(); // sb = new StringBuilder(); // for (int i = 0; i < leftTypeCheckInfo.getCompoundType().size(); i++) { // if (i > 0) { // sb.append(" or "); // TypeCheckInfo tic = leftTypeCheckInfo.getCompoundType().get(i); // sb.append(tic != null ? tic.rangeValueType != null ? tic.rangeValueType.toString() : "UNIDENTIFIED" : "UNIDENTIFIED"); // leftRange = sb.toString(); // return null; } private String getListLengthAsString(NamedNode node) { StringBuilder sb = new StringBuilder(); int length = node.getListLength(); int minLength = node.getMinListLength(); int maxLength = node.getMaxListLength(); if(length != -1 || minLength != -1 || maxLength != -1) { sb.append("length "); if(minLength != -1 || maxLength != -1) { if(minLength == -1) { sb.append("0"); }else { sb.append(minLength); } sb.append("-"); if(maxLength == -1) { sb.append("*"); }else { sb.append(maxLength); } }else { sb.append(length); } sb.append(" "); } return sb.toString(); } private boolean rdfPropertyTypeCheckInfoHasRange(TypeCheckInfo typeCheckInfo) { if (typeCheckInfo.getTypeCheckType() != null) { return true; } if (typeCheckInfo.getCompoundTypes() != null) { for (int i = 0; i < typeCheckInfo.getCompoundTypes().size(); i++) { TypeCheckInfo next = typeCheckInfo.getCompoundTypes().get(i); boolean b = rdfPropertyTypeCheckInfoHasRange(next); if (b) { return true; } } } return false; } protected boolean skipOperations(List<String> operations) { if(operations.contains("and") || operations.contains("or")){ return true; } return false; } protected TypeCheckInfo getType(EObject expression) throws InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException, CircularDefinitionException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException{ if (expressionsTypeCheckCache != null && expressionsTypeCheckCache.containsKey(expression)) { return expressionsTypeCheckCache.get(expression); } TypeCheckInfo returnedTci = null; if(expression instanceof Name){ returnedTci = getType((Name)expression); }else if(expression instanceof SadlResource){ returnedTci = getType((SadlResource)expression); } else if(expression instanceof Declaration){ SadlTypeReference decltype = ((Declaration)expression).getType(); if (decltype != null) { returnedTci = getType(decltype); } else { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.NULL_TYPE.toString(), expression); } //Need to return passing case for time being // ConceptName declarationConceptName = new ConceptName("todo"); // return new TypeCheckInfo(declarationConceptName, declarationConceptName); } else if(expression instanceof StringLiteral || expression instanceof SadlStringLiteral) { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.xstring.getURI(), NodeType.DataTypeNode)); ConceptName stringLiteralConceptName = getModelProcessor().namedNodeToConceptName(tctype); returnedTci = new TypeCheckInfo(stringLiteralConceptName, tctype, this, expression); } else if(expression instanceof NumberLiteral || expression instanceof SadlNumberLiteral){ BigDecimal value = null; Literal litval = null; if (expression instanceof NumberLiteral) { value = ((NumberLiteral)expression).getValue(); } else { // SadlNumberLiteral if (((SadlNumberLiteral)expression).getUnit() != null && !getModelProcessor().ignoreUnittedQuantities) { return getUnittedQuantityTypeCheckInfo(expression, ((SadlNumberLiteral)expression).getUnit()); } String strval = ((SadlNumberLiteral)expression).getLiteralNumber().toPlainString(); if (strval.indexOf('.') >= 0) { value = BigDecimal.valueOf(Double.parseDouble(strval)); } else { value = BigDecimal.valueOf(Long.parseLong(strval)); } } if (expression.eContainer() != null && expression.eContainer() instanceof UnaryExpression && ((UnaryExpression)expression.eContainer()).getOp().equals("-")) { value = value.negate(); } ConceptName numberLiteralConceptName = null; Node tctype = null; if (value.stripTrailingZeros().scale() <= 0 || value.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0) { if (value.compareTo(BigDecimal.valueOf(MAX_INT)) <= 0 && value.compareTo(BigDecimal.valueOf(MIN_INT)) >= 0) { tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.xint.getURI(), NodeType.DataTypeNode)); numberLiteralConceptName = getModelProcessor().namedNodeToConceptName((NamedNode) tctype); litval = theJenaModel.createTypedLiteral(value.intValue()); } else { numberLiteralConceptName = new ConceptName(XSD.xlong.getURI()); tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.xlong.getURI(), NodeType.DataTypeNode)); if (value.compareTo(BigDecimal.valueOf(MAX_LONG)) > 0 || value.compareTo(BigDecimal.valueOf(MIN_LONG)) < 0) { issueAcceptor.addError("Error converting to a number", expression); } else { litval = theJenaModel.createTypedLiteral(value.longValue()); } } } else { numberLiteralConceptName = new ConceptName(XSD.decimal.getURI()); litval = theJenaModel.createTypedLiteral(value.doubleValue()); tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.decimal.getURI(), NodeType.DataTypeNode)); } numberLiteralConceptName.setType(ConceptType.RDFDATATYPE); TypeCheckInfo litTci; if (litval != null) { litTci = new TypeCheckInfo(numberLiteralConceptName, litval, ExplicitValueType.VALUE, this, expression); } else { litTci = new TypeCheckInfo(numberLiteralConceptName, createNamedNode(numberLiteralConceptName.toFQString(), OntConceptType.LITERAL), this, expression); } litTci.setTypeCheckType(tctype); returnedTci = litTci; } else if (expression instanceof UnitExpression) { returnedTci = getUnittedQuantityTypeCheckInfo(((UnitExpression)expression).getLeft(), ((UnitExpression)expression).getUnit()); } else if(expression instanceof BooleanLiteral || expression instanceof SadlBooleanLiteral){ returnedTci = createBooleanTypeCheckInfo(expression); } else if(expression instanceof Constant){ returnedTci = getType((Constant)expression); } else if (expression instanceof SadlConstantLiteral) { returnedTci = getType((SadlConstantLiteral)expression); } else if(expression instanceof ValueTable){ ConceptName declarationConceptName = new ConceptName("TODO"); returnedTci = new TypeCheckInfo(declarationConceptName, null, this, expression); } else if(expression instanceof PropOfSubject){ returnedTci = getType((PropOfSubject)expression); } else if(expression instanceof SubjHasProp){ returnedTci = getType((SubjHasProp)expression); } else if (SadlASTUtils.isCommaSeparatedAbbreviatedExpression(expression)) { // validate the property initializations within validateCommaSeparatedAbreviatedExpression((SubjHasProp) expression); returnedTci = getType(((SubjHasProp)expression).getLeft()); } else if(expression instanceof UnaryExpression){ returnedTci = getType(((UnaryExpression) expression).getExpr()); } else if (expression instanceof SadlUnaryExpression) { returnedTci = getType(((SadlUnaryExpression)expression).getValue()); } else if(expression instanceof ElementInList){ returnedTci = getType((ElementInList)expression); } else if(expression instanceof BinaryOperation){ returnedTci = getType((BinaryOperation)expression); } else if (expression instanceof Sublist) { // the type is the type of the list TypeCheckInfo listtype = getType((((Sublist)expression).getList())); if (listtype != null && !listtype.getRangeValueType().equals(RangeValueType.LIST)) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.IS_NOT_A.get("this","list"), ((Sublist)expression).getList()); } returnedTci = listtype; } else if (expression instanceof SadlPrimitiveDataType) { returnedTci = getType((SadlPrimitiveDataType)expression); } else if (expression instanceof SadlSimpleTypeReference) { returnedTci = getType((SadlSimpleTypeReference)expression); } else if (expression instanceof SadlIntersectionType) { returnedTci = getType((SadlIntersectionType)expression); } else if (expression instanceof SadlPropertyCondition) { returnedTci = getType((SadlPropertyCondition)expression); } else if (expression instanceof SadlResource) { returnedTci = getType((SadlResource)expression); } else if (expression instanceof SadlTypeReference) { returnedTci = getType((SadlTypeReference)expression); } else if (expression instanceof SadlUnionType) { returnedTci = getType((SadlUnionType)expression); } else if (expression instanceof SadlInstance) { returnedTci = getType((SadlInstance)expression); } else if (expression != null) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.DECOMPOSITION_ERROR.get(expression.toString()), expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } throw new TranslationException("Unhandled expression type: " + expression.getClass().getCanonicalName()); } if (returnedTci != null) { expressionsTypeCheckCache.put(expression, returnedTci); } return returnedTci; } private TypeCheckInfo getType(SadlInstance expression) throws InvalidTypeException, DontTypeCheckException, CircularDefinitionException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, CircularDependencyException, PropertyWithoutRangeException { SadlResource inst = expression.getInstance(); if (inst == null) { SadlTypeReference typ = expression.getType(); if (typ != null && typ instanceof SadlSimpleTypeReference) { inst = ((SadlSimpleTypeReference)typ).getType(); if (declarationExtensions.getConceptUri(inst).equals(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI) && getModelProcessor().ignoreUnittedQuantities) { if (expression instanceof SadlNestedInstance) { Iterator<SadlPropertyInitializer> pinititr = ((SadlNestedInstance)expression).getPropertyInitializers().iterator(); while (pinititr.hasNext()) { SadlPropertyInitializer spinit = pinititr.next(); if (declarationExtensions.getConceptUri(spinit.getProperty()).equals(SadlConstants.SADL_IMPLICIT_MODEL_VALUE_URI)) { return getType(spinit.getProperty()); } } } } } } if (inst != null) { TypeCheckInfo insttci = getType(inst); if (insttci != null && insttci.getTypeCheckType() == null) { SadlTypeReference typ = expression.getType(); if (typ != null && typ instanceof SadlSimpleTypeReference) { SadlResource typsr = ((SadlSimpleTypeReference)typ).getType(); insttci.setTypeCheckType(getModelProcessor().validateNamedNode(new NamedNode(declarationExtensions.getConceptUri(typsr), NodeType.ClassNode))); } } return insttci; } else { issueAcceptor.addError("Unhandled condition of SadlInstance", expression); return null; } } private TypeCheckInfo getType(ElementInList expression) throws InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException, CircularDefinitionException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { Expression el = expression.getElement(); if (el instanceof PropOfSubject) { TypeCheckInfo listtype = getType(((PropOfSubject)el).getRight()); if (listtype == null) { getModelProcessor().addIssueToAcceptor("Unable to get the List type", el); } else if (listtype.getRangeValueType() != RangeValueType.LIST) { getModelProcessor().addIssueToAcceptor("Expected a List", el); } else { // the element's type is the type of the list but not necessarily a list listtype = convertListTypeToElementOfListType(listtype); } return listtype; } else { return getType(el); } // else { // getModelProcessor().addIssueToAcceptor(SadlErrorMessages.UNHANDLED.get("element type in element in list construct. ", el.getClass().getCanonicalName() + "; please report"), expression); // if (metricsProcessor != null) { // metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_ERROR_URI); // return null; } private TypeCheckInfo getType(SubjHasProp expression) throws CircularDefinitionException, DontTypeCheckException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { if (SadlASTUtils.isUnitExpression(expression)) { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI, NodeType.ClassNode)); ConceptName uqcn = getModelProcessor().namedNodeToConceptName(tctype); TypeCheckInfo tci = new TypeCheckInfo(uqcn, tctype, this, expression); tci.setTypeToExprRelationship(SadlASTUtils.getUnitAsString(expression)); return tci; } else if (expression.isComma() && expression.getRight() == null) { issueAcceptor.addError(SadlErrorMessages.TYPE_COMPARISON.toString(), expression); return null; } else if (!getModelProcessor().isDeclaration(expression) && expression.eContainer() instanceof BinaryOperation || expression.eContainer() instanceof SelectExpression || expression.eContainer() instanceof AskExpression || expression.eContainer() instanceof ConstructExpression) { // we are comparing or assigning this to something else so we want the type of the root (if there is a chain) property if (expression.getProp() instanceof SadlResource) { SadlResource prop = expression.getProp(); return getType(prop); } else { issueAcceptor.addError("This subject-has-property construct isn't properly validated, please report.", expression); return null; } } else { if (modelProcessor.getTarget() instanceof Rule) { return getType(expression.getProp()); } else { Declaration subjHasPropInDeclaration = subjHasPropIsDeclaration((SubjHasProp) expression); // are we in a Declaration (a real declaration--the type is a class) if (subjHasPropInDeclaration != null) { return getType(subjHasPropInDeclaration); } else { issueAcceptor.addError("This appears to be a declaration that isn't fully supported; should it be nested (in parentheses)", expression); return null; } } } } private TypeCheckInfo getType(BinaryOperation expression) throws CircularDependencyException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException, CircularDefinitionException, InvalidTypeException, PropertyWithoutRangeException { List<String> operations = Arrays.asList(expression.getOp().split("\\s+")); TypeCheckInfo leftTypeCheckInfo = unifyCompoundTypeCheckInfos(getType(expression.getLeft())); TypeCheckInfo rightTypeCheckInfo = unifyCompoundTypeCheckInfos(getType(expression.getRight())); if (expression.getLeft() instanceof PropOfSubject && ((BinaryOperation)expression).getRight() instanceof Declaration) { TypeCheckInfo subjtype = getType(((PropOfSubject)expression.getLeft()).getRight()); if (subjtype != null) { Node subject = subjtype.getTypeCheckType(); if (subject != null) { ConceptIdentifier ltcetype = leftTypeCheckInfo.getExpressionType(); if (ltcetype instanceof ConceptName) { NamedNode pred = getModelProcessor().conceptNameToNamedNode((ConceptName) ltcetype); TripleElement tr = new TripleElement(subject, pred, rightTypeCheckInfo.getTypeCheckType()); getModelProcessor().handleLocalRestriction(expression, tr); } } } } TypeCheckInfo binopreturn = combineBinaryOperationTypesWithComparison(operations, expression, expression.getLeft(), expression.getRight(), leftTypeCheckInfo, rightTypeCheckInfo, ImplicitPropertySide.NONE); if (getModelProcessor().isNumericOperator(expression.getOp())) { TypeCheckInfo uqTci = getTypeCompatibleWithOperationOnUnittedQuantities(((BinaryOperation)expression).getOp(), leftTypeCheckInfo, rightTypeCheckInfo); if (uqTci != null) { return uqTci; } if (leftTypeCheckInfo != null && !isNumeric(leftTypeCheckInfo) && !isNumericWithImpliedProperty(leftTypeCheckInfo, ((BinaryOperation)expression).getLeft())) { getModelProcessor().addIssueToAcceptor("Numeric operator requires numeric arguments", ((BinaryOperation)expression).getLeft()); } if (rightTypeCheckInfo != null && !isNumeric(rightTypeCheckInfo) && !isNumericWithImpliedProperty(rightTypeCheckInfo, ((BinaryOperation)expression).getRight())) { getModelProcessor().addIssueToAcceptor("Numeric operator requires numeric arguments", ((BinaryOperation)expression).getRight()); } NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.decimal.getURI(), NodeType.DataTypeNode)); ConceptName decimalLiteralConceptName = getModelProcessor().namedNodeToConceptName(tctype); decimalLiteralConceptName.setType(ConceptType.RDFDATATYPE); return new TypeCheckInfo(decimalLiteralConceptName, tctype, this, expression); } if (binopreturn != null) { return binopreturn; } else { return createBooleanTypeCheckInfo(expression); } } private TypeCheckInfo createBooleanTypeCheckInfo(EObject expression) throws TranslationException, InvalidNameException, InvalidTypeException { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.xboolean.getURI(), NodeType.DataTypeNode)); ConceptName booleanLiteralConceptName = getModelProcessor().namedNodeToConceptName(tctype); return new TypeCheckInfo(booleanLiteralConceptName, tctype, this, expression); } private TypeCheckInfo getTypeCompatibleWithOperationOnUnittedQuantities(String op, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) { if (!modelProcessor.isNumericOperator(op)) { return null; } if (leftTypeCheckInfo == null || rightTypeCheckInfo == null) { return null; } if (!leftTypeCheckInfo.getTypeCheckType().toFullyQualifiedString().equals(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI) || !rightTypeCheckInfo.getTypeCheckType().toFullyQualifiedString().equals(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI)) { return null; } if (op.equals("+") || op.equals("-")) { if (leftTypeCheckInfo.getTypeToExprRelationship() != null && rightTypeCheckInfo.getTypeToExprRelationship() != null && leftTypeCheckInfo.getTypeToExprRelationship().equals(rightTypeCheckInfo.getTypeToExprRelationship())) { return leftTypeCheckInfo; } if (leftTypeCheckInfo.getTypeToExprRelationship().equals(RANGE) && !rightTypeCheckInfo.getTypeToExprRelationship().equals(RANGE)) { // could issue warning that units may not match return leftTypeCheckInfo; } if (!leftTypeCheckInfo.getTypeToExprRelationship().equals(RANGE) && rightTypeCheckInfo.getTypeToExprRelationship().equals(RANGE)) { // could issue warning that units may not match return rightTypeCheckInfo; } } if (op.equals("/") || op.equals("*") || op.equals("^")) { if (leftTypeCheckInfo.getTypeToExprRelationship() != null && rightTypeCheckInfo.getTypeToExprRelationship() != null) { leftTypeCheckInfo.setTypeToExprRelationship(leftTypeCheckInfo.getTypeToExprRelationship() + op + rightTypeCheckInfo.getTypeToExprRelationship()); return leftTypeCheckInfo; } } return null; } private Declaration getEmbeddedDeclaration(EObject expr) { if (expr instanceof SubjHasProp) { return getEmbeddedDeclaration(((SubjHasProp)expr).getLeft()); } else if (expr instanceof BinaryOperation) { Declaration decl = getEmbeddedDeclaration(((BinaryOperation)expr).getLeft()); if (decl != null) { return decl; } decl = getEmbeddedDeclaration(((BinaryOperation)expr).getRight()); if (decl != null) { return decl; } } else if (expr instanceof UnaryExpression && ((UnaryExpression)expr).getExpr() instanceof Declaration) { return (Declaration) ((UnaryExpression)expr).getExpr(); } else if (expr instanceof Declaration) { return (Declaration) expr; } return null; } private TypeCheckInfo getUnittedQuantityTypeCheckInfo(EObject expression, String unit) throws InvalidTypeException, InvalidNameException, TranslationException { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI, NodeType.ClassNode)); ConceptName uqcn = getModelProcessor().namedNodeToConceptName(tctype); List<ConceptName> impliedProperties = getImpliedProperties(theJenaModel.getOntResource(uqcn.getUri())); if (impliedProperties != null) { TypeCheckInfo tci = new TypeCheckInfo(uqcn, tctype, impliedProperties, this, expression); tci.setTypeToExprRelationship(unit); return tci; } else { TypeCheckInfo tci = new TypeCheckInfo(uqcn, tctype, this, expression); tci.setTypeToExprRelationship(unit); return tci; } } protected void validateCommaSeparatedAbreviatedExpression(SubjHasProp expression) throws DontTypeCheckException, CircularDefinitionException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { TypeCheckInfo proptct = getType(expression.getProp()); TypeCheckInfo rghttct = getType(expression.getRight()); if (!compareTypesUsingImpliedProperties(Arrays.asList("is"), expression.getProp(), expression.getRight(), proptct, rghttct, ImplicitPropertySide.NONE)) { StringBuilder errorMessageBuilder = new StringBuilder(); createErrorMessage(errorMessageBuilder, proptct, rghttct, "property initialization", true, expression); } } protected Declaration subjHasPropIsDeclaration(SubjHasProp expression) throws DontTypeCheckException, CircularDefinitionException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { if (expression.getLeft() instanceof Declaration) { TypeCheckInfo declType = getType(((Declaration)expression.getLeft()).getType()); if (declType == null) { // throw new TranslationException("Declaration has no type"); return null; // this happens when a file is open in the editor and there is a clean/build } Node tct = declType.getTypeCheckType(); if (tct instanceof NamedNode && ((NamedNode)tct).getNodeType() != null && ((NamedNode)tct).getNodeType().equals(NodeType.ClassNode)) { return (Declaration)expression.getLeft(); } } if (expression.getLeft() instanceof SubjHasProp) { return subjHasPropIsDeclaration((SubjHasProp)expression.getLeft()); } return null; } private TypeCheckInfo unifyCompoundTypeCheckInfos(TypeCheckInfo tci) throws CircularDependencyException, InvalidNameException, TranslationException, InvalidTypeException { // if this is a compound TypeCheckInfo, look to make sure that one isn't a subclass of another and eliminate lower classes if (tci != null && tci.getCompoundTypes() != null) { int size = tci.getCompoundTypes().size(); if (size == 1) { return tci.getCompoundTypes().get(0); } List<TypeCheckInfo> considered = new ArrayList<TypeCheckInfo>(); considered.add(tci.getCompoundTypes().get(0)); List<TypeCheckInfo> toEliminate = null; int index = 1; for (int i = index; i < size; i++) { TypeCheckInfo newTci = tci.getCompoundTypes().get(i); RangeValueType newRvt = newTci.getRangeValueType(); if (newRvt.equals(RangeValueType.CLASS_OR_DT)) { Node newTct = newTci.getTypeCheckType(); if (newTct instanceof NamedNode) { OntClass newOr = theJenaModel.getOntClass(((NamedNode)newTct).toFullyQualifiedString()); if (newOr != null) { for (int j = 0; j < considered.size(); j++) { if (newRvt.equals(considered.get(j).getRangeValueType())) { Node consideredTct = considered.get(j).getTypeCheckType(); if (consideredTct instanceof NamedNode) { OntClass consideredOr = theJenaModel.getOntClass(((NamedNode)consideredTct).toFullyQualifiedString()); if (consideredOr != null) { if (SadlUtils.classIsSubclassOf(newOr, consideredOr, true, null)) { if (toEliminate == null) toEliminate = new ArrayList<TypeCheckInfo>(); toEliminate.add(newTci); } else if (SadlUtils.classIsSubclassOf(consideredOr, newOr, true, null)) { if (toEliminate == null) toEliminate = new ArrayList<TypeCheckInfo>(); toEliminate.add(considered.get(j)); } } } else { throw new TranslationException("Non-NamedNode type not handled yet"); } } } } } else { throw new TranslationException("Non-NamedNode type not handled yet"); } } } if (toEliminate != null) { for (int i = 0; i < toEliminate.size(); i++) { if (tci.getCompoundTypes().contains(toEliminate.get(i))) { tci.getCompoundTypes().remove(toEliminate.get(i)); } } } size = tci.getCompoundTypes().size(); if (size == 1) { return tci.getCompoundTypes().get(0); } } return tci; } private boolean isNumericWithImpliedProperty(TypeCheckInfo tci, Expression expr) throws DontTypeCheckException, InvalidNameException, InvalidTypeException, TranslationException { if (tci.getImplicitProperties() != null) { Iterator<ConceptName> litr = tci.getImplicitProperties().iterator(); while (litr.hasNext()) { ConceptName cn = litr.next(); Property prop = theJenaModel.getProperty(cn.getUri()); if (prop.canAs(ObjectProperty.class)) { cn.setType(ConceptType.OBJECTPROPERTY); } else if (prop.canAs(DatatypeProperty.class)) { cn.setType(ConceptType.DATATYPEPROPERTY); } else { cn.setType(ConceptType.RDFPROPERTY); } TypeCheckInfo newtci = getTypeInfoFromRange(cn, prop, expr); if (isNumeric(newtci)) { return true; } } } return false; } private boolean isNumeric(TypeCheckInfo tci) throws InvalidTypeException { Node ci; if (tci != null) { if (tci.getTypeCheckType() != null) { ci = tci.getTypeCheckType(); if (ci instanceof NamedNode) { return getModelProcessor().isNumericType(((NamedNode)ci).toFullyQualifiedString()); } } else if (tci.getExplicitValueType() != null) { //TODO this is incomplete; more examples needed AWC 12/19/2016 ExplicitValueType evt = tci.getExplicitValueType(); if (evt.equals(ExplicitValueType.RESTRICTION)) { issueAcceptor.addWarning("Explicit value type is RESTRICTION, which isn't yet handled. Please report with use case.", tci.context); } else if (tci.getExpressionType() instanceof ConceptName){ return getModelProcessor().isNumericType((ConceptName) tci.getExpressionType()); } } } return false; } private boolean isUnittedQuantity(TypeCheckInfo tci) { if (tci != null) { Node tctn = tci.getTypeCheckType(); if (tctn instanceof NamedNode && ((NamedNode)tctn).toFullyQualifiedString().equals(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI)) { return true; } } return false; } private TypeCheckInfo convertListTypeToElementOfListType(TypeCheckInfo listtype) { Node tctype = listtype.getTypeCheckType(); if (tctype instanceof NamedNode) { try { NamedNode clonedNode = (NamedNode) tctype.clone(); clonedNode.setList(false); listtype.setTypeCheckType(clonedNode); } catch (CloneNotSupportedException e) { logger.error(e.getMessage()); } } listtype.setRangeValueType(RangeValueType.CLASS_OR_DT); if(listtype.getCompoundTypes() != null){ // compound Iterator<TypeCheckInfo> tci_iter = listtype.getCompoundTypes().iterator(); while(tci_iter.hasNext()){ convertListTypeToElementOfListType(tci_iter.next()); } } return listtype; } private TypeCheckInfo convertElementOfListToListType(TypeCheckInfo elementtype) { Node tctype = elementtype.getTypeCheckType(); if (tctype instanceof NamedNode) { try { NamedNode clonedNode = (NamedNode) tctype.clone(); clonedNode.setList(true); elementtype.setTypeCheckType(clonedNode); } catch (CloneNotSupportedException e) { logger.error(e.getMessage()); } } elementtype.setRangeValueType(RangeValueType.LIST); if(elementtype.getCompoundTypes() != null){ // compound Iterator<TypeCheckInfo> tci_iter = elementtype.getCompoundTypes().iterator(); while(tci_iter.hasNext()){ convertListTypeToElementOfListType(tci_iter.next()); } } return elementtype; } protected TypeCheckInfo getType(Constant expression) throws DontTypeCheckException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, CircularDefinitionException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { //What do we do about the rest of the constants? /*'--' | 'a'? 'type' ;*/ String constant = expression.getConstant(); if(constant.equals(SadlConstants.CONSTANT_PI) || constant.equals(SadlConstants.CONSTANT_E)){ NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.decimal.getURI(), NodeType.DataTypeNode)); ConceptName constantConceptName = getModelProcessor().namedNodeToConceptName(tctype); return new TypeCheckInfo(constantConceptName, tctype, this, expression); } else if(constant.equals("length") || constant.equals("count") || constant.equals("index")){ NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.xint.getURI(), NodeType.DataTypeNode)); ConceptName constantConceptName = getModelProcessor().namedNodeToConceptName(tctype); return new TypeCheckInfo(constantConceptName, tctype, this, expression); } else if(constant.endsWith("element") && (constant.startsWith("first") || constant.startsWith("last"))){ //Handle list types??? ConceptName declarationConceptName = new ConceptName(constant); return new TypeCheckInfo(declarationConceptName, null, this, expression); } // else if (constant.endsWith("value")) { // throw new DontTypeCheckException(); else if (expression instanceof Constant && (((Constant)expression).getConstant().equals("value") || ((Constant)expression).getConstant().equals("type"))) { Sublist slexpr = getSublistContainer(expression); if (slexpr != null) { TypeCheckInfo matchTci = getType(slexpr.getList()); // matchTci.setRangeValueType(RangeValueType.CLASS_OR_DT); return matchTci; } issueAcceptor.addError("Unable to get sublist type", expression); return getType(expression); } else if (constant.equals("a type")) { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(RDFS.subClassOf.getURI(), NodeType.ClassNode)); ConceptName rdfType = getModelProcessor().namedNodeToConceptName(tctype); return new TypeCheckInfo(rdfType, tctype, this, expression); } else if(constant.equals(SadlConstants.CONSTANT_NONE)){ ConstantNode tctype = new ConstantNode(SadlConstants.CONSTANT_NONE); ConceptName constantConceptName = new ConceptName(SadlConstants.CONSTANT_NONE); return new TypeCheckInfo(constantConceptName, tctype, this, expression); } else if (constant.equals("known")) { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(constant, NodeType.InstanceNode)); ConceptName constantConceptName = getModelProcessor().namedNodeToConceptName(tctype); return new TypeCheckInfo(constantConceptName, tctype, this, expression); } else { // let any subclass validators do their thing lastSuperCallExpression = expression; return getType((Constant)expression); } } private TypeCheckInfo getType(SadlConstantLiteral expression) throws TranslationException, InvalidNameException, InvalidTypeException { String term = expression.getTerm(); Literal litval = null; if (term.equals(SadlConstants.CONSTANT_PI)) { litval = theJenaModel.createTypedLiteral(Math.PI); } else if (term.equals(SadlConstants.CONSTANT_E)) { litval = theJenaModel.createTypedLiteral(Math.E); } else { throw new TranslationException("Unhandled SadlConstantLiteral type: " + expression.getClass().getCanonicalName()); } NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.decimal.getURI(), NodeType.DataTypeNode)); ConceptName numberLiteralConceptName = getModelProcessor().namedNodeToConceptName(tctype); TypeCheckInfo litTci = new TypeCheckInfo(numberLiteralConceptName, litval, ExplicitValueType.VALUE, this, expression); litTci.setTypeCheckType(tctype); return litTci; } private boolean isVariable(TypeCheckInfo tci) { if (tci == null) return false; Node ci = tci.getTypeCheckType(); if (ci instanceof NamedNode && ((NamedNode)ci).getNodeType() != null && ((NamedNode)ci).getNodeType().equals(NodeType.VariableNode)) { return true; } return false; } private TypeCheckInfo getType(SadlTypeReference expression) throws DontTypeCheckException, CircularDefinitionException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { if (expression instanceof SadlIntersectionType) { return getType((SadlIntersectionType)expression); } else if (expression instanceof SadlPrimitiveDataType) { return getType((SadlPrimitiveDataType)expression); } else if (expression instanceof SadlPropertyCondition) { return getType((SadlPropertyCondition)expression); } else if (expression instanceof SadlSimpleTypeReference) { return getType((SadlSimpleTypeReference)expression); } else if (expression instanceof SadlUnionType) { return getType((SadlUnionType)expression); } getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_REFERENCE_ERROR.get(expression.getClass().getCanonicalName()), expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, null, this, expression); } private TypeCheckInfo getType(SadlIntersectionType expression) { ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, null, this, expression); } private TypeCheckInfo getType(SadlPrimitiveDataType expression) throws TranslationException, InvalidNameException, InvalidTypeException { TypeCheckInfo tci = getType(expression.getPrimitiveType()); tci.setContext(this, expression); return tci; } private TypeCheckInfo getType(SadlDataType primitiveType) throws TranslationException, InvalidNameException, InvalidTypeException { String nm = primitiveType.getName(); NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.getURI() + nm, NodeType.DataTypeNode)); ConceptName cn = getModelProcessor().namedNodeToConceptName(tctype); return new TypeCheckInfo(cn, tctype, this, null); } private TypeCheckInfo getType(SadlPropertyCondition expression) { ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, null, this, expression); } private TypeCheckInfo getType(SadlSimpleTypeReference expression) throws DontTypeCheckException, CircularDefinitionException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { TypeCheckInfo tci = getType(expression.getType()); if (expression.isList()) { tci.setRangeValueType(RangeValueType.LIST); int[] lenRest = getModelProcessor().getLengthRestrictions(expression.eContainer()); Node tctype = tci.getTypeCheckType(); if (lenRest != null && tctype instanceof NamedNode) { if (lenRest.length == 1) { ((NamedNode)tctype).setListLength(lenRest[0]); } else if (lenRest.length == 2) { ((NamedNode)tctype).setMinListLength(lenRest[0]); ((NamedNode)tctype).setMaxListLength(lenRest[1]); } } } return tci; } private TypeCheckInfo getType(SadlUnionType expression) { ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, null, this, expression); } private TypeCheckInfo getType(PropOfSubject expression) throws InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException, CircularDefinitionException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { String ofOp = expression.getOf(); Expression predicate = expression.getLeft(); Expression subject = expression.getRight(); boolean isNegated = false; if (predicate instanceof UnaryExpression && ((UnaryExpression)predicate).getOp().equals("not")) { predicate = ((UnaryExpression)predicate).getExpr(); isNegated = true; } if (predicate instanceof Constant) { String cnstval = ((Constant)predicate).getConstant(); TypeCheckInfo subjtype = null; if (constantRequiresListNext(cnstval)) { subjtype = getType(subject); if (subjtype != null && !subjtype.getRangeValueType().equals(RangeValueType.LIST)) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.MUST_BE_APPLIED_TO_LIST.get(cnstval, getTypeCheckTypeString(subjtype)), subject); } } else if (constantFollowedByIntThenList(cnstval)) { subjtype = getType(subject); } else if (constantFollowedByElementThenList(cnstval)) { subjtype = getType(subject); } if (cnstval.endsWith("length") || cnstval.equals("count") || cnstval.endsWith("index")) { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.xint.getURI(), NodeType.DataTypeNode)); ConceptName nlcn = getModelProcessor().namedNodeToConceptName(tctype); return new TypeCheckInfo(nlcn, tctype, this, expression); } else if (subjtype != null && (cnstval.endsWith(" element"))) { if (subjtype != null && (cnstval.equals("first element") || cnstval.equals("last element")) ) { subjtype.setRangeValueType(RangeValueType.CLASS_OR_DT); // keep type but change from List to reflect this is an element of the list return subjtype; } String article = cnstval.substring(0, cnstval.indexOf(" ")); subjtype.setRangeValueType(RangeValueType.CLASS_OR_DT); // keep type but change from List to reflect this is an element of the list if (subjtype.getTypeCheckType() instanceof NamedNode) { if (((NamedNode)subjtype.getTypeCheckType()).getNodeType().equals(NodeType.ClassListNode)) { ((NamedNode)subjtype.getTypeCheckType()).setNodeType(NodeType.ClassNode); } else { throw new TranslationException("unhandled element of list type check type, NamedNode but not ClassListNode"); } } else { throw new TranslationException("unhandled element of list type, type check type not a NamedNode"); } return subjtype; } else if (cnstval.equals("a type")) { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(RDFS.subClassOf.getURI(), NodeType.ClassNode)); ConceptName rdfType = getModelProcessor().namedNodeToConceptName(tctype); return new TypeCheckInfo(rdfType, tctype, this, expression); } else { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.UNHANDLED.get("Constant Property", cnstval), expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } } } else if (predicate instanceof ElementInList) { // this is like the constant "element" TypeCheckInfo subjtype = getType(subject); subjtype = convertListTypeToElementOfListType(subjtype); subjtype.setAdditionalInformation("element of"); return subjtype; } boolean isElementInListConstruct = false; if (predicate instanceof Name) { try { OntConceptType predtype = declarationExtensions.getOntConceptType(((Name)predicate).getName()); if (ofOp != null && ofOp.equals("in")) { // this is a list construct: element in list isElementInListConstruct = true; return null; } else if (!predtype.equals(OntConceptType.CLASS_PROPERTY) && !predtype.equals(OntConceptType.DATATYPE_PROPERTY) && !predtype.equals(OntConceptType.RDF_PROPERTY) && !predtype.equals(OntConceptType.ANNOTATION_PROPERTY)) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.EXPECTED_A.get("property in property chain"), predicate); //String preduri = declarationExtensions.getConceptUri(((Name)predicate).getName()); } } catch (CircularDefinitionException e) { e.printStackTrace(); } } boolean validSubject = true; if (subject instanceof Name || subject instanceof Declaration) { // check for applicable local restriction first TypeCheckInfo predicateType = null; try { List<Node> lrs = getApplicableLocalRestriction(subject, predicate); if (lrs != null) { if (predicate instanceof Name) { String propuri = declarationExtensions.getConceptUri(((Name)predicate).getName()); ConceptName pcn = new ConceptName(propuri); pcn.setType(getModelProcessor().nodeTypeToConceptType(getModelProcessor().ontConceptTypeToNodeType(declarationExtensions.getOntConceptType(((Name)predicate).getName())))); TypeCheckInfo lastTci = null; for (int i = 0; i < lrs.size(); i++) { TypeCheckInfo lrtci = new TypeCheckInfo(pcn, lrs.get(i), this, expression); lrtci.setTypeToExprRelationship(RESTRICTED_TO); if (lastTci != null) { predicateType = new TypeCheckInfo(pcn, this, expression); predicateType.addCompoundType(lastTci); } lastTci = lrtci; } if (predicateType != null) { predicateType.addCompoundType(lastTci); } else { predicateType = lastTci; } } if(predicateType != null) { if (predicateType.getTypeCheckType() != null){ addEffectiveRange(predicateType, subject); } return predicateType; } } } catch (PrefixNotFoundException e) { e.printStackTrace(); } catch (InvalidTypeException e) { e.printStackTrace(); } // check for AllValuesFrom restriction before defaulting to checking property range predicateType = getTypeFromRestriction(subject, predicate); if (predicateType != null) { if(predicateType.getTypeCheckType() != null){ addEffectiveRange(predicateType, subject); } return predicateType; } } else { // getModelProcessor().addIssueToAcceptor("Property of subject has unexpected subject type '" + subject.getClass().getCanonicalName() + "'", expression); // we don't care about any other types? validSubject = false; } if (predicate != null) { TypeCheckInfo predicateType = getType(predicate); if (subject instanceof PropOfSubject && predicateType.getExpressionType() instanceof ConceptName) { predicateType = checkEmbeddedPropOfSubject(subject, predicate, predicateType); return predicateType; }else if(validSubject && predicateType != null && predicateType.getTypeCheckType() != null){ //add interface range addEffectiveRange(predicateType, subject); } else if (subject instanceof SubjHasProp && SadlASTUtils.isUnitExpression(subject)) { issueAcceptor.addWarning("Units are associated with the subject of this expression; should the expression be in parentheses?", subject); } return predicateType; } return null; } protected String generateLocalRestrictionKey(Object transobj) { String key = transobj instanceof NamedNode ? ((NamedNode)transobj).toFullyQualifiedString() : transobj.toString(); return key; } private void addEffectiveRange(TypeCheckInfo predicateType, Expression subject) throws CircularDefinitionException, InvalidTypeException, CircularDependencyException{ if(metricsProcessor != null){ try { if (subject instanceof Name) { String className = declarationExtensions.getConceptUri(((Name) subject).getName()); SadlResource cls = ((Name) subject).getName(); if (!declarationExtensions.getOntConceptType(cls).equals(OntConceptType.CLASS)) { // need to convert this to the Class representing the type; use existing type checking functionality TypeCheckInfo subjTCI = getType(cls); if (subjTCI != null /* && !subjTCI.getTypeCheckType().toString().equals("TODO")*/) { addEffectiveRangeByTypeCheckInfo(predicateType, subjTCI); } } else { // cls = ((Name)subject).getName(); addEffectiveRangeUnit(className, predicateType); } } else if (subject instanceof Declaration) { SadlTypeReference str = ((Declaration)subject).getType(); if (str instanceof SadlSimpleTypeReference) { String className = declarationExtensions.getConceptUri(((SadlSimpleTypeReference)str).getType()); addEffectiveRangeUnit(className, predicateType); } } else if (subject instanceof ElementInList) { TypeCheckInfo tci = getType(((ElementInList)subject)); addEffectiveRangeByTypeCheckInfo(predicateType, tci); } else if (subject instanceof SubjHasProp) { TypeCheckInfo tci; tci = getType(((SubjHasProp)subject).getLeft()); addEffectiveRangeByTypeCheckInfo(predicateType, tci); } else { throw new InvalidNameException("addEffectiveRange given a subject of type '" + subject.getClass().getCanonicalName() + "', not yet handled."); } } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DontTypeCheckException e) { } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (PropertyWithoutRangeException e) { } } } private void addEffectiveRangeByTypeCheckInfo(TypeCheckInfo predicateType, TypeCheckInfo subjTCI) throws InvalidNameException, CircularDefinitionException { if (subjTCI.getCompoundTypes() != null) { Iterator<TypeCheckInfo> itr = subjTCI.getCompoundTypes().iterator(); while (itr.hasNext()) { TypeCheckInfo nexttci = itr.next(); addEffectiveRangeByTypeCheckInfo(predicateType, nexttci); } } else { Node ci = subjTCI.getTypeCheckType(); if (ci instanceof NamedNode) { // this should be the class name String className = ((NamedNode) ci).toFullyQualifiedString(); addEffectiveRangeUnit(className, predicateType); } else { throw new InvalidNameException("addEffectiveRangeByTypeCheckInfo called with TypeCheckInfo '" + subjTCI.toString() + ", which isn't handled."); } } } private void addEffectiveRangeUnit(String className, TypeCheckInfo predicateType) { String propertyName = predicateType.getExpressionType().toString(); String rangeStr = predicateType.getTypeCheckType().toString(); boolean isList = predicateType.getRangeValueType().equals(RangeValueType.LIST); metricsProcessor.addControlledOrMonitoredProperty(null, propertyName); metricsProcessor.addEffectiveRangeAndDomain(null, className, propertyName, rangeStr, isList); } private String getTypeCheckTypeString(TypeCheckInfo tci) { if (tci != null) { if (tci.typeCheckType != null) { return tci.typeCheckType.toString(); } if (tci.getCompoundTypes() != null) { StringBuilder sb = new StringBuilder(); Iterator<TypeCheckInfo> itr = tci.getCompoundTypes().iterator(); int cntr = 0; while (itr.hasNext()) { if (cntr > 0) sb.append(" or "); sb.append(getTypeCheckTypeString(itr.next())); cntr++; } return sb.toString(); } } return "(null)"; } protected List<Node> getApplicableLocalRestriction(Expression subject, Expression predicate) throws IOException, PrefixNotFoundException, InvalidNameException, InvalidTypeException, TranslationException, ConfigurationException, CircularDefinitionException { return null; } private boolean constantFollowedByElementThenList(String cnstval) { if (cnstval.equals("index") || cnstval.equals("count")) { return true; } return false; } private boolean constantFollowedByIntThenList(String cnstval) { if (cnstval.equals("element")) { return true; } return false; } private boolean constantRequiresListNext(String cnstval) { if (cnstval.equals("length") || cnstval.endsWith(" element") || cnstval.equals("first element") || cnstval.equals("last element")) { return true; } return false; } private TypeCheckInfo checkEmbeddedPropOfSubject(Expression subject, Expression predicate, TypeCheckInfo predicateType) throws InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException, CircularDefinitionException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { if (predicate instanceof Name) { String propuri = declarationExtensions.getConceptUri(((Name)predicate).getName()); OntConceptType oct = declarationExtensions.getOntConceptType(((Name)predicate).getName()); if (oct.equals(OntConceptType.ANNOTATION_PROPERTY)) { issueAcceptor.addWarning(SadlErrorMessages.DOMAIN_MATCHING.get("annotation property"), predicate); return predicateType; } Property prop = theJenaModel.getProperty(propuri); TypeCheckInfo subjType = getType(subject); List<OntClass> subjClasses = subjType != null ? getTypeCheckTypeClasses(subjType) : null; try { List<Node> lrs = getApplicableLocalRestriction(subject, predicate); if (lrs != null) { for (int i = 0; i < lrs.size(); i++) { if (lrs.size() > 1) { throw new TranslationException("More than one matching local restriction found; this shouldn't happen"); } if (!(lrs.get(0) instanceof NamedNode)) { throw new TranslationException("Local restriction isn't instance of NamedNode; this shouldn't happen"); } predicateType.setTypeCheckType((NamedNode)lrs.get(0)); predicateType.setTypeToExprRelationship(RESTRICTED_TO); if (predicateType.getTypeCheckType() != null){ addEffectiveRangeByTypeCheckInfo(predicateType, subjType); } return predicateType; } } } catch (PrefixNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } StmtIterator domainItr = prop.listProperties(RDFS.domain); boolean domainMatched = false; List<Resource> domainList = new ArrayList<Resource>(); while (domainItr.hasNext() && !domainMatched) { RDFNode dmn = domainItr.next().getObject(); if (dmn instanceof Resource) { if (checkDomain(subjClasses, dmn.asResource(), domainList)) { domainItr.close(); domainMatched = true; break; } } } boolean possibleMatch = false; if (!domainMatched) { // there was no direct match for (int i = 0; domainList != null && i < domainList.size() && !domainMatched; i++) { Resource dmn = domainList.get(i); if ((dmn instanceof OntResource || dmn.canAs(OntResource.class)) && subjType != null && subjType.getTypeCheckType() != null) { try { for (int j = 0; subjClasses != null && j < subjClasses.size(); j++) { OntClass subj = subjClasses.get(j); if (dmn.canAs(OntClass.class)) { /* * This handles the case of a property chain, e.g., p1 of p2, where p1 has domain D1 and p2 has range R2. * Normally this would pass type checking if R2 is a subclass of D1, proper or improper. In other words, * we want whatever can be returned as the value of p2 (R2) to be within the domain of p1. This is the first test. * Note that the domainList is D1, subjClasses is the range R2, and may be a union with elements ranged over by subj * * However, sometimes the range R2 isn't really a range but rather a local restriction, and in this case D1 may not be a subclass of R2, * but it will then be the case that */ if (SadlUtils.classIsSubclassOf(subj, dmn.as(OntClass.class), true, null)) { domainMatched = true; break; } else if (subjType.getTypeToExprRelationship() != null && subjType.getTypeToExprRelationship().equals(RESTRICTED_TO)) { // if (SadlUtils.classIsSubclassOf(subj, dmn.as(OntClass.class), true, null)) { if (SadlUtils.classIsSubclassOf(dmn.as(OntClass.class), subj, true, null)) { domainMatched = true; break; } } else if (SadlUtils.classIsSubclassOf(dmn.as(OntClass.class), subj, true, null)) { // this could match but isn't guaranteed to do so; generate a warning possibleMatch = true; } } } } catch (CircularDependencyException e) { e.printStackTrace(); } } } } if (!domainMatched && domainList != null) { // there wasn't any subclass match either so create an appropriate error message try { oct = declarationExtensions.getOntConceptType(((Name)predicate).getName()); StringBuilder errorMessageBuilder = new StringBuilder(); TypeCheckInfo leftTypeCheckInfo; if (domainList.size() == 1) { ConceptName cn1 = createTypedConceptName(propuri, oct); NamedNode cn2 = null; if (domainList.get(0).isURIResource()) { cn2 = getModelProcessor().validateNamedNode(new NamedNode(domainList.get(0).getURI(), NodeType.ClassNode)); leftTypeCheckInfo = new TypeCheckInfo(createTypedConceptName(propuri, oct), cn2, this, predicate); } else { leftTypeCheckInfo = createTypeCheckInfoForNonUriPropertyRange(domainList.get(0), cn1, predicate, cn1.getType()); } leftTypeCheckInfo.setTypeToExprRelationship("domain"); } else { leftTypeCheckInfo = new TypeCheckInfo(createTypedConceptName(propuri, oct), this, predicate); for (int i = 0; i < domainList.size(); i++) { Resource dmn = domainList.get(i); if (dmn.isURIResource()) { TypeCheckInfo tci = new TypeCheckInfo(createTypedConceptName(propuri, oct), getModelProcessor().validateNamedNode(new NamedNode(domainList.get(i).getURI(), NodeType.ClassNode)), this, predicate); leftTypeCheckInfo.addCompoundType(tci); leftTypeCheckInfo.setTypeToExprRelationship("domain"); } else { ConceptName cn = createTypedConceptName(propuri, oct); TypeCheckInfo tci = createTypeCheckInfoForNonUriPropertyRange(dmn, cn, predicate, cn.getType()); leftTypeCheckInfo.addCompoundType(tci); leftTypeCheckInfo.setTypeToExprRelationship("domain"); } } } if (possibleMatch) { StringBuilder warningMessageBuilder = new StringBuilder(); createErrorMessage(warningMessageBuilder, leftTypeCheckInfo, subjType, "chained property", false, predicate); int idx = warningMessageBuilder.indexOf("cannot operate"); warningMessageBuilder.replace(idx, idx + 14, "may, but is not guaranteed (because of broader range), to operate"); issueAcceptor.addWarning(warningMessageBuilder.toString(), predicate); } else { createErrorMessage(errorMessageBuilder, leftTypeCheckInfo, subjType, "chained property", true, predicate); } } catch (CircularDefinitionException e) { e.printStackTrace(); } } } return predicateType; } protected boolean checkDomain(List<OntClass> subjClasses, Resource dmn, List<Resource> domainList) { boolean domainMatched = false; if (dmn.isURIResource()) { for (int i = 0; subjClasses != null && i < subjClasses.size(); i++) { if (subjClasses.get(i).getURI().equals(((Resource) dmn).getURI())) { domainMatched = true; // this is a direct match break; } } if (!domainMatched) { domainList.add((Resource) dmn); } } else if (dmn.asResource().canAs(OntClass.class)) { if (dmn.asResource().as(OntClass.class).isUnionClass()) { ExtendedIterator<? extends OntClass> ucitr = dmn.asResource().as(OntClass.class).asUnionClass().listOperands(); while (ucitr.hasNext() && !domainMatched) { OntClass uccls = ucitr.next(); if (uccls.isURIResource()) { for (int i = 0; subjClasses != null && i < subjClasses.size(); i++) { if (subjClasses.get(i).getURI().equals(uccls.getURI())) { ucitr.close(); domainMatched = true; // this is a direct match break; } } if (!domainMatched) { domainList.add(uccls); } } else { if (checkDomain(subjClasses, uccls, domainList)) { ucitr.close(); domainMatched = true; } } } } } return domainMatched; } protected List<OntClass> getTypeCheckTypeClasses(TypeCheckInfo tci) { List<OntClass> results = null; if (tci.compoundTypes != null) { for (int i = 0; i < tci.compoundTypes.size(); i++) { TypeCheckInfo subtci = tci.compoundTypes.get(i); List<OntClass> subresults = getTypeCheckTypeClasses(subtci); if (results == null) { results = subresults; } else { results.addAll(subresults); } } } else { if (tci.getTypeCheckType() != null && tci.getTypeCheckType().toFullyQualifiedString() != null) { OntClass result = theJenaModel.getOntClass(tci.getTypeCheckType().toFullyQualifiedString()); if (result != null) { results = new ArrayList<OntClass>(); results.add(result); } } } return results; } protected TypeCheckInfo getTypeFromRestriction(Expression subject, Expression predicate) throws CircularDefinitionException, InvalidTypeException, DontTypeCheckException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, CircularDependencyException, PropertyWithoutRangeException { if (subject instanceof Name && predicate instanceof Name) { String subjuri = declarationExtensions.getConceptUri(((Name)subject).getName()); OntConceptType subjtype = declarationExtensions.getOntConceptType(((Name)subject).getName()); if (subjtype.equals(OntConceptType.VARIABLE)) { TypeCheckInfo varTci = getType(((Name)subject).getName()); if (varTci != null && varTci.getTypeCheckType() != null) { Node varci = varTci.getTypeCheckType(); if (varci instanceof NamedNode) { if (((NamedNode) varci).toString().equals("TODO")) { return null; } if (((NamedNode) varci).getName() == null || ((NamedNode) varci).getNamespace() == null) { return null; } subjuri = ((NamedNode)varci).toFullyQualifiedString(); } } } String propuri = declarationExtensions.getConceptUri(((Name)predicate).getName()); if (propuri == null) { getModelProcessor().addIssueToAcceptor("Predicate name could not be resolved", predicate); } else { OntConceptType proptype = declarationExtensions.getOntConceptType(((Name)predicate).getName()); return getTypeFromRestriction(subjuri, propuri, proptype, predicate); } } return null; } protected TypeCheckInfo getTypeFromRestriction(String subjuri, String propuri, OntConceptType proptype, Expression predicate) throws InvalidTypeException, TranslationException { Resource subj = theJenaModel.getResource(subjuri); if (subj != null) { if (!(subj instanceof OntClass || subj.canAs(OntClass.class)) && subj.canAs(Individual.class)) { ExtendedIterator<Resource> subjects = subj.as(Individual.class).listRDFTypes(true); while(subjects.hasNext()) { TypeCheckInfo type = getTypeFromRestriction(subjects.next(), propuri, proptype, predicate); if(type != null) { return type; } } }else { return getTypeFromRestriction(subj, propuri, proptype, predicate); } } return null; } protected TypeCheckInfo getTypeFromRestriction(Resource subj, String propuri, OntConceptType proptype, Expression predicate) throws InvalidTypeException, TranslationException { if (subj != null && subj.canAs(OntClass.class)){ Property prop = theJenaModel.getProperty(propuri); // look for restrictions on "range" StmtIterator sitr = theJenaModel.listStatements(null, OWL.onProperty, prop); while (sitr.hasNext()) { Statement stmt = sitr.nextStatement(); Resource sr = stmt.getSubject(); if (sr.canAs(OntClass.class) && subj.as(OntClass.class).hasSuperClass(sr.as(OntClass.class))) { if (sr.as(OntClass.class).asRestriction().isAllValuesFromRestriction()) { Resource avf = sr.as(OntClass.class).asRestriction().asAllValuesFromRestriction().getAllValuesFrom(); if (avf.isLiteral()) { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(avf.getURI(), NodeType.ClassNode)); TypeCheckInfo avftci = new TypeCheckInfo(createTypedConceptName(propuri, proptype), tctype, this, predicate); avftci.setTypeToExprRelationship(RESTRICTED_TO); return avftci; } else if (avf.isURIResource()){ List<ConceptName> impliedProperties = getImpliedProperties(avf); NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(avf.getURI(), NodeType.ClassNode)); TypeCheckInfo avftci = new TypeCheckInfo(createTypedConceptName(propuri, proptype), tctype, impliedProperties, this, predicate); avftci.setTypeToExprRelationship(RESTRICTED_TO); if (isTypedListSubclass(avf)) { avftci.setTypeCheckType(getTypedListType(avf)); avftci.setRangeValueType(RangeValueType.LIST); } return avftci; } } else if (sr.as(OntClass.class).asRestriction().isHasValueRestriction()) { RDFNode hvr = sr.as(OntClass.class).asRestriction().asHasValueRestriction().getHasValue(); TypeCheckInfo hvtci = new TypeCheckInfo(createTypedConceptName(propuri, proptype), hvr, ExplicitValueType.RESTRICTION, this, predicate); if (isTypedListSubclass(hvr)) { hvtci.setTypeCheckType(getTypedListType(hvr)); hvtci.setRangeValueType(RangeValueType.LIST); } return hvtci; } } } } return null; } private NamedNode getTypedListType(RDFNode node) throws TranslationException { return modelProcessor.getTypedListType(node); } private boolean isTypedListSubclass(RDFNode node) { return modelProcessor.isTypedListSubclass(node); } private TypeCheckInfo getType(Name expression) throws InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException, CircularDefinitionException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { SadlResource qnm =expression.getName(); if (qnm.eIsProxy()) { handleUndefinedFunctions(expression); } //If the expression is a function, find equation definition from name and get the return type if(expression.isFunction()){ try { TypeCheckInfo ftci = getFunctionType(qnm); if (qnm.eContainer() instanceof ExternalEquationStatement) { EList<Expression> args = expression.getArglist(); EList<SadlParameterDeclaration> params = ((ExternalEquationStatementImpl)qnm.eContainer()).getParameter(); checkFunctionArguments(params, args, expression); } else if (qnm.eContainer() instanceof EquationStatement) { EList<Expression> args = expression.getArglist(); EList<SadlParameterDeclaration> params = ((EquationStatement)qnm.eContainer()).getParameter(); checkFunctionArguments(params, args, expression); } if (ftci != null) { return ftci; } } catch (DontTypeCheckException e) { getModelProcessor().addWarning("External equation declaration does not provide type information; can't type check.", expression); throw e; } handleUndefinedFunctions(expression); } return getType(qnm, expression); } private void checkFunctionArguments(EList<SadlParameterDeclaration> params, EList<Expression> args, Name expression) throws InvalidTypeException, TranslationException { boolean variableNumArgs = false; int minNumArgs = 0; if (args.size() != params.size() || (params.size() > 1 && params.get(params.size() - 1).getEllipsis() != null)) { boolean wrongNumArgs = true; if (params.get(params.size() - 1).getEllipsis() != null) { minNumArgs = params.size() - 1; variableNumArgs = true; if (args.size() >= minNumArgs) { wrongNumArgs = false; } } if (wrongNumArgs) { getModelProcessor().addIssueToAcceptor("Number of arguments does not match function declaration", expression); } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < args.size(); i++) { Expression arg = args.get(i); SadlParameterDeclaration param = null; if (variableNumArgs) { param = (i >= minNumArgs) ? params.get(minNumArgs - 1) : params.get(i); } else if (i < params.size()) { param = params.get(i); } if (param != null) { validateBinaryOperationByParts(expression, arg, param.getType(), "argument", sb, false); if (sb.length() > 0) { getModelProcessor().addIssueToAcceptor(sb.toString(), expression); } } } } private TypeCheckInfo getFunctionType(SadlResource fsr) throws DontTypeCheckException, CircularDefinitionException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { if(fsr.eContainer() instanceof EquationStatement){ EquationStatement es = (EquationStatement) fsr.eContainer(); if(es != null){ return getType(es.getReturnType()); } }else if(fsr.eContainer() instanceof ExternalEquationStatement){ ExternalEquationStatement ees = (ExternalEquationStatement)fsr.eContainer(); if(ees != null) { if (ees.getUnknown() == null){ return getType(ees.getReturnType()); } else { throw new DontTypeCheckException(); } } } return null; } private boolean isInQuery(EObject expression) { EObject cntr = expression.eContainer(); if (cntr != null) { if (cntr instanceof QueryStatement) { return true; } return isInQuery(cntr); } return false; } protected void handleUndefinedFunctions(Name expression) throws ConfigurationException, DontTypeCheckException, InvalidTypeException{ String expressionName = declarationExtensions.getConcreteName(expression); ITranslator translator = getModelProcessor().getTranslator(); //If only names for built-in functions are available, check the name matches a built-in functions. If not, error. if (translator == null) { issueAcceptor.addWarning(SadlErrorMessages.TYPE_CHECK_TRANSLATOR_CLASS_NOT_FOUND.get(getModelProcessor().getConfigMgr().getTranslatorClassName()), expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.WARNING_MARKER_URI, MetricsProcessor.UNDEFINED_FUNCTION_URI); } } else if(translator.isBuiltinFunctionTypeCheckingAvailable() == SadlConstants.SADL_BUILTIN_FUNCTIONS_TYPE_CHECKING_AVAILABILITY.NAME_ONLY){ if(translator.isBuiltinFunction(expressionName)){ issueAcceptor.addWarning(SadlErrorMessages.TYPE_CHECK_BUILTIN_EXCEPTION.get(expressionName), expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.WARNING_MARKER_URI, MetricsProcessor.UNDEFINED_FUNCTION_URI); } }else{ getModelProcessor().addIssueToAcceptor(SadlErrorMessages.RETURN_TYPE_WARNING.get("Function " + expressionName), expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNDEFINED_FUNCTION_URI); } } } //Either the Reasoner/Translator provides full built-in information or provides nothing. //Regardless, if this point is reached, error. else { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.RETURN_TYPE_WARNING.get("Function " + expressionName), expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNDEFINED_FUNCTION_URI); } } // throw new DontTypeCheckException(); // we've added an error message (presumably) so why throw exception? } protected TypeCheckInfo getType(SadlResource sr) throws DontTypeCheckException, CircularDefinitionException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { return getType(sr, sr); } protected TypeCheckInfo getType(SadlResource sr, EObject reference) throws DontTypeCheckException, CircularDefinitionException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException{ String conceptUri = declarationExtensions.getConceptUri(sr); EObject expression = sr.eContainer(); if (conceptUri == null) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.UNIDENTIFIED.toString(), (reference != null ? reference : sr)); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } } OntConceptType conceptType; try { conceptType = declarationExtensions.getOntConceptType(sr); } catch (CircularDefinitionException e) { conceptType = e.getDefinitionType(); getModelProcessor().addIssueToAcceptor(e.getMessage(), reference); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } } if(conceptType.equals(OntConceptType.CLASS) || conceptType.equals(OntConceptType.DATATYPE)){ NamedNode tctype = createNamedNode(conceptUri, conceptType); ConceptName conceptName = getModelProcessor().namedNodeToConceptName(tctype); if (conceptName.getUri().equals(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI) && getModelProcessor().ignoreUnittedQuantities) { if (expression instanceof SadlClassOrPropertyDeclaration) { Iterator<SadlProperty> spitr = ((SadlClassOrPropertyDeclaration)expression).getDescribedBy().iterator(); while (spitr.hasNext()) { SadlProperty sp = spitr.next(); if (declarationExtensions.getConceptUri(sp.getProperty()).equals(SadlConstants.SADL_IMPLICIT_MODEL_VALUE_URI)) { return getType(sr, declarationExtensions.getDeclaration(sp.getProperty())); } } } else { getModelProcessor().addIssueToAcceptor("Can't handle this expression type when ignoring UnittedQuantities",expression); } } else { List<ConceptName> impliedProps = getImpliedProperties(theJenaModel.getResource(conceptUri)); TypeCheckInfo tci = new TypeCheckInfo(conceptName, tctype, this, impliedProps, reference); if (conceptType.equals(OntConceptType.CLASS)) { tci.setTypeToExprRelationship("self"); } return tci; } } else if(conceptType.equals(OntConceptType.DATATYPE_PROPERTY)){ TypeCheckInfo propcheckinfo = getNameProperty(sr, ConceptType.DATATYPEPROPERTY, conceptUri, reference); if (propcheckinfo != null) { return propcheckinfo; } throw new PropertyWithoutRangeException(declarationExtensions.getConcreteName(sr)); } else if(conceptType.equals(OntConceptType.CLASS_PROPERTY)){ TypeCheckInfo propcheckinfo = getNameProperty(sr, ConceptType.OBJECTPROPERTY, conceptUri, reference); if (propcheckinfo != null) { return propcheckinfo; } throw new PropertyWithoutRangeException(declarationExtensions.getConcreteName(sr)); } else if (conceptType.equals(OntConceptType.RDF_PROPERTY)) { TypeCheckInfo rdfpropcheckinfo = getNameProperty(sr, ConceptType.RDFPROPERTY, conceptUri, reference); if (rdfpropcheckinfo != null) { return rdfpropcheckinfo; } throw new PropertyWithoutRangeException(declarationExtensions.getConcreteName(sr)); } else if(conceptType.equals(OntConceptType.INSTANCE)){ // this is an instance--if it is already in the ontology we can get its type. If not maybe we can get it from its declaration Individual individual = theJenaModel.getIndividual(conceptUri); if(individual == null){ SadlResource qnmDecl = declarationExtensions.getDeclaration(sr); if (qnmDecl != null) { if (qnmDecl.eContainer() instanceof SadlInstance) { SadlTypeReference typeref = ((SadlInstance)qnmDecl.eContainer()).getType(); if (typeref != null) { return getType(typeref); } else { SadlResource nor = ((SadlInstance)qnmDecl.eContainer()).getNameOrRef(); if (!nor.equals(qnmDecl)) { return getType(nor); } } } else if (qnmDecl.eContainer() instanceof SadlMustBeOneOf) { if (qnmDecl.eContainer().eContainer() instanceof SadlClassOrPropertyDeclaration) { return getType(((SadlClassOrPropertyDeclaration)qnmDecl.eContainer().eContainer()).getClassOrProperty().get(0)); } } } getModelProcessor().addIssueToAcceptor(SadlErrorMessages.UNIDENTIFIED.toString(), reference); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } return null; } ConceptName instConceptName = new ConceptName(conceptUri); instConceptName.setType(ConceptType.INDIVIDUAL); // TODO could belong to multiple classes ExtendedIterator<Resource> typeitr = individual.listRDFTypes(true); TypeCheckInfo compoundTci = null; TypeCheckInfo tci = null; while (typeitr.hasNext()) { Resource ontResource = typeitr.next(); if(!ontResource.isURIResource()){ if (isSadlTypedList(ontResource) && ontResource.canAs(OntClass.class)) { tci = getSadlTypedListTypeCheckInfo(ontResource.as(OntClass.class), null, reference, null); } else { ConceptName declarationConceptName = new ConceptName("TODO"); declarationConceptName.setType(ConceptType.ONTCLASS); tci = new TypeCheckInfo(instConceptName, null, this, reference); } } else { String uriOfTypeToBeReturned = ontResource.getURI(); NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(uriOfTypeToBeReturned, NodeType.ClassNode)); ConceptName conceptName = getModelProcessor().namedNodeToConceptName(tctype); List<ConceptName> impliedProperties = getImpliedProperties(ontResource); tci = new TypeCheckInfo(instConceptName, tctype, this, impliedProperties, reference); } if (typeitr.hasNext() && compoundTci == null) { compoundTci = new TypeCheckInfo(instConceptName, this, reference); } if (compoundTci != null) { if (compoundTci.getCompoundTypes() == null || !compoundTci.getCompoundTypes().contains(tci)) { compoundTci.addCompoundType(tci); } } } if (compoundTci != null) { return compoundTci; } if (tci == null) { tci = new TypeCheckInfo(instConceptName); } return tci; } else if(conceptType.equals(OntConceptType.VARIABLE)){ String nm = declarationExtensions.getConcreteName(sr); String uri = declarationExtensions.getConceptUri(sr); if (uri == null) { getModelProcessor().addIssueToAcceptor("Unable to resolve name",reference); return null; } TypeCheckInfo tci = getVariableType(ConceptType.VARIABLE, sr, nm, uri, reference); if (tci != null) { // will be null on invalid input, e.g., during clean ConceptName et = new ConceptName(uri); et.setType(ConceptType.VARIABLE); tci.setExpressionType(et); } return tci; } else if(conceptType.equals(OntConceptType.ANNOTATION_PROPERTY)){ //This matches any type. ConceptName declarationConceptName = new ConceptName("TODO"); TypeCheckInfo tci = new TypeCheckInfo(declarationConceptName, null, this, reference); tci.setAdditionalInformation("" + conceptUri + "' is an annotation property and has no range"); tci.setSeverity(Severity.IGNORE); return tci; } else if (conceptType.equals(OntConceptType.FUNCTION_DEFN)) { return getFunctionType(sr); } else if (conceptType.equals(OntConceptType.CLASS_LIST)) { if (conceptUri != null) { OntClass ontcls = theJenaModel.getOntClass(conceptUri); ConceptName typecn = getListClassType(ontcls); conceptUri = typecn.toFQString(); } SadlResource declsr = declarationExtensions.getDeclaration(sr); NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(conceptUri, NodeType.ClassListNode)); ConceptName conceptName = getModelProcessor().namedNodeToConceptName(tctype); if (conceptName.getUri().equals(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI) && getModelProcessor().ignoreUnittedQuantities) { if (expression instanceof SadlClassOrPropertyDeclaration) { Iterator<SadlProperty> spitr = ((SadlClassOrPropertyDeclaration)expression).getDescribedBy().iterator(); while (spitr.hasNext()) { SadlProperty sp = spitr.next(); if (declarationExtensions.getConceptUri(sp.getProperty()).equals(SadlConstants.SADL_IMPLICIT_MODEL_VALUE_URI)) { return getType(sp.getProperty(), declarationExtensions.getDeclaration(sp.getProperty())); } } } else { getModelProcessor().addIssueToAcceptor("Can't handle this expression type when ignoring UnittedQuantities",expression); } } else { List<ConceptName> impliedProps = getImpliedProperties(theJenaModel.getResource(conceptUri)); TypeCheckInfo tci = new TypeCheckInfo(conceptName, tctype, this, impliedProps, reference); return tci; } } ConceptName declarationConceptName = new ConceptName("TODO"); return new TypeCheckInfo(declarationConceptName, null, this, reference); } private String getSadlModelUri(EObject eobj) { if (eobj.eContainer() instanceof SadlModel) { return ((SadlModel)eobj.eContainer()).getBaseUri(); } else if (eobj.eContainer() != null) { return getSadlModelUri(eobj.eContainer()); } return null; } private ConceptName createTypedConceptName(String conceptUri, OntConceptType conceptType) { return modelProcessor.createTypedConceptName(conceptUri, conceptType); } private NamedNode createNamedNode(String conceptUri, OntConceptType conceptType) { return modelProcessor.createNamedNode(conceptUri, conceptType); } protected TypeCheckInfo getNameProperty(SadlResource qnm, ConceptType propertyType, String conceptUri, EObject expression) throws DontTypeCheckException, InvalidTypeException, TranslationException, InvalidNameException { Property property = theJenaModel.getProperty(conceptUri); if(property == null){ getModelProcessor().addIssueToAcceptor(SadlErrorMessages.UNIDENTIFIED.toString(), qnm != null ? qnm : expression); if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.UNCLASSIFIED_FAILURE_URI); } return null; } ConceptName propConceptName = new ConceptName(conceptUri); propConceptName.setType(propertyType); return getTypeInfoFromRange(propConceptName, property, expression); } private TypeCheckInfo getPropertyDomainType(SadlResource propsr, EObject expr) throws InvalidTypeException { String propuri = declarationExtensions.getConceptUri(propsr); Property prop = theJenaModel.getProperty(propuri); ConceptName pcn = new ConceptName(propuri); getModelProcessor().setPropertyConceptNameType(pcn, prop); return getTypeInfoFromDomain(pcn, prop, expr); } private TypeCheckInfo getPropertyRangeType(SadlResource propsr, EObject expr) throws DontTypeCheckException, InvalidTypeException, TranslationException, InvalidNameException { String propuri = declarationExtensions.getConceptUri(propsr); Property prop = theJenaModel.getProperty(propuri); ConceptName pcn = new ConceptName(propuri); getModelProcessor().setPropertyConceptNameType(pcn, prop); return getTypeInfoFromRange(pcn, prop, expr); } public TypeCheckInfo getTypeInfoFromDomain(ConceptName propConceptName, Property property, EObject expression) throws InvalidTypeException { StmtIterator stmtitr = theJenaModel.listStatements(property, RDFS.domain, (RDFNode)null); while (stmtitr.hasNext()) { RDFNode obj = stmtitr.nextStatement().getObject(); if (obj.canAs(Resource.class)) { try { return createTypeCheckInfoForPropertyDomain(obj.asResource(), propConceptName, expression); } catch (DontTypeCheckException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return null; } public TypeCheckInfo getTypeInfoFromRange(ConceptName propConceptName, Property property, EObject expression) throws DontTypeCheckException, InvalidTypeException, TranslationException, InvalidNameException { ConceptType propertyType = propConceptName.getType(); StmtIterator sitr = theJenaModel.listStatements(property, RDFS.range, (RDFNode)null); if (sitr.hasNext()) { TypeCheckInfo compoundTci = null; TypeCheckInfo tci = null; while (sitr.hasNext()) { RDFNode first = sitr.next().getObject(); boolean isList = false; if(first.isURIResource()){ tci = createTypeCheckInfoForPropertyRange(first, propConceptName, expression, propertyType); } else if (isSadlTypedList(first)) { // get type restriction on "first" property--this is the type tci = getSadlTypedListTypeCheckInfo(first.as(OntClass.class), propConceptName, expression, propertyType); isList = true; } else { tci = createTypeCheckInfoForNonUriPropertyRange(first, propConceptName, expression, propertyType); } if (tci != null) { if (sitr.hasNext() && compoundTci == null) { compoundTci = new TypeCheckInfo(propConceptName, this, expression); if (isList) { compoundTci.setRangeValueType(RangeValueType.LIST); } } if (compoundTci != null) { if (tci.getCompoundTypes() != null) { for (TypeCheckInfo subtci:tci.getCompoundTypes()) { compoundTci.addCompoundType(subtci); } } else { compoundTci.addCompoundType(tci); } } } } sitr.close(); if (compoundTci != null) { return compoundTci; } return tci; } else { // no range on this property, check super properties StmtIterator sitr2 = theJenaModel.listStatements(property, RDFS.subPropertyOf, (RDFNode)null); while (sitr2.hasNext()) { RDFNode psuper = sitr2.next().getObject(); if (psuper.isResource()) { TypeCheckInfo superTCInfo = getNameProperty(null, propertyType, psuper.asResource().getURI(), expression); if (superTCInfo != null) { sitr2.close(); return superTCInfo; } } } } return null; } private TypeCheckInfo createTypeCheckInfoForNonUriPropertyRange(RDFNode rng, ConceptName propConceptName, EObject expression, ConceptType propertyType) throws InvalidTypeException, TranslationException, InvalidNameException { TypeCheckInfo tci = null; if (isSadlTypedList(rng)) { // get type restriction on "first" property--this is the type tci = getSadlTypedListTypeCheckInfo(rng.as(OntClass.class), propConceptName, expression, propertyType); } else if (rng.canAs(UnionClass.class)){ UnionClass ucls = rng.as(UnionClass.class); try { ExtendedIterator<? extends OntClass> eitr = ucls.listOperands(); if (eitr.hasNext()) { tci = new TypeCheckInfo(propConceptName, this, expression); while (eitr.hasNext()) { OntClass uclsmember = eitr.next(); if (uclsmember.isURIResource()) { TypeCheckInfo utci = createTypeCheckInfoForPropertyRange(uclsmember, propConceptName, expression, propertyType); tci.addCompoundType(utci); } else { TypeCheckInfo utci = createTypeCheckInfoForNonUriPropertyRange(uclsmember, propConceptName, expression, propertyType); tci.addCompoundType(utci); } } } } catch (Exception e) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.UNEXPECTED_TYPE_CHECK_ERROR.get("union range", e.getMessage() ), getDefaultContext()); } } else if (rng.canAs(IntersectionClass.class)){ issueAcceptor.addWarning(SadlErrorMessages.TYPE_CHECK_HANDLE_WARNING.get("intersections"), expression); } else if (rng.canAs(Restriction.class)){ issueAcceptor.addWarning(SadlErrorMessages.TYPE_CHECK_HANDLE_WARNING.get("restrictions"), expression); } return tci; } private TypeCheckInfo createTypeCheckInfoForNonUriPropertyDomain(Resource domain, ConceptName propConceptName, EObject expression) throws InvalidTypeException { TypeCheckInfo tci = null; if (domain.canAs(UnionClass.class)){ UnionClass ucls = domain.as(UnionClass.class); tci = createTypeCheckInfoForUnion(propConceptName, ucls, true, expression); } else if (domain.canAs(IntersectionClass.class)){ issueAcceptor.addWarning(SadlErrorMessages.TYPE_CHECK_HANDLE_WARNING.get("intersections"), expression); } else { issueAcceptor.addError("Unhandled type of non-URI domain", expression); } return tci; } private TypeCheckInfo createTypeCheckInfoForUnion(ConceptName propConceptName, UnionClass ucls, boolean isDomain, EObject expression) throws InvalidTypeException { TypeCheckInfo tci = null; try { ExtendedIterator<? extends OntClass> eitr = ucls.listOperands(); if (eitr.hasNext()) { tci = new TypeCheckInfo(propConceptName, this, expression); while (eitr.hasNext()) { try { OntClass uclsmember = eitr.next(); if (uclsmember.isURIResource()) { if (isDomain) { TypeCheckInfo utci = createTypeCheckInfoForPropertyDomain(uclsmember, propConceptName, expression); tci.addCompoundType(utci); } else { TypeCheckInfo utci = createTypeCheckInfoForPropertyRange(uclsmember, propConceptName, expression, propConceptName.getType()); tci.addCompoundType(utci); } } else { if (isDomain) { TypeCheckInfo utci = createTypeCheckInfoForNonUriPropertyDomain(uclsmember, propConceptName, expression); tci.addCompoundType(utci); } else { TypeCheckInfo utci = createTypeCheckInfoForNonUriPropertyRange(uclsmember, propConceptName, expression, propConceptName.getType()); tci.addCompoundType(utci); } } } catch (Exception e) { RDFNode uv = ucls.getPropertyValue(OWL.unionOf); if (ucls.canAs(RDFList.class)) { RDFList uclsr = ucls.as(RDFList.class); List<RDFNode> jlst = uclsr.asJavaList(); for (int i = 0; jlst != null && i < jlst.size(); i++) { System.out.println(jlst.get(i).toString()); } } } } } } catch (Exception e) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.UNEXPECTED_TYPE_CHECK_ERROR.get("union range", e.getMessage() ), getDefaultContext()); } return tci; } private TypeCheckInfo getSadlTypedListTypeCheckInfo(OntClass lst, ConceptName propConceptName, EObject expression, ConceptType propertyType) throws InvalidTypeException, TranslationException, InvalidNameException { Resource avf = getSadlTypedListType(lst); if (avf != null && avf.isURIResource()) { // List<ConceptName> impliedProperties = getImpliedProperties(avf.asResource()); List<ConceptName> impliedProperties = null; // don't impute implied properties when the range is a List NamedNode tctype = new NamedNode(avf.getURI()); tctype.setListLength(getSadlTypedListLengthRestriction(lst)); tctype.setMaxListLength(getSadlTypedListMaxLengthRestriction(lst)); tctype.setMinListLength(getSadlTypedListMinLengthRestriction(lst)); if (propertyType != null && propertyType.equals(ConceptType.DATATYPEPROPERTY)) { tctype.setNodeType(NodeType.DataTypeListNode); } else { tctype.setNodeType(NodeType.ClassListNode); } ConceptName rangeConceptName = getModelProcessor().namedNodeToConceptName(tctype); TypeCheckInfo tci = new TypeCheckInfo(propConceptName, tctype, impliedProperties, this, expression); tci.setRangeValueType(RangeValueType.LIST); return tci; } return null; } public boolean isSadlTypedList(RDFNode node) { if (node instanceof Resource && ((Resource)node).canAs(OntClass.class)) { OntClass cls = ((Resource)node).as(OntClass.class); OntResource lstrsrc = theJenaModel.getOntResource(SadlConstants.SADL_LIST_MODEL_LIST_URI); if (lstrsrc != null && cls.hasSuperClass(lstrsrc)) { // if the model doesn't have any lists the list model will not have been imported return true; } } return false; } public Resource getSadlTypedListType(OntClass lstcls) { ExtendedIterator<OntClass> eitr = ((OntClass)lstcls.as(OntClass.class)).listSuperClasses(true); while (eitr.hasNext()) { OntClass cls = eitr.next(); if (cls.isRestriction()) { if (cls.canAs(AllValuesFromRestriction.class)) { if (((AllValuesFromRestriction)cls.as(AllValuesFromRestriction.class)).onProperty(theJenaModel.getProperty(SadlConstants.SADL_LIST_MODEL_FIRST_URI))) { Resource avf = ((AllValuesFromRestriction)cls.as(AllValuesFromRestriction.class)).getAllValuesFrom(); eitr.close(); return avf; } } } } return null; } public int getSadlTypedListLengthRestriction(OntClass lstcls) { ExtendedIterator<OntClass> eitr = ((OntClass)lstcls.as(OntClass.class)).listSuperClasses(true); while (eitr.hasNext()) { OntClass cls = eitr.next(); if (cls.isRestriction()) { if (cls.canAs(HasValueRestriction.class)) { if (((HasValueRestriction)cls.as(HasValueRestriction.class)).onProperty(theJenaModel.getProperty(SadlConstants.SADL_LIST_MODEL_LENGTH_RESTRICTION_URI))) { int length = ((HasValueRestriction)cls.as(HasValueRestriction.class)).getHasValue().asLiteral().getInt(); eitr.close(); return length; } } } } return -1; } public int getSadlTypedListMaxLengthRestriction(OntClass lstcls) { ExtendedIterator<OntClass> eitr = ((OntClass)lstcls.as(OntClass.class)).listSuperClasses(true); while (eitr.hasNext()) { OntClass cls = eitr.next(); if (cls.isRestriction()) { if (cls.canAs(HasValueRestriction.class)) { if (((HasValueRestriction)cls.as(HasValueRestriction.class)).onProperty(theJenaModel.getProperty(SadlConstants.SADL_LIST_MODEL_MAXLENGTH_RESTRICTION_URI))) { int length = ((HasValueRestriction)cls.as(HasValueRestriction.class)).getHasValue().asLiteral().getInt(); eitr.close(); return length; } } } } return -1; } public int getSadlTypedListMinLengthRestriction(OntClass lstcls) { ExtendedIterator<OntClass> eitr = ((OntClass)lstcls.as(OntClass.class)).listSuperClasses(true); while (eitr.hasNext()) { OntClass cls = eitr.next(); if (cls.isRestriction()) { if (cls.canAs(HasValueRestriction.class)) { if (((HasValueRestriction)cls.as(HasValueRestriction.class)).onProperty(theJenaModel.getProperty(SadlConstants.SADL_LIST_MODEL_MINLENGTH_RESTRICTION_URI))) { int length = ((HasValueRestriction)cls.as(HasValueRestriction.class)).getHasValue().asLiteral().getInt(); eitr.close(); return length; } } } } return -1; } private TypeCheckInfo createTypeCheckInfoForPropertyDomain(Resource domain, ConceptName propConceptName, EObject expression) throws DontTypeCheckException, InvalidTypeException { TypeCheckInfo tci = null; if (!domain.isURIResource()) { return createTypeCheckInfoForNonUriPropertyDomain(domain, propConceptName, expression); } NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(domain.getURI(), NodeType.ClassNode)); if (tci == null) { tci = new TypeCheckInfo(propConceptName, tctype, this, expression); tci.setTypeToExprRelationship("domain"); } if (isTypedListSubclass(domain)) { tci.setRangeValueType(RangeValueType.LIST); } return tci; } private TypeCheckInfo createTypeCheckInfoForPropertyRange(RDFNode first, ConceptName propConceptName, EObject expression, ConceptType propertyType) throws InvalidTypeException, TranslationException, InvalidNameException { TypeCheckInfo tci = null; NamedNode rangeNamedNode = getModelProcessor().validateNamedNode(new NamedNode(first.asResource().getURI(), NodeType.DataTypeNode)); // ConceptName rangeConceptName = new ConceptName(first.asResource().getURI()); if (propertyType.equals(ConceptType.DATATYPEPROPERTY)) { // rangeConceptName.setType(ConceptType.RDFDATATYPE); OntResource range; range = theJenaModel.getOntResource(rangeNamedNode.toFullyQualifiedString()); if (theJenaModel.listStatements(range, RDF.type, RDFS.Datatype).hasNext()) { // this is a user-defined datatype RDFNode rngEC = range.listPropertyValues(OWL.equivalentClass).next(); if (rngEC != null && rngEC.canAs(OntResource.class)) { try { RDFNode baseType = rngEC.as(OntResource.class).listPropertyValues(OWL2.onDatatype).next(); if (baseType != null && baseType.isURIResource()) { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(baseType.asResource().getURI(), NodeType.DataTypeNode)); tci = new TypeCheckInfo(propConceptName, tctype, this, expression); } } catch (Exception e) { // didn't have a OWL2.onDataType property OntResource rngOC = rngEC.as(OntResource.class); if (rngOC.canAs(OntClass.class)) { OntClass rmgOntC = rngOC.as(OntClass.class); if (rmgOntC.isUnionClass()) { tci = createTypeCheckInfoForUnion(propConceptName, rmgOntC.asUnionClass(), false, expression); } } } } } else { // rangeConceptName.setRangeValueType(propConceptName.getRangeValueType()); if (propConceptName.getRangeValueType().equals(RangeValueType.LIST)) { rangeNamedNode.setNodeType(NodeType.DataTypeListNode); } } } else { rangeNamedNode.setNodeType(NodeType.ClassNode); } List<ConceptName> impliedProperties = getImpliedProperties(first.asResource()); if (tci == null) { tci = new TypeCheckInfo(propConceptName, rangeNamedNode, impliedProperties, this, expression); } else if (impliedProperties != null){ tci.addImplicitProperties(impliedProperties); } if (isTypedListSubclass(first)) { tci.setRangeValueType(RangeValueType.LIST); if (first.isURIResource()) { // looks like a named list in which case we probably have the wrong type if (!first.asResource().canAs(OntClass.class)){ issueAcceptor.addError("Unexpected non-OntClass named list, please report." , expression); } return getSadlTypedListTypeCheckInfo(first.asResource().as(OntClass.class), propConceptName, expression, propertyType); } } return tci; } protected List<ConceptName> getImpliedProperties(Resource first) throws InvalidTypeException { return getModelProcessor().getImpliedProperties(first); } // private boolean isRangeKlugyDATASubclass(OntResource rsrc) { // if (rsrc.getURI().endsWith("#DATA")) { // return true; // if (rsrc.canAs(OntClass.class)){ // ExtendedIterator<OntClass> itr = rsrc.as(OntClass.class).listSuperClasses(); // while (itr.hasNext()) { // OntClass spr = itr.next(); // if (spr.isURIResource() && spr.getURI().endsWith("#DATA")) { // return true; // return false; protected TypeCheckInfo getVariableType(ConceptType variable, SadlResource sr, String conceptNm, String conceptUri, EObject reference) throws DontTypeCheckException, CircularDefinitionException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { if (sr == null) { return null; // this might happen when cleaning with editor open } // 1) get the Name of the SadlResource for the variable // 2) get the definition of the Name // 3) if the container of the reference is a SubjHasProp: // 3a) look at the SubjHasProp left and right // 3aa) if the Name matches left, get the type as the domain of the SubjHasProp prop // 3ab) if the Name matches right, get the type as the range of the SubjHasProp prop VariableNode var = getModelProcessor().getVariable(conceptNm); if (var != null && var.getType() != null) { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(var.getType().toFullyQualifiedString(), NodeType.VariableNode)); ConceptName et = getModelProcessor().namedNodeToConceptName(tctype); TypeCheckInfo tci = new TypeCheckInfo(et, var.getType(), this, reference); return tci; } SadlResource name = sr.getName(); if (name != null) { SadlResource def = declarationExtensions.getDeclaration(name); EObject defContainer = def.eContainer(); if (defContainer instanceof SubjHasProp) { SadlResource propsr = ((SubjHasProp)defContainer).getProp(); if (((SubjHasProp)defContainer).getLeft().equals(name)) { return getPropertyDomainType(propsr, reference); } else if (((SubjHasProp)defContainer).getRight().equals(name)) { return getPropertyRangeType(propsr, reference); } } else if (defContainer instanceof SadlParameterDeclaration) { SadlTypeReference exprType = ((SadlParameterDeclaration)defContainer).getType(); return getType(exprType); } else if (defContainer instanceof BinaryOperation) { if (((BinaryOperation)defContainer).getLeft() instanceof Name) { // && !((BinaryOperation)defContainer).getLeft().equals(reference)) { if (getModelProcessor().isDeclaration(((BinaryOperation)defContainer).getRight())) { Declaration decl = getEmbeddedDeclaration(defContainer); // are we in a Declaration (a real declaration--the type is a class) if (decl != null) { return getType(decl); } } else { TypeCheckInfo ptci = getType(((BinaryOperation)defContainer).getRight()); return ptci; } } else if (((BinaryOperation)defContainer).getLeft() instanceof PropOfSubject && ((BinaryOperation)defContainer).getRight() instanceof Name) { TypeCheckInfo tci = getType(((BinaryOperation)defContainer).getLeft()); return tci; } else { issueAcceptor.addError("Unhandled variable container for variable '" + conceptNm + "'.", defContainer); } } else if (defContainer instanceof SadlParameterDeclaration) { SadlTypeReference exprType = ((SadlParameterDeclaration)defContainer).getType(); return getType(exprType); } else if (defContainer instanceof BinaryOperation) { if (((BinaryOperation)defContainer).getLeft() instanceof Name) { // && !((BinaryOperation)defContainer).getLeft().equals(expression)) { // this causes failure in some cases awc 9/27/17 if (getModelProcessor().isDeclaration(((BinaryOperation)defContainer).getRight())) { Declaration decl = getEmbeddedDeclaration(defContainer); // are we in a Declaration (a real declaration--the type is a class) if (decl != null) { return getType(decl); } } else { TypeCheckInfo ptci = getType(((BinaryOperation)defContainer).getRight()); return ptci; } } } } if (conceptUri == null) { return null; } EObject refContainer = reference.eContainer(); if (refContainer instanceof SadlParameterDeclaration) { SadlTypeReference exprType = ((SadlParameterDeclaration)refContainer).getType(); return getType(exprType); } else if (refContainer instanceof SubjHasProp) { SadlResource psr = ((SubjHasProp)refContainer).getProp(); if (psr.equals(sr)) { ConceptName tci = new ConceptName("TODO"); return new TypeCheckInfo(tci, null, this, refContainer); } TypeCheckInfo ptci = getType(psr); return ptci; } else if (refContainer instanceof PropOfSubject) { Expression pred = ((PropOfSubject)refContainer).getLeft(); if (pred instanceof SadlResource && ((PropOfSubject)refContainer).getRight().equals(name)) { return getPropertyDomainType((SadlResource) pred, reference); } } else if (refContainer instanceof BinaryOperation) { if (((BinaryOperation)refContainer).getLeft() instanceof Name && !((BinaryOperation)refContainer).getLeft().equals(reference)) { if (getModelProcessor().isDeclaration(((BinaryOperation)refContainer).getRight())) { Declaration decl = getEmbeddedDeclaration(refContainer); // are we in a Declaration (a real declaration--the type is a class) if (decl != null) { return getType(decl); } } else { if (((BinaryOperation)refContainer).getRight().equals(reference)) { // this will be an infinite recursion otherwise return null; } TypeCheckInfo ptci = getType(((BinaryOperation)refContainer).getRight()); return ptci; } } } else if (refContainer instanceof SelectExpression) { // find name in expression and get type from there TypeCheckInfo tci = getTypeFromWhereExpression(sr, conceptUri, ((SelectExpression)refContainer).getWhereExpression()); if (tci == null) { throw new DontTypeCheckException(); } } NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(conceptUri, NodeType.VariableNode)); ConceptName declarationConceptName = getModelProcessor().namedNodeToConceptName(tctype); return new TypeCheckInfo(declarationConceptName, tctype, this, reference); } private TypeCheckInfo getTypeFromWhereExpression(SadlResource sr, String uri, Expression expr) throws InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, DontTypeCheckException, CircularDefinitionException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { if (expr instanceof SubjHasProp) { Expression sexpr = findDefiningExpression(uri, ((SubjHasProp)expr).getLeft()); if (sexpr != null && !sexpr.equals(sr) && !(sexpr instanceof Name && ((Name)sexpr).getName().equals(sr))) { return getType(sexpr); } sexpr = findDefiningExpression(uri, ((SubjHasProp)expr).getProp()); if (sexpr != null && !sexpr.equals(sr) && !(sexpr instanceof Name && ((Name)sexpr).getName().equals(sr))) { return getType(sexpr); } sexpr = findDefiningExpression(uri, ((SubjHasProp)expr).getRight()); if (sexpr != null && !sexpr.equals(sr) && !(sexpr instanceof Name && ((Name)sexpr).getName().equals(sr))) { return getType(sexpr); } } else if (expr instanceof Name) { String nuri = declarationExtensions.getConceptUri(((Name)expr).getName()); if (nuri != null && nuri.equals(uri)) { if (expr != null && !expr.equals(sr) && !(expr instanceof Name && ((Name)expr).getName().equals(sr))) { return getType(expr); } } } else if (expr instanceof SadlResource) { String nuri = declarationExtensions.getConceptUri((SadlResource)expr); if (expr != null && !expr.equals(sr) && !(expr instanceof Name && ((Name)expr).getName().equals(sr))) { return getType(expr); } } return null; } private Expression findDefiningExpression(String uri, Expression expr) { if (expr instanceof SubjHasProp) { Expression sexpr = findDefiningExpression(uri, ((SubjHasProp)expr).getLeft()); if (sexpr != null) { return sexpr; } sexpr = findDefiningExpression(uri, ((SubjHasProp)expr).getProp()); if (sexpr != null) { return sexpr; } sexpr = findDefiningExpression(uri, ((SubjHasProp)expr).getRight()); if (sexpr != null) { return ((SubjHasProp)expr).getProp(); } } else if (expr instanceof Name) { String nuri = declarationExtensions.getConceptUri(((Name)expr).getName()); if (nuri != null && nuri.equals(uri)) { return expr; } } else if (expr instanceof SadlResource) { String nuri = declarationExtensions.getConceptUri((SadlResource)expr); if (nuri != null && nuri.equals(uri)) { return expr; } } return null; } private TypeCheckInfo combineBinaryOperationTypesWithComparison(List<String> operations, EObject binExpr, EObject leftExpression, EObject rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo, ImplicitPropertySide side) throws InvalidNameException, DontTypeCheckException, InvalidTypeException, TranslationException { if(!compareTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo, side)){ return null; } return combineBinaryOperationTypes(operations, binExpr, leftTypeCheckInfo, rightTypeCheckInfo); } private TypeCheckInfo combineBinaryOperationTypes(List<String> operations, EObject binExpr, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) throws InvalidTypeException, TranslationException, InvalidNameException { if (getModelProcessor().isBooleanComparison(operations)) { NamedNode tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.xboolean.getURI(), NodeType.DataTypeProperty)); ConceptName booleanLiteralConceptName = getModelProcessor().namedNodeToConceptName(tctype); return new TypeCheckInfo(booleanLiteralConceptName, tctype, this, binExpr); } else if (getModelProcessor().isNumericOperator(operations)) { if (leftTypeCheckInfo != null && isNumeric(leftTypeCheckInfo) && rightTypeCheckInfo != null && isNumeric(rightTypeCheckInfo)) { NamedNode lcn = getTypeCheckInfoType(leftTypeCheckInfo); NamedNode rcn = getTypeCheckInfoType(rightTypeCheckInfo); if (lcn == null || lcn.getNamespace() == null) { return leftTypeCheckInfo; } if (rcn == null || rcn.getNamespace() == null) { return rightTypeCheckInfo; } if (rcn.equals(lcn)) { return leftTypeCheckInfo; } else { ConceptName cn = numericalPrecedenceType(getModelProcessor().namedNodeToConceptName(lcn), getModelProcessor().namedNodeToConceptName(rcn)); return new TypeCheckInfo(cn, getModelProcessor().conceptNameToNamedNode(cn), this, binExpr); } } else { NamedNode tctype; if (leftTypeCheckInfo != null && isNumeric(leftTypeCheckInfo)) { tctype = getTypeCheckInfoType(leftTypeCheckInfo); } else if (rightTypeCheckInfo != null && isNumeric(rightTypeCheckInfo)) { tctype = getTypeCheckInfoType(rightTypeCheckInfo); } else { tctype = getModelProcessor().validateNamedNode(new NamedNode(XSD.decimal.getURI(), NodeType.DataTypeNode)); } ConceptName decimalLiteralConceptName = getModelProcessor().namedNodeToConceptName(tctype); decimalLiteralConceptName.setType(ConceptType.RDFDATATYPE); return new TypeCheckInfo(decimalLiteralConceptName, tctype, this, binExpr); } } else{ return leftTypeCheckInfo; } } private ConceptName numericalPrecedenceType(ConceptName lcn, ConceptName rcn) throws InvalidNameException { if (lcn.getUri().equals(XSD.decimal.getURI())) { return lcn; } else if (rcn.getUri().equals(XSD.decimal.getURI())) { return rcn; } else if (lcn.getUri().equals(XSD.xdouble.getURI())) { return lcn; } else if (rcn.getUri().equals(XSD.xdouble.getURI())) { return rcn; } else if (lcn.getUri().equals(XSD.xfloat.getURI())) { return lcn; } else if (rcn.getUri().equals(XSD.xfloat.getURI())) { return rcn; } else if (lcn.getUri().equals(XSD.xlong.getURI())) { return lcn; } else if (rcn.getUri().equals(XSD.xlong.getURI())) { return rcn; } else if (lcn.getUri().equals(XSD.integer.getURI())) { return lcn; } else if (rcn.getUri().equals(XSD.integer.getURI())) { return rcn; } else if (lcn.getUri().equals(XSD.xint.getURI())) { return lcn; } else if (rcn.getUri().equals(XSD.xint.getURI())) { return rcn; } return rcn; } private NamedNode getTypeCheckInfoType(TypeCheckInfo tci) throws InvalidNameException, TranslationException, InvalidTypeException { if (tci.getExplicitValueType() != null && tci.getExplicitValueType().equals(ExplicitValueType.VALUE)) { if (tci.getExpressionType() instanceof ConceptName) { return getModelProcessor().conceptNameToNamedNode((ConceptName) tci.getExpressionType()); } } if (tci.getTypeCheckType() instanceof NamedNode) { return (NamedNode) tci.getTypeCheckType(); } if (tci.compoundTypes != null) { return null; } throw new InvalidNameException("Failed to get TypeCheckInfoType"); } /** * Compare two TypeCheckInfo structures * @param operations * @param leftExpression * @param rightExpression * @param leftTypeCheckInfo * @param rightTypeCheckInfo * @return return true if they pass type check comparison else false * @throws InvalidNameException * @throws DontTypeCheckException * @throws InvalidTypeException * @throws TranslationException */ protected boolean compareTypes(List<String> operations, EObject leftExpression, EObject rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo, ImplicitPropertySide side) throws InvalidNameException, DontTypeCheckException, InvalidTypeException, TranslationException { boolean listTemporarilyDisabled = false; try { boolean isNumericOperator = getModelProcessor().isNumericOperator(operations); boolean isNumericLeft = isNumeric(leftTypeCheckInfo) || isUnittedQuantity(leftTypeCheckInfo); boolean isNumericRight = isNumeric(rightTypeCheckInfo) || isUnittedQuantity(rightTypeCheckInfo); if (!isNumericOperator && (isNumericLeft || isNumericRight)) { isNumericOperator = getModelProcessor().canBeNumericOperator(operations); } // negated expressions have the type of the expression negated if (leftExpression instanceof UnaryExpression && ((UnaryExpression)leftExpression).getOp().equals("not")) { leftExpression = ((UnaryExpression)leftExpression).getExpr(); } if (rightExpression instanceof UnaryExpression && ((UnaryExpression)rightExpression).getOp().equals("not")) { rightExpression = ((UnaryExpression)rightExpression).getExpr(); } if (rightExpression instanceof Constant && ((Constant)rightExpression).getConstant().equals("known")) { // everything matches "known" return true; } if (leftExpression instanceof Constant && ((Constant)leftExpression).getConstant().equals("known")) { // everything matches "known" return true; } if (rightExpression instanceof Constant && ((Constant)rightExpression).getConstant().equals("None")) { // everything matches "None" return true; } if (leftExpression instanceof Constant && ((Constant)leftExpression).getConstant().equals("None")) { // everything matches "None" return true; } if (!isNumericOperator) { if (directCompareTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo, side)) { return true; } } if (leftExpression instanceof Constant && (((Constant)leftExpression).getConstant().equals("value") || ((Constant)leftExpression).getConstant().equals("type"))) { listTemporarilyDisabled = true; leftTypeCheckInfo = convertListTypeToElementOfListType(leftTypeCheckInfo); } if (isNumericOperator) { if (!isNumericLeft) { if (!isNumericRight) { side = ImplicitPropertySide.BOTH; } else { side = ImplicitPropertySide.LEFT; } } else if (!isNumericRight) { side = ImplicitPropertySide.RIGHT; } } if (side.equals(ImplicitPropertySide.NONE)) { // Compare literal types if (compareTypesRecursively(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo)){ return true; } } else if (side.equals(ImplicitPropertySide.BOTH)) { String opstr = (operations != null && operations.size() > 0) ? operations.get(0) : null; if (useImpliedPropertyToMatchNumericOperator(leftExpression, leftTypeCheckInfo, "left side of '" + opstr + "'") && useImpliedPropertyToMatchNumericOperator(rightExpression, rightTypeCheckInfo, "right side of '" + opstr + "'")) { return true; } return false; // don't fall through to call below, it doesn't handle BOTH } //Compare implied property types if(compareTypesUsingImpliedPropertiesRecursively(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo, side)){ return true; } if (directCompareTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo, side)) { return true; } return false; } finally { if (listTemporarilyDisabled) { leftTypeCheckInfo = convertElementOfListToListType(leftTypeCheckInfo); } } } private boolean directCompareTypes(List<String> operations, EObject leftExpression, EObject rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo, ImplicitPropertySide side) throws InvalidNameException, InvalidTypeException, DontTypeCheckException, TranslationException { if (leftTypeCheckInfo != null && leftTypeCheckInfo.getTypeCheckType() != null && rightTypeCheckInfo != null && rightTypeCheckInfo.getTypeCheckType() != null) { if (leftTypeCheckInfo.getTypeCheckType().equals(rightTypeCheckInfo.getTypeCheckType())) { return true; } if (compatibleTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo)) { return true; } } return false; } public boolean compareTypesUsingImpliedPropertiesRecursively(List<String> operations, EObject leftExpression, EObject rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo, ImplicitPropertySide side) throws InvalidNameException, DontTypeCheckException, InvalidTypeException, TranslationException { List<TypeCheckInfo> ltciCompound = leftTypeCheckInfo != null ? leftTypeCheckInfo.getCompoundTypes() : null; if(ltciCompound != null){ for (int i = 0; i < ltciCompound.size(); i++) { boolean thisResult = compareTypesUsingImpliedProperties(operations, leftExpression, rightExpression, ltciCompound.get(i), rightTypeCheckInfo, side); if (thisResult) { return true; } } if (rightTypeCheckInfo.getCompoundTypes() == null) { return false; } } List<TypeCheckInfo> rtciCompound = rightTypeCheckInfo != null ? rightTypeCheckInfo.getCompoundTypes() : null; if(rtciCompound != null){ for (int j = 0; j < rtciCompound.size(); j++) { boolean thisResult = compareTypesUsingImpliedProperties(operations, leftExpression, rightExpression, leftTypeCheckInfo, rtciCompound.get(j), side); if (thisResult) { return true; } } if (leftTypeCheckInfo.getCompoundTypes() == null) { return false; } } if(compareTypesUsingImpliedProperties(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo, side)){ return true; } return false; } public boolean compareTypesRecursively(List<String> operations, EObject leftExpression, EObject rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) throws InvalidNameException, DontTypeCheckException, InvalidTypeException, TranslationException { List<TypeCheckInfo> ltciCompound = leftTypeCheckInfo != null ? leftTypeCheckInfo.getCompoundTypes() : null; if(ltciCompound != null){ for (int i = 0; i < ltciCompound.size(); i++) { boolean thisResult = compareTypesRecursively(operations, leftExpression, rightExpression, ltciCompound.get(i), rightTypeCheckInfo); if (thisResult) { return true; } } if (rightTypeCheckInfo.getCompoundTypes() == null) { return false; } } List<TypeCheckInfo> rtciCompound = rightTypeCheckInfo != null ? rightTypeCheckInfo.getCompoundTypes() : null; if(rtciCompound != null){ for (int j = 0; j < rtciCompound.size(); j++) { boolean thisResult = compareTypesRecursively(operations, leftExpression, rightExpression, leftTypeCheckInfo, rtciCompound.get(j)); if (thisResult) { return true; } } if (leftTypeCheckInfo.getCompoundTypes() == null) { return false; } } ConceptIdentifier leftConceptIdentifier = leftTypeCheckInfo != null ? getConceptIdentifierFromTypeCheckInfo(leftTypeCheckInfo): null; ConceptIdentifier rightConceptIdentifier = rightTypeCheckInfo != null ? getConceptIdentifierFromTypeCheckInfo(rightTypeCheckInfo) : null; if ((leftConceptIdentifier != null && leftConceptIdentifier.toString().equals(SadlConstants.CONSTANT_NONE)) || (rightConceptIdentifier != null && rightConceptIdentifier.toString().equals(SadlConstants.CONSTANT_NONE)) || (leftConceptIdentifier != null && leftConceptIdentifier.toString().equals("TODO")) || (rightConceptIdentifier != null && rightConceptIdentifier.toString().equals("TODO"))) { // Can't type-check on "None" as it represents that it doesn't exist. return true; } else if (leftConceptIdentifier == null) { if (leftTypeCheckInfo != null && leftTypeCheckInfo.getSeverity() != null) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_COMPARISON.toString(), leftTypeCheckInfo.getSeverity(), leftExpression); } else { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_COMPARISON.toString(), leftExpression); } if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } return false; } else if(rightConceptIdentifier == null){ if (rightTypeCheckInfo != null && rightTypeCheckInfo != null && rightTypeCheckInfo.getSeverity() != null) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_COMPARISON.toString(), rightTypeCheckInfo.getSeverity(), rightExpression); } else { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.TYPE_COMPARISON.toString(), rightExpression); } if (metricsProcessor != null) { metricsProcessor.addMarker(null, MetricsProcessor.ERROR_MARKER_URI, MetricsProcessor.TYPE_CHECK_FAILURE_URI); } return false; } else if (!compatibleTypes(operations, leftExpression, rightExpression, leftTypeCheckInfo, rightTypeCheckInfo)) { if (isConjunctiveLocalRestriction(leftExpression, rightExpression)) { return true; } return false; } return true; } private boolean isConjunctiveLocalRestriction(EObject leftExpression, EObject rightExpression) { if (rightExpression instanceof Declaration && rightExpression.eContainer() instanceof BinaryOperation && ((BinaryOperation)rightExpression.eContainer()).getOp().equals("is") && rightExpression.eContainer().eContainer() instanceof BinaryOperation && ((BinaryOperation)rightExpression.eContainer().eContainer()).getOp().equals("or") && contains(rightExpression.eContainer().eContainer(), leftExpression)) { return true; } return false; } /** * Returns true if eobj1 contains eobj2 else false * * @param eobj1 * @param eobj2 * @return */ protected boolean contains(EObject eobj1, EObject eobj2) { if (eobj2.eContainer() != null) { if (eobj2.eContainer().equals(eobj1)) { return true; } else { return contains(eobj1, eobj2.eContainer()); } } return false; } protected ConceptIdentifier getConceptIdentifierFromTypeCheckInfo(TypeCheckInfo tci) throws TranslationException, InvalidNameException, InvalidTypeException { if (tci.getRangeValueType().equals(RangeValueType.LIST)) { ConceptName cn = getListType(tci); if (cn != null) { return cn; } } if (tci.getExplicitValue() != null) { RDFNode val = tci.getExplicitValue(); if (val.isURIResource()) { ConceptName cn = new ConceptName(val.asResource().getURI()); cn.setType(ConceptType.INDIVIDUAL); return cn; } else if (val.isLiteral()) { ConceptName literalConceptName = new ConceptName(val.asLiteral().getDatatype().getURI()); literalConceptName.setType(ConceptType.RDFDATATYPE); return literalConceptName; } } Node tcttype = tci.getTypeCheckType(); if (tcttype == null) { return null; } if (tcttype instanceof ProxyNode) { if (((ProxyNode)tcttype).getProxyFor() instanceof ConceptIdentifier) { return (ConceptIdentifier) ((ProxyNode)tcttype).getProxyFor(); } else if (((ProxyNode)tcttype).getProxyFor() instanceof Junction) { // convert Junction (or) to SadlUnionClass return junctionToSadlUntionClass((Junction)((ProxyNode)tcttype).getProxyFor()); } } return getModelProcessor().namedNodeToConceptName((NamedNode) tci.getTypeCheckType()); } private ConceptIdentifier junctionToSadlUntionClass(Junction proxyFor) throws TranslationException, InvalidNameException, InvalidTypeException { List<ConceptIdentifier> cnlist = new ArrayList<ConceptIdentifier>(); cnlist = junctionToList(proxyFor, cnlist); SadlUnionClass union = new SadlUnionClass(cnlist); return union; } private List<ConceptIdentifier> junctionToList(Junction jct, List<ConceptIdentifier> cnlist) throws TranslationException, InvalidNameException, InvalidTypeException { Object lhs = jct.getLhs(); Object rhs = jct.getRhs(); if (lhs instanceof NamedNode) { cnlist.add(getModelProcessor().namedNodeToConceptName((NamedNode) lhs)); } else if (lhs instanceof Junction) { cnlist = junctionToList((Junction)lhs, cnlist); } else { throw new TranslationException("unhandled type (" + lhs.getClass().getCanonicalName() + ") in junctionToList"); } if (rhs instanceof NamedNode) { cnlist.add(getModelProcessor().namedNodeToConceptName((NamedNode) rhs)); } else if (rhs instanceof Junction) { cnlist = junctionToList((Junction)rhs, cnlist); } else { throw new TranslationException("unhandled type (" + rhs.getClass().getCanonicalName() + ") in junctionToList"); } return cnlist; } private boolean compareTypesUsingImpliedProperties(List<String> operations, EObject leftExpression, EObject rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo, ImplicitPropertySide side) throws InvalidNameException, DontTypeCheckException, InvalidTypeException, TranslationException { if (side.equals(ImplicitPropertySide.BOTH)) { throw new TranslationException("This method does not handle looking for implied properties on BOTH sides"); } // There must be a mismatch or we wouldn't have gotten to here, so we know that to pass (return true) we // need to find an implied property that fixes the mismatch on one side or the other. // If the side is explicitly specified, then we won't check the other side. Otherwise we will // check both sides and if we find a match we should return true. boolean leftSideOK = !side.equals(ImplicitPropertySide.RIGHT) ? false : true; boolean rightSideOK = !side.equals(ImplicitPropertySide.LEFT) ? false : true; String opstr = (operations != null && operations.size() > 0) ? operations.get(0) : null; if (leftTypeCheckInfo != null && !side.equals(ImplicitPropertySide.RIGHT) && leftTypeCheckInfo.getImplicitProperties() != null) { Iterator<ConceptName> litr = leftTypeCheckInfo.getImplicitProperties().iterator(); while (litr.hasNext()) { ConceptName cn = litr.next(); Property prop = theJenaModel.getProperty(cn.getUri()); if (prop.canAs(ObjectProperty.class)) { cn.setType(ConceptType.OBJECTPROPERTY); } else if (prop.canAs(DatatypeProperty.class)) { cn.setType(ConceptType.DATATYPEPROPERTY); } else { cn.setType(ConceptType.RDFPROPERTY); } TypeCheckInfo newltci = getTypeInfoFromRange(cn, prop, leftExpression); if (compareTypesRecursively(operations, leftExpression, rightExpression, newltci, rightTypeCheckInfo)) { issueAcceptor.addInfo("Implied property '" + getModelProcessor().conceptIdentifierToString(cn) + "' used (left side" + (opstr != null ? (" of '" + opstr + "'") : "") + ") to pass type check", leftExpression); addImpliedPropertiesUsed(leftExpression, prop); leftSideOK = true; if (!side.equals(ImplicitPropertySide.BOTH)) { rightSideOK = true; } break; } } } if (rightTypeCheckInfo != null && !side.equals(ImplicitPropertySide.LEFT) && rightTypeCheckInfo.getImplicitProperties() != null) { Iterator<ConceptName> ritr = rightTypeCheckInfo.getImplicitProperties().iterator(); while (ritr.hasNext()) { ConceptName cn = ritr.next(); Property prop = theJenaModel.getProperty(cn.getUri()); if (prop.canAs(ObjectProperty.class)) { cn.setType(ConceptType.OBJECTPROPERTY); } else if (prop.canAs(DatatypeProperty.class)) { cn.setType(ConceptType.DATATYPEPROPERTY); } else { cn.setType(ConceptType.RDFPROPERTY); } TypeCheckInfo newrtci = getTypeInfoFromRange(cn, prop, rightExpression); if (compareTypesRecursively(operations, leftExpression, rightExpression, leftTypeCheckInfo, newrtci)) { issueAcceptor.addInfo("Implied property '" + getModelProcessor().conceptIdentifierToString(cn) + "' used (right side" + (opstr != null ? (" of '" + opstr + "'") : "") + ") to pass type check", rightExpression); addImpliedPropertiesUsed(rightExpression, prop); rightSideOK = true; if (!side.equals(ImplicitPropertySide.BOTH)) { leftSideOK = true; } break; } } } return leftSideOK && rightSideOK; } private boolean useImpliedPropertyToMatchNumericOperator(EObject expr, TypeCheckInfo tci, String sideId) throws DontTypeCheckException, InvalidTypeException, TranslationException, InvalidNameException { if (tci != null && tci.getImplicitProperties() != null) { Iterator<ConceptName> ipitr = tci.getImplicitProperties().iterator(); while (ipitr.hasNext()) { ConceptName cn = ipitr.next(); Property prop = theJenaModel.getProperty(cn.getUri()); if (prop.canAs(ObjectProperty.class)) { cn.setType(ConceptType.OBJECTPROPERTY); } else if (prop.canAs(DatatypeProperty.class)) { cn.setType(ConceptType.DATATYPEPROPERTY); } else { cn.setType(ConceptType.RDFPROPERTY); } TypeCheckInfo newltci = getTypeInfoFromRange(cn, prop, expr); if (isNumeric(newltci)) { issueAcceptor.addInfo("Implied property '" + getModelProcessor().conceptIdentifierToString(cn) + "' used (" + sideId + ") to pass type check", expr); addImpliedPropertiesUsed(expr, prop); return true; } } } return false; } private boolean compatibleTypes(List<String> operations, EObject leftExpression, EObject rightExpression, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) throws InvalidNameException, InvalidTypeException, DontTypeCheckException, TranslationException{ if ((leftTypeCheckInfo.getRangeValueType() == null && rightTypeCheckInfo.getRangeValueType() != null && !rightTypeCheckInfo.getRangeValueType().equals(RangeValueType.CLASS_OR_DT)) || (leftTypeCheckInfo.getRangeValueType() != null && !leftTypeCheckInfo.getRangeValueType().equals(RangeValueType.CLASS_OR_DT) && rightTypeCheckInfo.getRangeValueType() == null) || (leftTypeCheckInfo.getRangeValueType() != null && rightTypeCheckInfo.getRangeValueType() != null && !(leftTypeCheckInfo.getRangeValueType().equals(rightTypeCheckInfo.getRangeValueType())))) { if (!isQualifyingListOperation(operations, leftTypeCheckInfo, rightTypeCheckInfo)) { if (isCompatibleListTypes(operations, leftTypeCheckInfo, rightTypeCheckInfo)) { return true; } return false; } } if(leftTypeCheckInfo.getRangeValueType() != null && leftTypeCheckInfo.getRangeValueType().equals(RangeValueType.LIST) && rightTypeCheckInfo.getRangeValueType() != null && rightTypeCheckInfo.getRangeValueType().equals(RangeValueType.LIST)) { if(leftTypeCheckInfo.getTypeCheckType() != null && rightTypeCheckInfo.getTypeCheckType() != null && leftTypeCheckInfo.getTypeCheckType().toFullyQualifiedString().equals(rightTypeCheckInfo.getTypeCheckType().toFullyQualifiedString())){ ConceptName leftConceptName = (ConceptName)getConceptIdentifierFromTypeCheckInfo(leftTypeCheckInfo); ConceptName rightConceptName = (ConceptName)getConceptIdentifierFromTypeCheckInfo(rightTypeCheckInfo); if(leftConceptName.getType().equals(rightConceptName.getType())){ return leftTypeCheckInfo.getTypeCheckType().equals(rightTypeCheckInfo.getTypeCheckType()); } } } if (getModelProcessor().isDeclaration(leftExpression) && getModelProcessor().isDeclaration(rightExpression) && leftTypeCheckInfo.getTypeToExprRelationship().equals("self") && rightTypeCheckInfo.getTypeToExprRelationship().equals("self")) { // this is a test for class membership to be resolved by the reasoner return true; } ConceptIdentifier leftConceptIdentifier = getConceptIdentifierFromTypeCheckInfo(leftTypeCheckInfo); ConceptIdentifier rightConceptIdentifier = getConceptIdentifierFromTypeCheckInfo(rightTypeCheckInfo); if (leftConceptIdentifier == null || rightConceptIdentifier == null) { return false; } List<ConceptIdentifier> leftCIs = null; if (leftConceptIdentifier instanceof SadlUnionClass) { leftCIs = ((SadlUnionClass)leftConceptIdentifier).getClasses(); } else { leftCIs = new ArrayList<ConceptIdentifier>(1); leftCIs.add(leftConceptIdentifier); } List<ConceptIdentifier> rightCIs = null; if (rightConceptIdentifier instanceof SadlUnionClass) { rightCIs = ((SadlUnionClass)rightConceptIdentifier).getClasses(); } else { rightCIs = new ArrayList<ConceptIdentifier>(1); rightCIs.add(rightConceptIdentifier); } for (int leftIdx = 0; leftIdx < leftCIs.size(); leftIdx++) { for (int rightIdx = 0; rightIdx < rightCIs.size(); rightIdx++) { leftConceptIdentifier = leftCIs.get(leftIdx); rightConceptIdentifier = rightCIs.get(rightIdx); if (leftConceptIdentifier instanceof ConceptName && rightConceptIdentifier instanceof ConceptName) { ConceptName leftConceptName = (ConceptName) leftConceptIdentifier; ConceptName rightConceptName = (ConceptName) rightConceptIdentifier; if (getModelProcessor().isNumericOperator(operations) && ((!isNumeric(leftTypeCheckInfo) && !isNumericWithImpliedProperty(leftTypeCheckInfo,(Expression)leftExpression))|| (!isNumeric(rightTypeCheckInfo) && !isNumericWithImpliedProperty(rightTypeCheckInfo,(Expression)rightExpression)))) { if (!leftConceptName.getUri().equals(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI) || !rightConceptName.getUri().equals(SadlConstants.SADL_IMPLICIT_MODEL_UNITTEDQUANTITY_URI)) { return false; } } if (leftConceptName.equals(rightConceptName) && !getModelProcessor().isNumericOperator(operations)) { return true; } else if ((getModelProcessor().isNumericOperator(operations) || getModelProcessor().canBeNumericOperator(operations)) && (getModelProcessor().isNumericType(leftConceptName) && getModelProcessor().isNumericType(rightConceptName))) { return true; } else if (leftConceptName.getType() == null || rightConceptName.getType() == null) { if (rightConceptName.getType() == null && leftConceptName.getType() == null) { return true; } // else { // return false; } else if (leftConceptName.getType().equals(ConceptType.RDFDATATYPE) && rightConceptName.getType().equals(ConceptType.RDFDATATYPE)) { if(leftConceptName.getUri().equals(rightConceptName.getUri())){ return true; } else if (isInteger(leftConceptName) && isInteger(rightConceptName)) { return true; } else if(isDecimal(leftConceptName) && isInteger(rightConceptName)){ return true; } else if(isInteger(leftConceptName) && isDecimal(rightConceptName)){ // TODO does this need to be restricted to certain operators? This should work for numerical comparison... return true; } else if(isDecimal(leftConceptName) && isDecimal(rightConceptName)){ return true; } else if (rightConceptName.getUri().equals(XSD.xstring.getURI()) && (leftConceptName.getUri().equals(XSD.dateTime.getURI()) || leftConceptName.getUri().equals(XSD.date.getURI()))) { return true; } else { // maybe one or both is a user-defined datatype } } else if (leftConceptName.getType().equals(ConceptType.DATATYPEPROPERTY) && rightConceptName.getType().equals(ConceptType.DATATYPEPROPERTY)) { if(leftConceptName.getUri().equals(rightConceptName.getUri())){ return true; } } else if(leftConceptName.getType().equals(ConceptType.OBJECTPROPERTY) && rightConceptName.getType().equals(ConceptType.OBJECTPROPERTY)){ if(leftConceptName.getUri().equals(rightConceptName.getUri())){ return true; } } else if (leftConceptName.getType().equals(ConceptType.ONTCLASS) && rightConceptName.getType().equals(ConceptType.ONTCLASS)) { if (partOfTest(leftExpression, rightExpression)) { // if we're in a test we don't want to type check as it may fail when not using the inferred model. return true; } //How do we determine if either is a sub/super class of the other? if(leftConceptName.getUri().equals(rightConceptName.getUri())){ return true; } // these next two ifs are a little loose, but not clear how to determine which way the comparison should be? May need tightening... AWC 5/11/2016 try { // if (rightTypeCheckInfo.getExpressionType() instanceof ConceptName && ((ConceptName)rightTypeCheckInfo.getExpressionType()).getType().equals(ConceptType.INDIVIDUAL)) { // // here we can do a tighter check // if (!getModelProcessor().instanceBelongsToClass(theJenaModel, // theJenaModel.getOntResource(((ConceptName)rightTypeCheckInfo.getExpressionType()).getUri()), // theJenaModel.getOntResource(leftConceptName.getUri()))) { // return false; OntClass subcls = theJenaModel.getOntClass(leftConceptName.getUri()); OntResource supercls = theJenaModel.getOntResource(rightConceptName.getUri()); if (SadlUtils.classIsSubclassOf(subcls, supercls, true, null)) { return true; } if (SadlUtils.classIsSubclassOf(theJenaModel.getOntClass(rightConceptName.getUri()), theJenaModel.getOntResource(leftConceptName.getUri()), true, null)) { return true; } // TODO handle equivalent classes. // StmtIterator sitr = theJenaModel.listStatements(theJenaModel.getOntClass(rightConceptName.getUri()), OWL.equivalentClass, (RDFNode)null); // if (sitr.hasNext()) { // System.out.println(sitr.nextStatement().toString()); // else { // theJenaModel.write(System.out, "N-TRIPLE"); } catch (CircularDependencyException e) { e.printStackTrace(); // } catch (JenaProcessorException e) { // e.printStackTrace(); } } //Case: a class is being type-checked against a decomposition which is a sub/super-class of the former or // a decomposition variable is being type-checked against a class else if ((leftConceptName.getType().equals(ConceptType.ONTCLASS) && rightConceptName.getType().equals(ConceptType.VARIABLE)) || (leftConceptName.getType().equals(ConceptType.VARIABLE) && rightConceptName.getType().equals(ConceptType.ONTCLASS))) { try { if (SadlUtils.classIsSubclassOf(theJenaModel.getOntClass(leftConceptName.getUri()), theJenaModel.getOntResource(rightConceptName.getUri()), true, null)) { return true; } if (SadlUtils.classIsSubclassOf(theJenaModel.getOntClass(rightConceptName.getUri()), theJenaModel.getOntResource(leftConceptName.getUri()), true, null)) { return true; } } catch (CircularDependencyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if ((leftConceptName.getType().equals(ConceptType.INDIVIDUAL) && rightConceptName.getType().equals(ConceptType.ONTCLASS))) { if (instanceBelongsToClass(theJenaModel.getIndividual(leftConceptName.getUri()), theJenaModel.getOntClass(rightConceptName.getUri()))) { return true; } } else if ((leftConceptName.getType().equals(ConceptType.ONTCLASS) && rightConceptName.getType().equals(ConceptType.INDIVIDUAL))){ if (instanceBelongsToClass(theJenaModel.getIndividual(rightConceptName.getUri()), theJenaModel.getOntClass(leftConceptName.getUri()))) { return true; } } else if ((leftConceptName.getType().equals(ConceptType.INDIVIDUAL) && rightConceptName.getType().equals(ConceptType.INDIVIDUAL))){ // TODO Is this the right way to compare for two individuals? if (instancesHaveCommonType(theJenaModel.getIndividual(leftConceptName.getUri()), theJenaModel.getIndividual(rightConceptName.getUri()))) { return true; } } else if (leftConceptName.getType().equals(ConceptType.VARIABLE) && getModelProcessor().isDeclaration(rightExpression)) { return true; } } } } return false; } private boolean isCompatibleListTypes(List<String> operations, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) { // TODO Auto-generated method stub return false; } private ConceptName getListType(TypeCheckInfo tci) throws TranslationException, InvalidTypeException { Node tct = tci.getTypeCheckType(); if (tct != null) { if (tct instanceof NamedNode) { try { OntResource cls = theJenaModel.getOntResource(((NamedNode)tct).toFullyQualifiedString()); if (tci.getTypeToExprRelationship().equals(RANGE) || tci.getTypeToExprRelationship().equals(RESTRICTED_TO)) { if (cls.isURIResource()) { // return new ConceptName(cls.getURI()); return getModelProcessor().namedNodeToConceptName((NamedNode) tct); } } if (cls != null && cls.canAs(OntClass.class)){ ConceptName listcn = getListClassType(cls); if (listcn != null) { return listcn; } } } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return null; } protected ConceptName getListClassType(OntResource cls) { ExtendedIterator<OntClass> eitr = cls.as(OntClass.class).listSuperClasses(); while (eitr.hasNext()) { OntClass supercls = eitr.next(); if (supercls.isRestriction() && supercls.hasProperty(OWL.onProperty, theJenaModel.getProperty(SadlConstants.SADL_LIST_MODEL_FIRST_URI))) { RDFNode avf = supercls.getPropertyValue(OWL.allValuesFrom); if (avf.canAs(Resource.class)) { Resource r = avf.as(Resource.class); if (r.isURIResource()) { eitr.close(); return new ConceptName(r.getURI()); } } } } return null; } private boolean partOfTest(EObject leftExpression, EObject rightExpression) { if (checkForContainer(leftExpression, TestStatementImpl.class)) { return true; } return checkForContainer(rightExpression, TestStatement.class); } private <X extends EObject> boolean checkForContainer(EObject expr, Class<X> t ) { if (expr.eContainer() == null) { return false; } if (expr.eContainer().getClass().equals(t)) { return true; } return checkForContainer(expr.eContainer(), t); } protected boolean isQualifyingListOperation(List<String> operations, TypeCheckInfo leftTypeCheckInfo, TypeCheckInfo rightTypeCheckInfo) { if ((operations.contains("contain") || operations.contains("contains")) && leftTypeCheckInfo != null && leftTypeCheckInfo.getRangeValueType().equals(RangeValueType.LIST)) { return true; } if (operations.contains("unique") && operations.contains("in") && rightTypeCheckInfo != null && rightTypeCheckInfo.getRangeValueType().equals(RangeValueType.LIST)) { return true; } return false; } private boolean instancesHaveCommonType(Individual individualL, Individual individualR) { ExtendedIterator<Resource> lcitr = individualL.listRDFTypes(true); ExtendedIterator<Resource> rcitr = individualR.listRDFTypes(true); while (lcitr.hasNext()) { Resource lr = lcitr.next(); while (rcitr.hasNext()) { Resource rr = rcitr.next(); if (lr.equals(rr)) { lcitr.close(); rcitr.close(); return true; } } } return false; } private boolean instanceBelongsToClass(Individual individual, OntClass ontClass) { ExtendedIterator<Resource> citr = individual.listRDFTypes(false); while (citr.hasNext()) { Resource cls = citr.next(); if (cls.isURIResource() && cls.getURI().equals(ontClass.getURI())) { return true; } else { // this may be a union or intersection class; how should this be handled? // TODO } } return false; } private boolean isInteger(ConceptIdentifier type) throws InvalidNameException { if (type instanceof ConceptName) { String uri = ((ConceptName)type).getUri(); if (uri.equals(XSD.integer.getURI())) { return true; } else if (uri.equals(XSD.xint.getURI())) { return true; } else if (uri.equals(XSD.xlong.getURI())) { return true; } } return false; } private boolean isDecimal(ConceptIdentifier type) throws InvalidNameException { if (type instanceof ConceptName) { String uri = ((ConceptName)type).getUri(); if (uri.equals(XSD.xfloat.getURI()) || uri.equals(XSD.xdouble.getURI()) || uri.equals(XSD.decimal.getURI())) { return true; } } return false; } private EObject getDefaultContext() { return defaultContext; } private void setDefaultContext(EObject defaultContext) { this.defaultContext = defaultContext; } public Map<EObject, Property> getImpliedPropertiesUsed() { return impliedPropertiesUsed; } public boolean clearImpliedPropertiesUsed() { if (impliedPropertiesUsed != null) { impliedPropertiesUsed.clear(); return true; } return false; } public boolean removeImpliedPropertyUsed(EObject obj) { if (impliedPropertiesUsed != null) { if (impliedPropertiesUsed.containsKey(obj)) { impliedPropertiesUsed.remove(obj); return true; } } return false; } protected boolean addImpliedPropertiesUsed(EObject context, Property impliedPropertyUsed) { if (impliedPropertiesUsed == null) { impliedPropertiesUsed = new HashMap<EObject, Property>(); impliedPropertiesUsed.put(context, impliedPropertyUsed); return true; } else { if (!impliedPropertiesUsed.containsKey(context)) { impliedPropertiesUsed.put(context, impliedPropertyUsed); return true; } } return false; } public void checkPropertyDomain(OntModel ontModel, Expression subject, SadlResource predicate, Expression target, boolean propOfSubjectCheck) throws InvalidTypeException { OntConceptType ptype = null; try { ptype = declarationExtensions.getOntConceptType(predicate); } catch (CircularDefinitionException e1) { // TODO Auto-generated catch block e1.printStackTrace(); getModelProcessor().addIssueToAcceptor("Unable to get type. This should not happen. Please report.", predicate); return; } boolean checkDomain = true; if (ptype.equals(OntConceptType.VARIABLE) && declarationExtensions.getDeclaration(predicate).equals(predicate)) { getModelProcessor().addIssueToAcceptor(SadlErrorMessages.VARIABLE_INSTEAD_OF_PROP2.get(declarationExtensions.getConcreteName(predicate)), predicate); checkDomain = false; } if (subject instanceof SadlResource) { org.eclipse.emf.ecore.resource.Resource rsrc = subject.eResource(); if (rsrc != null) { if (ontModel != null) { try { OntConceptType stype = declarationExtensions.getOntConceptType((SadlResource)subject); String subjuri = declarationExtensions.getConceptUri((SadlResource) subject); String preduri = declarationExtensions.getConceptUri(predicate); NamedNode subjnn = new NamedNode(subjuri); subjnn.setNodeType(NodeType.ClassNode); NamedNode prednn = new NamedNode(preduri); prednn.setNodeType(getModelProcessor().ontConceptTypeToNodeType(ptype)); List<Node> lrs = getApplicableLocalRestrictions(subjnn, prednn); OntResource subj = null; String varName = null; if (stype.equals(OntConceptType.VARIABLE)) { TypeCheckInfo stci; // for now don't do any checking--may be able to do so later with variable definitions try { varName = declarationExtensions.getConcreteName((SadlResource)subject); stci = getType(subject); //It's possible that there are local restrictions // if (stci != null) { // TypeCheckInfo lr = getApplicableLocalRestriction(generateLocalRestrictionKey(varName)); // if (lr != null && lr.getTypeCheckType() != null) { // stci = lr; if (stci != null && stci.getTypeCheckType() != null) { subj = ontModel.getOntResource(stci.getTypeCheckType().toFullyQualifiedString()); if (subj != null) { Property prop = ontModel.getProperty(preduri); if (prop != null && checkDomain) { checkPropertyDomain(ontModel, subj, prop, target, propOfSubjectCheck, varName); } } } } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DontTypeCheckException e) { } catch (CircularDependencyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (PropertyWithoutRangeException e) { } } else if (stype.equals(OntConceptType.CLASS_PROPERTY)) { OntProperty propsubj = ontModel.getOntProperty(declarationExtensions.getConceptUri((SadlResource)subject)); if (propsubj != null) { Property prop = ontModel.getProperty(preduri); if (prop != null && checkDomain) { checkPropertyDomain(ontModel, propsubj, prop, target, propOfSubjectCheck, varName); } } } else { subj = ontModel.getOntResource(declarationExtensions.getConceptUri((SadlResource)subject)); if (subj != null) { if (preduri == null) { getModelProcessor().addIssueToAcceptor("Unable to resolve name", predicate); } else { Property prop = ontModel.getProperty(preduri); if (prop != null && checkDomain) { checkPropertyDomain(ontModel, subj, prop, target, propOfSubjectCheck, varName); } } } } } catch (CircularDefinitionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (PrefixNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InvalidNameException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (TranslationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } } public void checkPropertyDomain(OntModel ontModel, OntResource subj, Property prop, Expression target, boolean propOfSubjectCheck, String varName) throws InvalidTypeException { if(prop == null || prop.canAs(AnnotationProperty.class)){ return; } StmtIterator stmtitr = ontModel.listStatements(prop, RDFS.domain, (RDFNode)null); boolean matchFound = false; while (stmtitr.hasNext()) { RDFNode obj = stmtitr.nextStatement().getObject(); if (obj.isResource()) { matchFound = checkForPropertyDomainMatch(subj, prop, obj.asResource()); } if (matchFound) { stmtitr.close(); return; } } //Check for super properties if (prop.canAs(OntProperty.class)) { ExtendedIterator<? extends OntProperty> spropitr = prop.as(OntProperty.class).listSuperProperties(); while (spropitr.hasNext()) { OntProperty sprop = spropitr.next(); stmtitr = ontModel.listStatements(sprop, RDFS.domain, (RDFNode)null); while (stmtitr.hasNext()) { RDFNode obj = stmtitr.nextStatement().getObject(); if (obj.isResource()) { matchFound = checkForPropertyDomainMatch(subj, prop, obj.asResource()); } if (matchFound) { stmtitr.close(); break; } } } } if (subj != null && !matchFound) { if (varName != null) { if(propOfSubjectCheck){ getModelProcessor().addIssueToAcceptor(SadlErrorMessages.VARIABLE_NOT_IN_DOMAIN_OF_PROPERTY.get(varName, subj.getURI(),prop.getURI()), target); }else{ issueAcceptor.addWarning(SadlErrorMessages.VARIABLE_NOT_IN_DOMAIN_OF_PROPERTY.get(varName, getModelProcessor().rdfNodeToString(subj),getModelProcessor().rdfNodeToString(prop)), target); } } else { String msg; if (subj instanceof OntProperty) { msg = SadlErrorMessages.RANGE_OF_NOT_IN_DOMAIN_OF.get(getModelProcessor().rdfNodeToString(subj),getModelProcessor().rdfNodeToString(prop)); } else { msg = SadlErrorMessages.SUBJECT_NOT_IN_DOMAIN_OF_PROPERTY.get(getModelProcessor().rdfNodeToString(subj),getModelProcessor().rdfNodeToString(prop)); } if(propOfSubjectCheck){ getModelProcessor().addIssueToAcceptor(msg, target); }else{ issueAcceptor.addWarning(msg, target); } } } } private boolean checkForPropertyDomainMatch(Resource subj, Property prop, Resource obj) throws InvalidTypeException { if (obj.isResource()) { if (obj.canAs(UnionClass.class)){ List<OntResource> uclsMembers = getModelProcessor().getOntResourcesInUnionClass(theJenaModel, obj.as(UnionClass.class)); if (uclsMembers.contains(subj)) { return true; } if (subj.canAs(OntClass.class)){ for (int i = 0; i < uclsMembers.size(); i++) { OntResource member = uclsMembers.get(i); try { if (SadlUtils.classIsSubclassOf(subj.as(OntClass.class), member, true, null)) { return true; } } catch (CircularDependencyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else if (subj.canAs(Individual.class)){ ExtendedIterator<Resource> titr = subj.as(Individual.class).listRDFTypes(false); while (titr.hasNext()) { Resource type = titr.next(); if (uclsMembers.contains(type)) { titr.close(); return true; } } } } else if (subj != null && obj.isURIResource() && obj.asResource().getURI().equals(subj.getURI())) { return true; } else { if (subj.canAs(OntClass.class)){ try { if ( SadlUtils.classIsSubclassOf(subj.as(OntClass.class), obj.as(OntResource.class),true, null)) { return true; } // if (obj.canAs(OntClass.class) && SadlUtils.classIsSuperClassOf(obj.as(OntClass.class), subj.as(OntClass.class))) { // return true; } catch (CircularDependencyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (subj instanceof Property || subj.canAs(OntProperty.class)) { // this is a property chain missing an intermediate class or instance: get the range of the property StmtIterator stmtitr = getModelProcessor().getTheJenaModel().listStatements(subj, RDFS.range, (RDFNode)null); boolean matchFound = false; while (stmtitr.hasNext()) { RDFNode missingSubject = stmtitr.nextStatement().getObject(); if (missingSubject.isResource() && missingSubject.canAs(OntClass.class)) { try { if ( SadlUtils.classIsSubclassOf(missingSubject.as(OntClass.class), obj.as(OntResource.class),true, null)) { stmtitr.close(); return true; } } catch (CircularDependencyException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } else if (subj.canAs(Individual.class)){ Individual inst = subj.as(Individual.class); ExtendedIterator<Resource> itr = inst.listRDFTypes(false); while (itr.hasNext()) { Resource cls = itr.next(); boolean match = checkForPropertyDomainMatch(cls, prop, obj); if (match) { itr.close(); return true; } } } } } return false; } public List<ConceptName> getBinaryOpLeftImplliedProperties() { return binaryOpLeftImpliedProperties; } protected void setBinaryOpLeftImpliedProperties(List<ConceptName> binaryLeftTypeCheckInfo) { this.binaryOpLeftImpliedProperties = binaryLeftTypeCheckInfo; } public List<ConceptName> getBinaryOpRightImpliedProperties() { return binaryOpRightImpliedProperties; } protected void setBinaryOpRightImpliedProperties(List<ConceptName> binaryRightTypeCheckInfo) { this.binaryOpRightImpliedProperties = binaryRightTypeCheckInfo; } /** * Clear old values of left and right impliedProperties */ public void clearImpliedProperties() { setBinaryOpLeftImpliedProperties(null); setBinaryOpRightImpliedProperties(null); } protected JenaBasedSadlModelProcessor getModelProcessor() throws InvalidTypeException { return modelProcessor; } protected void setModelProcessor(JenaBasedSadlModelProcessor modelProcessor) { this.modelProcessor = modelProcessor; } public void resetValidatorState(SadlModelElement element) { if (impliedPropertiesUsed != null) { impliedPropertiesUsed.clear(); } if (binaryOpLeftImpliedProperties != null) { binaryOpLeftImpliedProperties.clear(); } if (binaryOpRightImpliedProperties != null) { binaryOpRightImpliedProperties.clear(); } } private Sublist getSublistContainer(EObject expression) { if (expression instanceof Sublist) { return (Sublist) expression; } if (expression.eContainer() != null) { return getSublistContainer(expression.eContainer()); } return null; } public boolean checkPropertyValueInRange(OntModel theJenaModel, Expression subj, SadlResource pred, EObject val, StringBuilder errorMessageBuilder) throws CircularDefinitionException, DontTypeCheckException, InvalidNameException, TranslationException, URISyntaxException, IOException, ConfigurationException, InvalidTypeException, CircularDependencyException, PropertyWithoutRangeException { TypeCheckInfo predType = getType(pred); if (predType == null) { return true; // this is an error which will have already been marked in call to getType } if (val == null && isInQuery(pred)) { return true; // this is OK } TypeCheckInfo valType = getType(val); List<String> operations = Arrays.asList("is"); if (declarationExtensions.getOntConceptType(pred).equals(OntConceptType.DATATYPE_PROPERTY)) { if (!checkNumericRangeLimits("=", predType, valType)) { return true; // return true so as to not generate error at higher level; failure has already created marker } } if (compareTypes(operations , pred, val, predType, valType, ImplicitPropertySide.NONE)) { return true; } // // TODO check for restrictions on subj class // OntConceptType predtype = declarationExtensions.getOntConceptType(pred); // String preduri = declarationExtensions.getConceptUri(pred); // Property prop = theJenaModel.getProperty(preduri); // if (prop == null) { // throw new JenaProcessorException("Unable to find property '" + preduri + "' in model."); // RDFNode val; // if (value instanceof SadlResource) { // OntConceptType srType = declarationExtensions.getOntConceptType((SadlResource)value); // SadlResource srValue = (SadlResource) value; // if (srType == null) { // srValue = ((SadlResource)value).getName(); // srType = declarationExtensions.getOntConceptType(srValue); // if (srType == null) { // throw new JenaProcessorException("Unable to resolve SadlResource value"); // if (srType.equals(OntConceptType.INSTANCE)) { // String valUri = declarationExtensions.getConceptUri(srValue); // if (valUri == null) { // throw new JenaProcessorException("Failed to find SadlResource in Xtext model"); // val = theJenaModel.getIndividual(valUri); // if (val == null) { // throw new JenaProcessorException("Failed to retrieve instance '" + valUri + "' from Jena model"); // return checkObjectPropertyValueInRange(prop, (Individual)val); // else { // return false; // else if (value instanceof SadlExplicitValue) { // if (prop.canAs(OntProperty.class)) { // val = modelProcessor.sadlExplicitValueToLiteral((SadlExplicitValue) value, prop.as(OntProperty.class).getRange()); // else { // val = modelProcessor.sadlExplicitValueToLiteral((SadlExplicitValue) value, null); // return checkDataPropertyValueInRange(theJenaModel, null, prop, val); if (createErrorMessage(errorMessageBuilder, predType, valType, operations.get(0), false, val.eContainer())) { return false; } else { return true; } } private boolean checkNumericRangeLimits(String op, TypeCheckInfo predType, TypeCheckInfo valType) throws TranslationException { if (valType == null || predType == null) { return false; // return as error } if (valType.getExplicitValue() instanceof Literal) { Object value = ((Literal)valType.getExplicitValue()).getValue(); Node rngType = predType.getTypeCheckType(); if (!(rngType instanceof NamedNode)) { throw new TranslationException("Unexpected non-NamedNode TypeCheckInfo typeCheckType"); } boolean outOfRange = false; if (rngType.toFullyQualifiedString().equals(XSD.xint.getURI())) { if (op.equals(">") || op.equals("<")) { if (value instanceof Long && ((Long)value >= MAX_INT || (Long)value <= MIN_INT)) { outOfRange = true; } else if (value instanceof Integer && ((Integer)value >= MAX_INT || (Integer)value <= MIN_INT)) { outOfRange = true; } } else { if (value instanceof Long && ((Long)value > MAX_INT || (Long)value < MIN_INT)) { outOfRange = true; } else if (value instanceof Integer && ((Integer)value > MAX_INT || (Integer)value < MIN_INT)) { outOfRange = true; } } if (outOfRange) { modelProcessor.addIssueToAcceptor("Value is not in range of property", valType.context); return false; } } else if (rngType.toFullyQualifiedString().equals(XSD.xlong.getURI())) { if (op.equals(">") || op.equals("<")) { if (value instanceof Long && ((Long)value >= MAX_LONG || (Long)value <= MIN_LONG)) { outOfRange = true; } else if (value instanceof Integer && ((Integer)value >= MAX_LONG || (Integer)value <= MIN_LONG)) { outOfRange = true; } } else { if (value instanceof Long && ((Long)value > MAX_LONG || (Long)value < MIN_LONG)) { outOfRange = true; } else if (value instanceof Integer && ((Integer)value > MAX_LONG || (Integer)value < MIN_LONG)) { outOfRange = true; } } if (outOfRange) { modelProcessor.addIssueToAcceptor("Value is not in range of property", valType.context); return false; } } } return true; // if we don't detect a problem assume that there isn't one } public boolean checkDataPropertyValueInRange(OntModel theJenaModel2, Resource subj, OntProperty prop, Literal val) { OntResource rng = prop.getRange(); if (rng == null) { return true; } String ptype = prop.getRange().getURI(); if (ptype == null) { return true; } String dtype = val.getDatatypeURI(); if (dtype.equals(ptype)) { return true; } if (dtype.equals(XSD.xint.getURI())) { // the literal is an integer if (ptype.equals(XSD.integer.getURI())) return true; if (ptype.equals(XSD.xlong.getURI())) return true; } return false; } public boolean checkObjectPropertyRange(OntModel theJenaModel2, OntProperty pred, OntResource obj, boolean isList, EObject expr) throws CircularDependencyException { if (pred.isObjectProperty()) { if (checkRangeForMatch(theJenaModel2, pred, obj, isList)) { return true; } ExtendedIterator<? extends OntProperty> propitr = pred.listSuperProperties(false); while (propitr.hasNext()) { OntProperty sprop = propitr.next(); if (checkRangeForMatch(theJenaModel2, sprop, obj, isList)) { propitr.close(); return true; } } return false; } return true; } public boolean checkPropertyRange(OntModel theJenaModel2, OntProperty pred, OntResource obj, boolean isList, EObject expr) throws CircularDependencyException { if (checkRangeForMatch(theJenaModel2, pred, obj, isList)) { return true; } ExtendedIterator<? extends OntProperty> propitr = pred.listSuperProperties(false); while (propitr.hasNext()) { OntProperty sprop = propitr.next(); if (checkRangeForMatch(theJenaModel2, sprop, obj, isList)) { propitr.close(); return true; } } return false; } private boolean checkRangeForMatch(OntModel theJenaModel2, OntProperty pred, OntResource obj, boolean isList) throws CircularDependencyException { StmtIterator rngitr = theJenaModel2.listStatements(pred, RDFS.range, (RDFNode)null); while (rngitr.hasNext()) { RDFNode rng = rngitr.nextStatement().getObject(); if (isTypedListSubclass(rng)) { if (!isList) { rngitr.close(); return false; } if (rng.canAs(OntClass.class )) { rng = getSadlTypedListType(rng.as(OntClass.class)); } else { // TODO this is an unhandled case } } if (obj instanceof Individual) { ExtendedIterator<Resource> institr = obj.asIndividual().listRDFTypes(true); while (institr.hasNext()) { Resource typ = institr.next(); if (rng.canAs(OntClass.class)) { if (SadlUtils.classIsSubclassOf(typ.as(OntClass.class), rng.asResource().as(OntClass.class), true, null)) { institr.close(); rngitr.close(); return true; } } } } else if (obj.canAs(OntClass.class) && rng.isResource() && rng.asResource().canAs(OntClass.class)) { if (SadlUtils.classIsSubclassOf(obj.as(OntClass.class), rng.asResource().as(OntClass.class), true, null)) { rngitr.close(); return true; } } } return false; } protected List<Node> getApplicableLocalRestrictions(NamedNode subj, NamedNode prop) throws IOException, PrefixNotFoundException, InvalidNameException, InvalidTypeException, TranslationException, ConfigurationException { // TODO Auto-generated method stub return null; } private List<Node> getApplicableLocalRestrictions(TripleElement tr) { if (tr.getSubject() instanceof NamedNode && tr.getPredicate() instanceof NamedNode) { try { return getApplicableLocalRestrictions((NamedNode)tr.getSubject(), (NamedNode)tr.getPredicate()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (PrefixNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidNameException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidTypeException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TranslationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } }
package org.jtalks.jcommune.service.jmx; import com.google.common.collect.Lists; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; /** @author stanislav bashkirtsev */ public class Log4jConfiguratorTest { private Log4jConfigurator sut; @BeforeMethod public void initSutAndDocs() throws Exception { sut = spy(new Log4jConfigurator()); } @Test public void getLoggersShouldReturnAllAvailableNames() { List<Logger> allLoggers = Lists.newArrayList(logger("a", "DEBUG"), logger("b", "INFO")); doReturn(allLoggers).when(sut).getAllLoggers(); assertEquals(sut.getLoggers(), Lists.newArrayList("a = DEBUG", "b = INFO")); } @Test public void getLoggersShouldReturnEmptyListIfNoLoggersConfigured() { doReturn(Lists.newArrayList()).when(sut).getAllLoggers(); assertTrue(sut.getLoggers().isEmpty()); } @Test public void testGetLogLevel() throws Exception { doReturn(logger("a", "INFO")).when(sut).getLogger("a"); assertEquals(sut.getLogLevel("a"), "INFO"); } @Test public void getLogLevelReturnsUnavailableIfNoSuchLogger(){ doReturn(null).when(sut).getLogger("a"); assertEquals(sut.getLogLevel("a"), "unavailable"); } @Test public void testSetLogLevel() throws Exception { doReturn(logger("a", "INFO")).when(sut).getLogger("a"); sut.setLogLevel("a", "DEBUG"); assertEquals(sut.getLogLevel("a"), "DEBUG"); } private Logger logger(String name, String level){ Logger logger = Logger.getLogger(name); logger = spy(logger); logger.setLevel(Level.toLevel(level)); return logger; } }
package com.pholser.util.properties.internal.conversions; import java.lang.reflect.Constructor; import com.pholser.util.properties.internal.exceptions.ValueConversionException; import com.pholser.util.properties.testonly.ForTriggeringIllegalAccess; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class ErrorsThatOccurWhenConvertingValuesViaConstructorsTest { @Test public void transformingInvocationTargetExceptions() throws Exception { Constructor<ConstructorRaisesException> ctor = ConstructorRaisesException.class.getDeclaredConstructor(String.class); try { new ConstructorInvokingValueConverter(ctor).convert(""); fail(); } catch (ValueConversionException expected) { assertThat(expected.getCause(), is(UnsupportedOperationException.class)); } } @Test public void transformingIllegalArgumentExceptions() throws Exception { Constructor<HasPlainOldConstructor> ctor = HasPlainOldConstructor.class.getDeclaredConstructor(); try { new ConstructorInvokingValueConverter(ctor).convert(""); fail(); } catch (ValueConversionException expected) { assertThat(expected.getCause(), is(IllegalArgumentException.class)); } } @Test public void transformingIllegalAccessExceptions() throws Exception { Constructor<ForTriggeringIllegalAccess> ctor = ForTriggeringIllegalAccess.class.getDeclaredConstructor(String.class); try { new ConstructorInvokingValueConverter(ctor).convert(""); fail(); } catch (ValueConversionException expected) { assertThat(expected.getCause(), is(IllegalAccessException.class)); } } @Test public void transformingInstantiationExceptions() throws Exception { Constructor<CannotBeInstantiated> ctor = CannotBeInstantiated.class.getDeclaredConstructor(String.class); try { new ConstructorInvokingValueConverter(ctor).convert(""); fail(); } catch (ValueConversionException expected) { assertThat(expected.getCause(), is(InstantiationException.class)); } } static class ConstructorRaisesException { ConstructorRaisesException(@SuppressWarnings("unused") String argument) { throw new UnsupportedOperationException(); } } static class HasPlainOldConstructor { // nothing to do here } abstract static class CannotBeInstantiated { CannotBeInstantiated(@SuppressWarnings("unused") String argument) { // nothing to do here } } }
package com.sdl.dxa.modules.ish.providers; import com.sdl.dxa.api.datamodel.model.SitemapItemModelData; import com.sdl.dxa.common.dto.SitemapRequestDto; import com.sdl.dxa.tridion.navigation.dynamic.DynamicNavigationModelProviderImpl; import com.sdl.web.api.dynamic.taxonomies.WebTaxonomyFactory; import com.tridion.taxonomies.Keyword; import com.tridion.taxonomies.TaxonomyRelationManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.List; @Service @Qualifier("ishDynamicNavigationModelProvider") public class IshDynamicNavigationModelProvider extends DynamicNavigationModelProviderImpl { public IshDynamicNavigationModelProvider(WebTaxonomyFactory taxonomyFactory, TaxonomyRelationManager relationManager) { super(taxonomyFactory, relationManager); } @Override protected String getKeywordMetaUri(String taxonomyId, SitemapRequestDto requestDto, List<SitemapItemModelData> children, Keyword keyword, boolean needsToAddChildren) { if (keyword ==null || keyword.getKeywordMeta() == null) return ""; Object firstValue = keyword.getKeywordMeta().getFirstValue("ish.ref.uri"); return firstValue == null ? "" : firstValue.toString().replaceAll("\\D+:(\\d++)-(\\d++)-\\d++", "$1/$2"); } }
package am.extension.userfeedback.experiments; import java.io.Serializable; import am.extension.userfeedback.UFLRegistry.CSEvaluationRegistry; import am.extension.userfeedback.UFLRegistry.CandidateSelectionRegistry; import am.extension.userfeedback.UFLRegistry.ExperimentRegistry; import am.extension.userfeedback.UFLRegistry.FeedbackPropagationRegistry; import am.extension.userfeedback.UFLRegistry.InitialMatcherRegistry; import am.extension.userfeedback.UFLRegistry.LoopInizializationRegistry; import am.extension.userfeedback.UFLRegistry.PropagationEvaluationRegistry; import am.extension.userfeedback.UFLRegistry.SaveFeedbackRegistry; import am.extension.userfeedback.UFLRegistry.UserValidationRegistry; public class UFLExperimentSetup implements Serializable { private static final long serialVersionUID = 2006678734079546244L; /** The experiment class that we are using. */ public ExperimentRegistry exp; public InitialMatcherRegistry im; public LoopInizializationRegistry fli; public CandidateSelectionRegistry cs; public CSEvaluationRegistry cse; public UserValidationRegistry uv; public FeedbackPropagationRegistry fp; public PropagationEvaluationRegistry pe; public SaveFeedbackRegistry sf; /** * Experiment-wide parameters. */ public UFLExperimentParameters parameters; }
package com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BaseRemoteRequestor implements RemoteRequestor { private static final int HTTP_STATUS_CODE_UNAUTHORIZED = 401; private static final int HTTP_STATUS_CODE_FORBIDDEN = 403; private static final int HTTP_STATUS_CODE_NOT_FOUND = 404; private final Logger log = LoggerFactory.getLogger(BaseRemoteRequestor.class); protected final String apiUrl; private HttpClientProxyConfig proxyConfig; public BaseRemoteRequestor(String apiUrl) { this.apiUrl = apiUrl; proxyConfig = new HttpClientProxyConfig(); } @Override public <T> T get(String uri, Map<String, String> parameters, ResponseCallback<T> callback) { HttpGet getMethod = new HttpGet(); return requestWithoutPayload(getMethod, uri, parameters, callback); } @Override public <T> T delete(String uri, Map<String, String> parameters, ResponseCallback<T> callback) { HttpDelete method = new HttpDelete(); return requestWithoutPayload(method, uri, parameters, callback); } @Override public <T> T post(String uri, Map<String, String> parameters, ResponseCallback<T> callback) { HttpPost method = new HttpPost(); return requestWithPayload(method, uri, parameters, callback); } @Override public <T> T put(String uri, Map<String, String> parameters, ResponseCallback<T> callback) { HttpPut method = new HttpPut(); return requestWithPayload(method, uri, parameters, callback); } // extension hooks /** * E.g. append basic auth headers ... */ protected void onConnectionCreated(DefaultHttpClient client, HttpRequestBase method, Map<String, String> params) throws IOException { } /** * E.g. append oauth params ... */ protected String afterFinalUriConstructed(HttpRequestBase method, String finalUri, Map<String, String> params) { return finalUri; } // Helpers protected void logRequest(HttpRequestBase method, String finalUrl, Map<String, String> params) { log.debug("[Headers {}]", method.getParams()); log.debug("[REST call {} : {} :: {}]", new Object[] { method.getMethod(), finalUrl, params }); } private <T> T requestWithPayload(HttpEntityEnclosingRequestBase method, String uri, Map<String, String> params, ResponseCallback<T> callback) { DefaultHttpClient client = new DefaultHttpClient(); RemoteResponse response = null; try { createConnection(client, method, uri, params); setPayloadParams(method, params); HttpResponse httpResponse = client.execute(method); response = checkAndCreateRemoteResponse(client, httpResponse); return callback.onResponse(response); } catch (BitbucketRequestException e) { throw e; // Unauthorized or NotFound exceptions will be rethrown } catch (IOException e) { log.debug("Failed to execute request: " + method.getURI(), e); throw new BitbucketRequestException("Failed to execute request " + method.getURI(), e); } catch (URISyntaxException e) { log.debug("Failed to execute request: " + method.getURI(), e); throw new BitbucketRequestException("Failed to execute request " + method.getURI(), e); } finally { closeResponse(response); } } private void closeResponse(RemoteResponse response) { if (response != null) { response.close(); } } private <T> T requestWithoutPayload(HttpRequestBase method, String uri, Map<String, String> parameters, ResponseCallback<T> callback) { DefaultHttpClient client = new DefaultHttpClient(); RemoteResponse response = null; try { createConnection(client, method, uri + paramsToString(parameters, uri.contains("?")), parameters); HttpResponse httpResponse = client.execute(method); response = checkAndCreateRemoteResponse(client, httpResponse); return callback.onResponse(response); } catch (IOException e) { log.debug("Failed to execute request: " + method.getURI(), e); throw new BitbucketRequestException("Failed to execute request " + method.getURI(), e); } catch (URISyntaxException e) { log.debug("Failed to execute request: " + method.getURI(), e); throw new BitbucketRequestException("Failed to execute request " + method.getURI(), e); } finally { closeResponse(response); } } private RemoteResponse checkAndCreateRemoteResponse(DefaultHttpClient client, HttpResponse httpResponse) throws IOException { RemoteResponse response = new RemoteResponse(); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode >= 300) { RuntimeException toBeThrown = new BitbucketRequestException("Error response code during the request : " + statusCode); switch (statusCode) { case HttpStatus.SC_UNAUTHORIZED: toBeThrown = new BitbucketRequestException.Unauthorized_401(); case HttpStatus.SC_FORBIDDEN: toBeThrown = new BitbucketRequestException.Forbidden_403(); case HttpStatus.SC_NOT_FOUND: toBeThrown = new BitbucketRequestException.NotFound_404(); } // log.error("Failed to properly execute request [" + connection.getRequestMethod() + "] : " + connection, toBeThrown); throw toBeThrown; } response.setHttpStatusCode(statusCode); if (httpResponse.getEntity() != null) { response.setResponse(httpResponse.getEntity().getContent()); } response.setHttpClient(client); return response; } protected String paramsToString(Map<String, String> parameters, boolean urlAlreadyHasParams) { StringBuilder queryStringBuilder = new StringBuilder(); if (parameters != null && !parameters.isEmpty()) { if (!urlAlreadyHasParams) { queryStringBuilder.append("?"); } else { queryStringBuilder.append("&"); } paramsMapToString(parameters, queryStringBuilder); } return queryStringBuilder.toString(); } private void paramsMapToString(Map<String, String> parameters, StringBuilder builder) { for (Iterator<Map.Entry<String, String>> iterator = parameters.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, String> entry = iterator.next(); builder.append(encode(entry.getKey())); builder.append("="); builder.append(encode(entry.getValue())); if (iterator.hasNext()) { builder.append("&"); } } } private static String encode(String str) { if (str == null) { return null; } try { return URLEncoder.encode(str, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new BitbucketRequestException("Required encoding not found", e); } } private void createConnection(DefaultHttpClient client, HttpRequestBase method, String uri, Map<String, String> params) throws IOException, URISyntaxException { proxyConfig.configureProxy(client, apiUrl + uri); String finalUrl = afterFinalUriConstructed(method, apiUrl + uri, params); method.setURI(new URI(finalUrl)); logRequest(method, finalUrl, params); // something to extend onConnectionCreated(client, method, params); } private void setPayloadParams(HttpEntityEnclosingRequestBase method, Map<String, String> params) throws IOException { if (params != null) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); for (Entry<String, String> entry : params.entrySet()) { formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); method.setEntity(entity); } } }
package com.fsck.k9.activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Config; import android.util.Log; import android.util.TypedValue; import android.view.*; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.*; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import com.fsck.k9.*; import com.fsck.k9.Account.FolderMode; import com.fsck.k9.activity.setup.AccountSettings; import com.fsck.k9.activity.setup.FolderSettings; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.Message; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.service.MailService; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; /** * FolderList is the primary user interface for the program. This * Activity shows list of the Account's folders */ public class FolderList extends K9ListActivity { private static final int DIALOG_MARK_ALL_AS_READ = 1; private static final String EXTRA_ACCOUNT = "account"; private static final String EXTRA_INITIAL_FOLDER = "initialFolder"; //private static final String STATE_CURRENT_FOLDER = "com.fsck.k9.activity.folderlist_folder"; private static final String EXTRA_CLEAR_NOTIFICATION = "clearNotification"; private static final boolean REFRESH_REMOTE = true; private ListView mListView; private FolderListAdapter mAdapter; private LayoutInflater mInflater; private Account mAccount; private FolderListHandler mHandler = new FolderListHandler(); private int mUnreadMessageCount; private FontSizes mFontSizes = K9.getFontSizes(); class FolderListHandler extends Handler { public void refreshTitle() { runOnUiThread(new Runnable() { public void run() { String dispString = mAdapter.mListener.formatHeader(FolderList.this, getString(R.string.folder_list_title, mAccount.getDescription()), mUnreadMessageCount, getTimeFormat()); setTitle(dispString); } }); } public void newFolders(final List<FolderInfoHolder> newFolders) { runOnUiThread(new Runnable() { public void run() { mAdapter.mFolders.clear(); mAdapter.mFolders.addAll(newFolders); mHandler.dataChanged(); } }); } public void workingAccount(final int res) { runOnUiThread(new Runnable() { public void run() { String toastText = getString(res, mAccount.getDescription()); Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_SHORT); toast.show(); } }); } public void accountSizeChanged(final long oldSize, final long newSize) { runOnUiThread(new Runnable() { public void run() { String toastText = getString(R.string.account_size_changed, mAccount.getDescription(), SizeFormatter.formatSize(getApplication(), oldSize), SizeFormatter.formatSize(getApplication(), newSize)); Toast toast = Toast.makeText(getApplication(), toastText, Toast.LENGTH_LONG); toast.show(); } }); } public void folderLoading(final String folder, final boolean loading) { runOnUiThread(new Runnable() { public void run() { FolderInfoHolder folderHolder = mAdapter.getFolder(folder); if (folderHolder != null) { folderHolder.loading = loading; } } }); } public void progress(final boolean progress) { runOnUiThread(new Runnable() { public void run() { setProgressBarIndeterminateVisibility(progress); } }); } public void dataChanged() { runOnUiThread(new Runnable() { public void run() { mAdapter.notifyDataSetChanged(); } }); } } /** * This class is responsible for reloading the list of local messages for a * given folder, notifying the adapter that the message have been loaded and * queueing up a remote update of the folder. */ private void checkMail(FolderInfoHolder folder) { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); final WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Email - UpdateWorker"); wakeLock.setReferenceCounted(false); wakeLock.acquire(K9.WAKE_LOCK_TIMEOUT); MessagingListener listener = new MessagingListener() { @Override public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { if (!account.equals(mAccount)) { return; } wakeLock.release(); } @Override public void synchronizeMailboxFailed(Account account, String folder, String message) { if (!account.equals(mAccount)) { return; } wakeLock.release(); } }; MessagingController.getInstance(getApplication()).synchronizeMailbox(mAccount, folder.name, listener); sendMail(mAccount); } private static void actionHandleAccount(Context context, Account account, String initialFolder) { Intent intent = new Intent(context, FolderList.class); intent.putExtra(EXTRA_ACCOUNT, account.getUuid()); if (initialFolder != null) { intent.putExtra(EXTRA_INITIAL_FOLDER, initialFolder); } context.startActivity(intent); } public static void actionHandleAccount(Context context, Account account) { actionHandleAccount(context, account, null); } public static Intent actionHandleAccountIntent(Context context, Account account, String initialFolder) { Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse("email://accounts/" + account.getAccountNumber()), context, FolderList.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(EXTRA_ACCOUNT, account.getUuid()); intent.putExtra(EXTRA_CLEAR_NOTIFICATION, true); if (initialFolder != null) { intent.putExtra(EXTRA_INITIAL_FOLDER, initialFolder); } return intent; } public static Intent actionHandleAccountIntent(Context context, Account account) { return actionHandleAccountIntent(context, account, null); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); mListView = getListView(); mListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET); mListView.setLongClickable(true); mListView.setFastScrollEnabled(true); mListView.setScrollingCacheEnabled(true); mListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { onOpenFolder(((FolderInfoHolder)mAdapter.getItem(id)).name); } }); registerForContextMenu(mListView); mListView.setSaveEnabled(true); mInflater = getLayoutInflater(); onNewIntent(getIntent()); } @Override public void onNewIntent(Intent intent) { setIntent(intent); // onNewIntent doesn't autoset our "internal" intent String initialFolder; mUnreadMessageCount = 0; String accountUuid = intent.getStringExtra(EXTRA_ACCOUNT); mAccount = Preferences.getPreferences(this).getAccount(accountUuid); initialFolder = intent.getStringExtra(EXTRA_INITIAL_FOLDER); if ( initialFolder != null && !K9.FOLDER_NONE.equals(initialFolder)) { onOpenFolder(initialFolder); finish(); } else { initializeActivityView(); } } private void initializeActivityView() { mAdapter = new FolderListAdapter(); final Object previousData = getLastNonConfigurationInstance(); if (previousData != null) { //noinspection unchecked mAdapter.mFolders = (ArrayList<FolderInfoHolder>) previousData; } setListAdapter(mAdapter); setTitle(mAccount.getDescription()); } @Override public Object onRetainNonConfigurationInstance() { return mAdapter.mFolders; } @Override public void onPause() { super.onPause(); MessagingController.getInstance(getApplication()).removeListener(mAdapter.mListener); } /** * On resume we refresh the folder list (in the background) and we refresh the * messages for any folder that is currently open. This guarantees that things * like unread message count and read status are updated. */ @Override public void onResume() { super.onResume(); if (mAdapter == null) initializeActivityView(); MessagingController.getInstance(getApplication()).addListener(mAdapter.mListener); //mAccount.refresh(Preferences.getPreferences(this)); MessagingController.getInstance(getApplication()).getAccountStats(this, mAccount, mAdapter.mListener); onRefresh(!REFRESH_REMOTE); NotificationManager notifMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notifMgr.cancel(mAccount.getAccountNumber()); notifMgr.cancel(-1000 - mAccount.getAccountNumber()); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { //Shortcuts that work no matter what is selected switch (keyCode) { case KeyEvent.KEYCODE_Q: //case KeyEvent.KEYCODE_BACK: { onAccounts(); return true; } case KeyEvent.KEYCODE_S: { onEditAccount(); return true; } case KeyEvent.KEYCODE_H: { Toast toast = Toast.makeText(this, R.string.folder_list_help_key, Toast.LENGTH_LONG); toast.show(); return true; } case KeyEvent.KEYCODE_1: { setDisplayMode(FolderMode.FIRST_CLASS); return true; } case KeyEvent.KEYCODE_2: { setDisplayMode(FolderMode.FIRST_AND_SECOND_CLASS); return true; } case KeyEvent.KEYCODE_3: { setDisplayMode(FolderMode.NOT_SECOND_CLASS); return true; } case KeyEvent.KEYCODE_4: { setDisplayMode(FolderMode.ALL); return true; } }//switch return super.onKeyDown(keyCode, event); }//onKeyDown private void setDisplayMode(FolderMode newMode) { mAccount.setFolderDisplayMode(newMode); mAccount.save(Preferences.getPreferences(this)); if (mAccount.getFolderPushMode() != FolderMode.NONE) { MailService.actionRestartPushers(this, null); } onRefresh(false); } private void onRefresh(final boolean forceRemote) { MessagingController.getInstance(getApplication()).listFolders(mAccount, forceRemote, mAdapter.mListener); } private void onEditAccount() { AccountSettings.actionSettings(this, mAccount); } private void onEditFolder(Account account, String folderName) { FolderSettings.actionSettings(this, account, folderName); } private void onAccounts() { Accounts.listAccounts(this); finish(); } private void onEmptyTrash(final Account account) { mHandler.dataChanged(); MessagingController.getInstance(getApplication()).emptyTrash(account, null); } private void onExpunge(final Account account, String folderName) { MessagingController.getInstance(getApplication()).expunge(account, folderName, null); } private void checkMail(final Account account) { MessagingController.getInstance(getApplication()).checkMail(this, account, true, true, mAdapter.mListener); } private void sendMail(Account account) { MessagingController.getInstance(getApplication()).sendPendingMessages(account, mAdapter.mListener); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.compose: MessageCompose.actionCompose(this, mAccount); return true; case R.id.check_mail: checkMail(mAccount); return true; case R.id.send_messages: MessagingController.getInstance(getApplication()).sendPendingMessages(mAccount, null); return true; case R.id.accounts: onAccounts(); return true; case R.id.list_folders: onRefresh(REFRESH_REMOTE); return true; case R.id.account_settings: onEditAccount(); return true; case R.id.empty_trash: onEmptyTrash(mAccount); return true; case R.id.compact: onCompact(mAccount); return true; case R.id.clear: onClear(mAccount); return true; case R.id.display_1st_class: { setDisplayMode(FolderMode.FIRST_CLASS); return true; } case R.id.display_1st_and_2nd_class: { setDisplayMode(FolderMode.FIRST_AND_SECOND_CLASS); return true; } case R.id.display_not_second_class: { setDisplayMode(FolderMode.NOT_SECOND_CLASS); return true; } case R.id.display_all: { setDisplayMode(FolderMode.ALL); return true; } default: return super.onOptionsItemSelected(item); } } private void onOpenFolder(String folder) { MessageList.actionHandleFolder(this, mAccount, folder); } private void onCompact(Account account) { mHandler.workingAccount(R.string.compacting_account); MessagingController.getInstance(getApplication()).compact(account, null); } private void onClear(Account account) { mHandler.workingAccount(R.string.clearing_account); MessagingController.getInstance(getApplication()).clear(account, null); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.folder_list_option, menu); return true; } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); FolderInfoHolder folder = (FolderInfoHolder) mAdapter.getItem(info.position); switch (item.getItemId()) { case R.id.open_folder: onOpenFolder(folder.name); break; case R.id.mark_all_as_read: onMarkAllAsRead(mAccount, folder.name); break; case R.id.send_messages: sendMail(mAccount); break; case R.id.check_mail: checkMail(folder); break; case R.id.folder_settings: onEditFolder(mAccount, folder.name); break; case R.id.empty_trash: onEmptyTrash(mAccount); break; case R.id.expunge: onExpunge(mAccount, folder.name); break; } return super.onContextItemSelected(item); } private FolderInfoHolder mSelectedContextFolder = null; private void onMarkAllAsRead(final Account account, final String folder) { mSelectedContextFolder = mAdapter.getFolder(folder); showDialog(DIALOG_MARK_ALL_AS_READ); } @Override public Dialog onCreateDialog(int id) { switch (id) { case DIALOG_MARK_ALL_AS_READ: return createMarkAllAsReadDialog(); } return super.onCreateDialog(id); } @Override public void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DIALOG_MARK_ALL_AS_READ: ((AlertDialog)dialog).setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mSelectedContextFolder.displayName)); break; default: super.onPrepareDialog(id, dialog); } } private Dialog createMarkAllAsReadDialog() { return new AlertDialog.Builder(this) .setTitle(R.string.mark_all_as_read_dlg_title) .setMessage(getString(R.string.mark_all_as_read_dlg_instructions_fmt, mSelectedContextFolder.displayName)) .setPositiveButton(R.string.okay_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); try { MessagingController.getInstance(getApplication()).markAllMessagesRead(mAccount, mSelectedContextFolder.name); mSelectedContextFolder.unreadMessageCount = 0; mHandler.dataChanged(); } catch (Exception e) { // Ignore } } }) .setNegativeButton(R.string.cancel_action, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dismissDialog(DIALOG_MARK_ALL_AS_READ); } }) .create(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; getMenuInflater().inflate(R.menu.folder_context, menu); FolderInfoHolder folder = (FolderInfoHolder) mAdapter.getItem(info.position); menu.setHeaderTitle((CharSequence) folder.displayName); if (!folder.name.equals(mAccount.getTrashFolderName())) menu.findItem(R.id.empty_trash).setVisible(false); if (folder.outbox) { menu.findItem(R.id.check_mail).setVisible(false); } else { menu.findItem(R.id.send_messages).setVisible(false); } if (K9.ERROR_FOLDER_NAME.equals(folder.name)) { menu.findItem(R.id.expunge).setVisible(false); } menu.setHeaderTitle(folder.displayName); } private String truncateStatus(String mess) { if (mess != null && mess.length() > 27) { mess = mess.substring(0, 27); } return mess; } class FolderListAdapter extends BaseAdapter { private ArrayList<FolderInfoHolder> mFolders = new ArrayList<FolderInfoHolder>(); public Object getItem(long position) { return getItem((int)position); } public Object getItem(int position) { return mFolders.get(position); } public long getItemId(int position) { return position ; } public int getCount() { return mFolders.size(); } @Override public boolean isEnabled(int item) { return true; } @Override public boolean areAllItemsEnabled() { return true; } private ActivityListener mListener = new ActivityListener() { @Override public void accountStatusChanged(BaseAccount account, AccountStats stats) { if (!account.equals(mAccount)) { return; } mUnreadMessageCount = stats.unreadMessageCount; mHandler.refreshTitle(); } @Override public void listFoldersStarted(Account account) { if (!account.equals(mAccount)) { return; } mHandler.progress(true); } @Override public void listFoldersFailed(Account account, String message) { if (!account.equals(mAccount)) { return; } mHandler.progress(false); if (Config.LOGV) { Log.v(K9.LOG_TAG, "listFoldersFailed " + message); } } @Override public void listFoldersFinished(Account account) { if (!account.equals(mAccount)) { return; } mHandler.progress(false); MessagingController.getInstance(getApplication()).refreshListener(mAdapter.mListener); mHandler.dataChanged(); } @Override public void listFolders(Account account, Folder[] folders) { if (!account.equals(mAccount)) { return; } List<FolderInfoHolder> newFolders = new LinkedList<FolderInfoHolder>(); List<FolderInfoHolder> topFolders = new LinkedList<FolderInfoHolder>(); Account.FolderMode aMode = account.getFolderDisplayMode(); Preferences prefs = Preferences.getPreferences(getApplication().getApplicationContext()); for (Folder folder : folders) { try { folder.refresh(prefs); Folder.FolderClass fMode = folder.getDisplayClass(); if ((aMode == Account.FolderMode.FIRST_CLASS && fMode != Folder.FolderClass.FIRST_CLASS) || (aMode == Account.FolderMode.FIRST_AND_SECOND_CLASS && fMode != Folder.FolderClass.FIRST_CLASS && fMode != Folder.FolderClass.SECOND_CLASS) || (aMode == Account.FolderMode.NOT_SECOND_CLASS && fMode == Folder.FolderClass.SECOND_CLASS)) { continue; } } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Couldn't get prefs to check for displayability of folder " + folder.getName(), me); } FolderInfoHolder holder = null; int folderIndex = getFolderIndex(folder.getName()); if (folderIndex >= 0) { holder = (FolderInfoHolder) getItem(folderIndex); } int unreadMessageCount = 0; try { unreadMessageCount = folder.getUnreadMessageCount(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to get unreadMessageCount for " + mAccount.getDescription() + ":" + folder.getName()); } if (holder == null) { holder = new FolderInfoHolder(folder, unreadMessageCount); } else { holder.populate(folder, unreadMessageCount); } if (folder.isInTopGroup()) { topFolders.add(holder); } else { newFolders.add(holder); } } Collections.sort(newFolders); Collections.sort(topFolders); topFolders.addAll(newFolders); mHandler.newFolders(topFolders); mHandler.refreshTitle(); } @Override public void synchronizeMailboxStarted(Account account, String folder) { super.synchronizeMailboxStarted(account, folder); mHandler.refreshTitle(); if (!account.equals(mAccount)) { return; } mHandler.progress(true); mHandler.folderLoading(folder, true); mHandler.dataChanged(); } @Override public void synchronizeMailboxProgress(Account account, String folder, int completed, int total) { super.synchronizeMailboxProgress(account, folder, completed, total); mHandler.refreshTitle(); } @Override public void synchronizeMailboxFinished(Account account, String folder, int totalMessagesInMailbox, int numNewMessages) { super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages); mHandler.refreshTitle(); if (!account.equals(mAccount)) { return; } mHandler.progress(false); mHandler.folderLoading(folder, false); refreshFolder(account, folder); } private void refreshFolder(Account account, String folderName) { // There has to be a cheaper way to get at the localFolder object than this Folder localFolder = null; try { if (account != null && folderName != null) { localFolder = account.getLocalStore().getFolder(folderName); int unreadMessageCount = localFolder.getUnreadMessageCount(); if (localFolder != null) { FolderInfoHolder folderHolder = getFolder(folderName); if (folderHolder != null) { folderHolder.populate(localFolder, unreadMessageCount); mHandler.dataChanged(); } } } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while populating folder", e); } finally { if (localFolder != null) { localFolder.close(); } } } @Override public void synchronizeMailboxFailed(Account account, String folder, String message) { super.synchronizeMailboxFailed(account, folder, message); mHandler.refreshTitle(); if (!account.equals(mAccount)) { return; } mHandler.progress(false); mHandler.folderLoading(folder, false); // String mess = truncateStatus(message); // mHandler.folderStatus(folder, mess); FolderInfoHolder holder = getFolder(folder); if (holder != null) { holder.lastChecked = 0; } mHandler.dataChanged(); } @Override public void setPushActive(Account account, String folderName, boolean enabled) { if (!account.equals(mAccount)) { return; } FolderInfoHolder holder = getFolder(folderName); if (holder != null) { holder.pushActive = enabled; mHandler.dataChanged(); } } @Override public void messageDeleted(Account account, String folder, Message message) { synchronizeMailboxRemovedMessage(account, folder, message); } @Override public void emptyTrashCompleted(Account account) { if (!account.equals(mAccount)) { return; } refreshFolder(account, mAccount.getTrashFolderName()); } @Override public void folderStatusChanged(Account account, String folderName, int unreadMessageCount) { if (!account.equals(mAccount)) { return; } refreshFolder(account, folderName); } @Override public void sendPendingMessagesCompleted(Account account) { super.sendPendingMessagesCompleted(account); mHandler.refreshTitle(); if (!account.equals(mAccount)) { return; } refreshFolder(account, mAccount.getOutboxFolderName()); } @Override public void sendPendingMessagesStarted(Account account) { super.sendPendingMessagesStarted(account); mHandler.refreshTitle(); if (!account.equals(mAccount)) { return; } mHandler.dataChanged(); } @Override public void sendPendingMessagesFailed(Account account) { super.sendPendingMessagesFailed(account); mHandler.refreshTitle(); if (!account.equals(mAccount)) { return; } refreshFolder(account, mAccount.getOutboxFolderName()); } @Override public void accountSizeChanged(Account account, long oldSize, long newSize) { if (!account.equals(mAccount)) { return; } mHandler.accountSizeChanged(oldSize, newSize); } @Override public void pendingCommandsProcessing(Account account) { super.pendingCommandsProcessing(account); mHandler.refreshTitle(); } @Override public void pendingCommandsFinished(Account account) { super.pendingCommandsFinished(account); mHandler.refreshTitle(); } @Override public void pendingCommandStarted(Account account, String commandTitle) { super.pendingCommandStarted(account, commandTitle); mHandler.refreshTitle(); } @Override public void pendingCommandCompleted(Account account, String commandTitle) { super.pendingCommandCompleted(account, commandTitle); mHandler.refreshTitle(); } }; public int getFolderIndex(String folder) { FolderInfoHolder searchHolder = new FolderInfoHolder(); searchHolder.name = folder; return mFolders.indexOf((Object) searchHolder); } public FolderInfoHolder getFolder(String folder) { FolderInfoHolder holder = null; int index = getFolderIndex(folder); if (index >= 0) { holder = (FolderInfoHolder) getItem(index); if (holder != null) { return holder; } } return null; } public View getView(int position, View convertView, ViewGroup parent) { if (position <= getCount()) { return getItemView(position, convertView, parent); } else { // XXX TODO - should catch an exception here return null; } } public View getItemView(int itemPosition, View convertView, ViewGroup parent) { FolderInfoHolder folder = (FolderInfoHolder) getItem(itemPosition); View view; if ((convertView != null) && (convertView.getId() == R.layout.folder_list_item)) { view = convertView; } else { view = mInflater.inflate(R.layout.folder_list_item, parent, false); view.setId(R.layout.folder_list_item); } FolderViewHolder holder = (FolderViewHolder) view.getTag(); if (holder == null) { holder = new FolderViewHolder(); holder.folderName = (TextView) view.findViewById(R.id.folder_name); holder.newMessageCount = (TextView) view.findViewById(R.id.folder_unread_message_count); holder.flaggedMessageCount = (TextView) view.findViewById(R.id.folder_flagged_message_count); holder.folderStatus = (TextView) view.findViewById(R.id.folder_status); holder.activeIcons = (RelativeLayout) view.findViewById(R.id.active_icons); holder.chip = view.findViewById(R.id.chip); holder.rawFolderName = folder.name; view.setTag(holder); } if (folder == null) { return view; } holder.folderName.setText(folder.displayName); String statusText = ""; if (folder.loading) { statusText = getString(R.string.status_loading); } else if (folder.status != null) { statusText = folder.status; } else if (folder.lastChecked != 0) { Date lastCheckedDate = new Date(folder.lastChecked); statusText = getTimeFormat().format(lastCheckedDate) + " "+ getDateFormat().format(lastCheckedDate); } if (folder.pushActive) { statusText = getString(R.string.folder_push_active_symbol) + " "+ statusText; } if (statusText != null) { holder.folderStatus.setText(statusText); holder.folderStatus.setVisibility(View.VISIBLE); } else { holder.folderStatus.setText(null); holder.folderStatus.setVisibility(View.GONE); } if (folder.unreadMessageCount != 0) { holder.newMessageCount.setText(Integer .toString(folder.unreadMessageCount)); holder.newMessageCount.setOnClickListener(new FolderClickListener(mAccount, folder.name, folder.displayName, SearchModifier.UNREAD)); holder.newMessageCount.setVisibility(View.VISIBLE); } else { holder.newMessageCount.setVisibility(View.GONE); } if (K9.messageListStars() && folder.flaggedMessageCount > 0) { holder.flaggedMessageCount.setText(Integer .toString(folder.flaggedMessageCount)); holder.flaggedMessageCount.setOnClickListener(new FolderClickListener(mAccount, folder.name, folder.displayName, SearchModifier.FLAGGED)); holder.flaggedMessageCount.setVisibility(View.VISIBLE); } else { holder.flaggedMessageCount.setVisibility(View.GONE); } holder.activeIcons.setOnClickListener(new OnClickListener() { public void onClick(View v) { Toast toast = Toast.makeText(getApplication(), getString(R.string.tap_hint), Toast.LENGTH_SHORT); toast.show(); } } ); holder.chip.setBackgroundResource(K9.COLOR_CHIP_RES_IDS[mAccount.getAccountNumber() % K9.COLOR_CHIP_RES_IDS.length]); holder.chip.getBackground().setAlpha(folder.unreadMessageCount == 0 ? 127 : 255); holder.folderName.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getFolderName()); holder.folderStatus.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mFontSizes.getFolderStatus()); return view; } @Override public boolean hasStableIds() { return false; } public boolean isItemSelectable(int position) { return true; } } public class FolderInfoHolder implements Comparable<FolderInfoHolder> { public String name; public String displayName; public long lastChecked; public int unreadMessageCount; public int flaggedMessageCount; public boolean loading; public String status; public boolean pushActive; public boolean lastCheckFailed; /** * Outbox is handled differently from any other folder. */ public boolean outbox; @Override public boolean equals(Object o) { return this.name.equals(((FolderInfoHolder)o).name); } @Override public int hashCode() { return name.hashCode(); } public int compareTo(FolderInfoHolder o) { String s1 = this.name; String s2 = o.name; int ret = s1.compareToIgnoreCase(s2); if (ret != 0) { return ret; } else { return s1.compareTo(s2); } } // constructor for an empty object for comparisons public FolderInfoHolder() { } public FolderInfoHolder(Folder folder, int unreadCount) { populate(folder, unreadCount); } public void populate(Folder folder, int unreadCount) { try { folder.open(Folder.OpenMode.READ_WRITE); // unreadCount = folder.getUnreadMessageCount(); } catch (MessagingException me) { Log.e(K9.LOG_TAG, "Folder.getUnreadMessageCount() failed", me); } this.name = folder.getName(); if (this.name.equalsIgnoreCase(K9.INBOX)) { this.displayName = getString(R.string.special_mailbox_name_inbox); } else { this.displayName = folder.getName(); } if (this.name.equals(mAccount.getOutboxFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_outbox_fmt), this.name); this.outbox = true; } if (this.name.equals(mAccount.getDraftsFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_drafts_fmt), this.name); } if (this.name.equals(mAccount.getTrashFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_trash_fmt), this.name); } if (this.name.equals(mAccount.getSentFolderName())) { this.displayName = String.format(getString(R.string.special_mailbox_name_sent_fmt), this.name); } this.lastChecked = folder.getLastUpdate(); String mess = truncateStatus(folder.getStatus()); this.status = mess; this.unreadMessageCount = unreadCount; try { this.flaggedMessageCount = folder.getFlaggedMessageCount(); } catch (Exception e) { Log.e(K9.LOG_TAG, "Unable to get flaggedMessageCount", e); } folder.close(); } } class FolderViewHolder { public TextView folderName; public TextView folderStatus; public TextView newMessageCount; public TextView flaggedMessageCount; public RelativeLayout activeIcons; public String rawFolderName; public View chip; } private class FolderClickListener implements OnClickListener { final BaseAccount account; final String folderName; final String displayName; final SearchModifier searchModifier; FolderClickListener(BaseAccount nAccount, String folderName, String displayName, SearchModifier nSearchModifier ) { account = nAccount; this.folderName = folderName; searchModifier = nSearchModifier; this.displayName = displayName; } @Override public void onClick(View v) { String description = getString(R.string.search_title, getString(R.string.message_list_title, account.getDescription(), displayName), getString(searchModifier.resId)); SearchSpecification searchSpec = new SearchSpecification() { @Override public String[] getAccountUuids() { return new String[] { account.getUuid() }; } @Override public Flag[] getForbiddenFlags() { return searchModifier.forbiddenFlags; } @Override public String getQuery() { return ""; } @Override public Flag[] getRequiredFlags() { return searchModifier.requiredFlags; } @Override public boolean isIntegrate() { return false; } @Override public String[] getFolderNames() { return new String[] { folderName }; } }; MessageList.actionHandle(FolderList.this, description, searchSpec); } } }
package com.fsck.k9.service; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.os.IBinder; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Config; import android.util.Log; import com.fsck.k9.*; import com.fsck.k9.mail.Pusher; import java.util.Collection; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MailService extends CoreService { private static final String ACTION_CHECK_MAIL = "com.fsck.k9.intent.action.MAIL_SERVICE_WAKEUP"; private static final String ACTION_RESCHEDULE = "com.fsck.k9.intent.action.MAIL_SERVICE_RESCHEDULE"; private static final String ACTION_RESCHEDULE_CHECK = "com.fsck.k9.intent.action.MAIL_SERVICE_RESCHEDULE_CHECK"; private static final String ACTION_CANCEL = "com.fsck.k9.intent.action.MAIL_SERVICE_CANCEL"; private static final String ACTION_REFRESH_PUSHERS = "com.fsck.k9.intent.action.MAIL_SERVICE_REFRESH_PUSHERS"; private static final String CONNECTIVITY_CHANGE = "com.fsck.k9.intent.action.MAIL_SERVICE_CONNECTIVITY_CHANGE"; private static final String BACKGROUND_DATA_CHANGED = "com.fsck.k9.intent.action.MAIL_SERVICE_BACKGROUND_DATA_CHANGED"; private static final String CANCEL_CONNECTIVITY_NOTICE = "com.fsck.k9.intent.action.MAIL_SERVICE_CANCEL_CONNECTIVITY_NOTICE"; private static final String HAS_CONNECTIVITY = "com.fsck.k9.intent.action.MAIL_SERVICE_HAS_CONNECTIVITY"; private final ExecutorService threadPool = Executors.newFixedThreadPool(1); // Must be single threaded public static void actionReschedule(Context context, Integer wakeLockId) { Intent i = new Intent(); i.setClass(context, MailService.class); i.setAction(MailService.ACTION_RESCHEDULE); addWakeLockId(i, wakeLockId); context.startService(i); } public static void rescheduleCheck(Context context, Integer wakeLockId) { Intent i = new Intent(); i.setClass(context, MailService.class); i.setAction(MailService.ACTION_RESCHEDULE_CHECK); addWakeLockId(i, wakeLockId); context.startService(i); } public static void actionCancel(Context context, Integer wakeLockId) { Intent i = new Intent(); i.setClass(context, MailService.class); i.setAction(MailService.ACTION_CANCEL); addWakeLockId(i, wakeLockId); context.startService(i); } public static void connectivityChange(Context context, boolean hasConnectivity, Integer wakeLockId) { Intent i = new Intent(); i.setClass(context, MailService.class); i.setAction(MailService.CONNECTIVITY_CHANGE); i.putExtra(HAS_CONNECTIVITY, hasConnectivity); addWakeLockId(i, wakeLockId); context.startService(i); } public static void backgroundDataChanged(Context context, Integer wakeLockId) { Intent i = new Intent(); i.setClass(context, MailService.class); i.setAction(MailService.BACKGROUND_DATA_CHANGED); addWakeLockId(i, wakeLockId); context.startService(i); } @Override public void onCreate() { super.onCreate(); if (K9.DEBUG) Log.v(K9.LOG_TAG, "***** MailService *****: onCreate"); } @Override public void startService(Intent intent, int startId) { Integer startIdObj = startId; long startTime = System.currentTimeMillis(); try { ConnectivityManager connectivityManager = (ConnectivityManager)getApplication().getSystemService(Context.CONNECTIVITY_SERVICE); boolean doBackground = true; boolean hasConnectivity = false; if (connectivityManager != null) { NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); if (netInfo != null) { State state = netInfo.getState(); hasConnectivity = state == State.CONNECTED; } boolean backgroundData = connectivityManager.getBackgroundDataSetting(); K9.BACKGROUND_OPS bOps = K9.getBackgroundOps(); doBackground = (backgroundData == true && bOps != K9.BACKGROUND_OPS.NEVER) | (backgroundData == false && bOps == K9.BACKGROUND_OPS.ALWAYS); } setForeground(true); // if it gets killed once, it'll never restart if (K9.DEBUG) Log.i(K9.LOG_TAG, "MailService.onStart(" + intent + ", " + startId + "), hasConnectivity = " + hasConnectivity + ", doBackground = " + doBackground); // MessagingController.getInstance(getApplication()).addListener(mListener); if (ACTION_CHECK_MAIL.equals(intent.getAction())) { if (K9.DEBUG) Log.i(K9.LOG_TAG, "***** MailService *****: checking mail"); if (hasConnectivity && doBackground) { PollService.startService(this); } reschedule(startIdObj); startIdObj = null; } else if (ACTION_CANCEL.equals(intent.getAction())) { if (Config.LOGV) { Log.v(K9.LOG_TAG, "***** MailService *****: cancel"); } cancel(); } else if (ACTION_RESCHEDULE.equals(intent.getAction())) { if (Config.LOGV) { Log.v(K9.LOG_TAG, "***** MailService *****: reschedule"); } rescheduleAll(hasConnectivity, doBackground, startIdObj); startIdObj = null; } else if (ACTION_RESCHEDULE_CHECK.equals(intent.getAction())) { if (Config.LOGV) { Log.v(K9.LOG_TAG, "***** MailService *****: reschedule check"); } reschedule(startIdObj); startIdObj = null; } else if (ACTION_REFRESH_PUSHERS.equals(intent.getAction())) { if (hasConnectivity && doBackground) { schedulePushers(null); refreshPushers(startIdObj); startIdObj = null; } } else if (CONNECTIVITY_CHANGE.equals(intent.getAction()) || BACKGROUND_DATA_CHANGED.equals(intent.getAction())) { notifyConnectionStatus(hasConnectivity); rescheduleAll(hasConnectivity, doBackground, startIdObj); startIdObj = null; if (K9.DEBUG) Log.i(K9.LOG_TAG, "Got connectivity action with hasConnectivity = " + hasConnectivity + ", doBackground = " + doBackground); } else if (CANCEL_CONNECTIVITY_NOTICE.equals(intent.getAction())) { notifyConnectionStatus(true); } } finally { if (startIdObj != null) { stopSelf(startId); } } if (K9.DEBUG) Log.i(K9.LOG_TAG, "MailService.onStart took " + (System.currentTimeMillis() - startTime) + "ms"); } private void rescheduleAll(final boolean hasConnectivity, final boolean doBackground, final Integer startId) { if (hasConnectivity && doBackground) { reschedule(null); reschedulePushers(startId); } else { stopPushers(startId); } } private void notifyConnectionStatus(boolean hasConnectivity) { if (true) return; NotificationManager notifMgr = (NotificationManager)getApplication().getSystemService(Context.NOTIFICATION_SERVICE); if (hasConnectivity == false) { String notice = getApplication().getString(R.string.no_connection_alert); String header = getApplication().getString(R.string.alert_header); Notification notif = new Notification(R.drawable.stat_notify_email_generic, header, System.currentTimeMillis()); Intent i = new Intent(); i.setClassName(getApplication().getPackageName(), "com.fsck.k9.service.MailService"); i.setAction(MailService.CANCEL_CONNECTIVITY_NOTICE); PendingIntent pi = PendingIntent.getService(this, 0, i, 0); notif.setLatestEventInfo(getApplication(), header, notice, pi); notif.flags = Notification.FLAG_ONGOING_EVENT; notifMgr.notify(K9.CONNECTIVITY_ID, notif); } else { notifMgr.cancel(K9.CONNECTIVITY_ID); } } @Override public void onDestroy() { if (K9.DEBUG) Log.v(K9.LOG_TAG, "***** MailService *****: onDestroy()"); super.onDestroy(); // MessagingController.getInstance(getApplication()).removeListener(mListener); } private void cancel() { Intent i = new Intent(); i.setClassName(getApplication().getPackageName(), "com.fsck.k9.service.MailService"); i.setAction(ACTION_CHECK_MAIL); BootReceiver.cancelIntent(this, i); } private void reschedule(Integer startId) { execute(getApplication(), new Runnable() { public void run() { int shortestInterval = -1; for (Account account : Preferences.getPreferences(MailService.this).getAccounts()) { if (account.getAutomaticCheckIntervalMinutes() != -1 && (account.getAutomaticCheckIntervalMinutes() < shortestInterval || shortestInterval == -1)) { shortestInterval = account.getAutomaticCheckIntervalMinutes(); } } if (shortestInterval == -1) { if (K9.DEBUG) Log.v(K9.LOG_TAG, "No next check scheduled for package " + getApplication().getPackageName()); cancel(); } else { long delay = (shortestInterval * (60 * 1000)); long nextTime = System.currentTimeMillis() + delay; if (K9.DEBUG) { try { Log.i(K9.LOG_TAG, "Next check for package " + getApplication().getPackageName() + " scheduled for " + new Date(nextTime)); } catch (Exception e) { // I once got a NullPointerException deep in new Date(); Log.e(K9.LOG_TAG, "Exception while logging", e); } } Intent i = new Intent(); i.setClassName(getApplication().getPackageName(), "com.fsck.k9.service.MailService"); i.setAction(ACTION_CHECK_MAIL); BootReceiver.scheduleIntent(MailService.this, nextTime, i); } } } , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, startId); } private void stopPushers(final Integer startId) { execute(getApplication(), new Runnable() { public void run() { MessagingController.getInstance(getApplication()).stopAllPushing(); PushService.stopService(MailService.this); } } , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, startId); } private void reschedulePushers(final Integer startId) { execute(getApplication(), new Runnable() { public void run() { Log.i(K9.LOG_TAG, "Rescheduling pushers"); stopPushers(null); setupPushers(null); schedulePushers(startId); } } , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, null); } private void setupPushers(final Integer startId) { execute(getApplication(), new Runnable() { public void run() { boolean pushing = false; for (Account account : Preferences.getPreferences(MailService.this).getAccounts()) { Log.i(K9.LOG_TAG, "Setting up pushers for account " + account.getDescription()); pushing |= MessagingController.getInstance(getApplication()).setupPushing(account); } if (pushing) { PushService.startService(MailService.this); } } } , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, startId); } private void refreshPushers(final Integer startId) { execute(getApplication(), new Runnable() { public void run() { try { Log.i(K9.LOG_TAG, "Refreshing pushers"); Collection<Pusher> pushers = MessagingController.getInstance(getApplication()).getPushers(); for (Pusher pusher : pushers) { pusher.refresh(); } } catch (Exception e) { Log.e(K9.LOG_TAG, "Exception while refreshing pushers", e); } } } , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, startId); } private void schedulePushers(final Integer startId) { execute(getApplication(), new Runnable() { public void run() { int minInterval = -1; Collection<Pusher> pushers = MessagingController.getInstance(getApplication()).getPushers(); for (Pusher pusher : pushers) { int interval = pusher.getRefreshInterval(); if (interval != -1 && (interval < minInterval || minInterval == -1)) { minInterval = interval; } } if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Pusher refresh interval = " + minInterval); } if (minInterval != -1) { long nextTime = System.currentTimeMillis() + minInterval; if (K9.DEBUG) { Log.d(K9.LOG_TAG, "Next pusher refresh scheduled for " + new Date(nextTime)); } Intent i = new Intent(); i.setClassName(getApplication().getPackageName(), "com.fsck.k9.service.MailService"); i.setAction(ACTION_REFRESH_PUSHERS); BootReceiver.scheduleIntent(MailService.this, nextTime, i); } } } , K9.MAIL_SERVICE_WAKE_LOCK_TIMEOUT, startId); } public void execute(Context context, final Runnable runner, int wakeLockTime, final Integer startId) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); final WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "K9"); wakeLock.setReferenceCounted(false); wakeLock.acquire(wakeLockTime); if (K9.DEBUG) Log.i(K9.LOG_TAG, "MailService queueing Runnable " + runner.hashCode() + " with startId " + startId); Runnable myRunner = new Runnable() { public void run() { try { if (K9.DEBUG) Log.i(K9.LOG_TAG, "MailService running Runnable " + runner.hashCode() + " with startId " + startId); runner.run(); } finally { if (K9.DEBUG) Log.i(K9.LOG_TAG, "MailService completed Runnable " + runner.hashCode() + " with startId " + startId); wakeLock.release(); if (startId != null) { stopSelf(startId); } } } }; threadPool.execute(myRunner); } public IBinder onBind(Intent intent) { return null; } }
package com.googlecode.ant_deb_task; import org.apache.tools.ant.*; import org.apache.tools.ant.taskdefs.Tar; import org.apache.tools.ant.types.*; import java.io.*; import java.util.*; import java.util.regex.*; import java.security.MessageDigest; /** * Task that creates a Debian package. * * @antTaskName deb */ public class Deb extends Task { private static final Pattern PACKAGE_NAME_PATTERN = Pattern.compile("[a-z0-9][a-z0-9+\\-.]+"); public static class Description extends ProjectComponent { private String _synopsis; private String _extended = ""; public String getSynopsis () { return _synopsis; } public void setSynopsis (String synopsis) { _synopsis = synopsis.trim (); } public void addText (String text) { _extended += getProject ().replaceProperties (text); } public String getExtended () { return _extended; } public String getExtendedFormatted () { StringBuffer buffer = new StringBuffer (_extended.length ()); String lines[] = _extended.split ("\n"); int start = 0; for (int i = 0; i < lines.length; i++) { String line = lines[i].trim (); if (line.length () > 0) break; start++; } int end = lines.length; for (int i = lines.length - 1; i >= 0; i { String line = lines[i].trim (); if (line.length () > 0) break; end } for (int i = start; i < end; i++) { String line = lines[i].trim (); buffer.append (' '); buffer.append (line.length () == 0 ? "." : line); buffer.append ('\n'); } buffer.deleteCharAt (buffer.length () - 1); return buffer.toString (); } } public static class Version extends ProjectComponent { private static final Pattern UPSTREAM_VERSION_PATTERN = Pattern.compile("[0-9][A-Za-z0-9+\\-.:]*"); private static final Pattern DEBIAN_VERSION_PATTERN = Pattern.compile("[A-Za-z0-9+\\-]+"); private int _epoch = 0; private String _upstream; private String _debian = "1"; public void setEpoch(int epoch) { _epoch = epoch; } public void setUpstream(String upstream) { _upstream = upstream.trim (); if (!UPSTREAM_VERSION_PATTERN.matcher (_upstream).matches ()) throw new BuildException("Invalid upstream version number!"); } public void setDebian(String debian) { _debian = debian.trim (); if (!DEBIAN_VERSION_PATTERN.matcher (_debian).matches ()) throw new BuildException("Invalid debian version number!"); } public String toString() { StringBuffer version = new StringBuffer(); if (_epoch > 0) { version.append(_epoch); version.append(':'); } else if (_upstream.indexOf(':') > -1) throw new BuildException("Upstream version can contain colons only if epoch is specified!"); version.append(_upstream); if (_debian.length() > 0) { version.append('-'); version.append(_debian); } else if (_upstream.indexOf('-') > -1) throw new BuildException("Upstream version can contain hyphens only if debian version is specified!"); return version.toString(); } } public static class Maintainer extends ProjectComponent { private String _name; private String _email; public void setName (String name) { _name = name.trim (); } public void setEmail (String email) { _email = email.trim (); } public String toString() { if (_name == null || _name.length () == 0) return _email; StringBuffer buffer = new StringBuffer (_name); buffer.append (" <"); buffer.append (_email); buffer.append (">"); return buffer.toString (); } } public static class Section extends EnumeratedAttribute { private static final String[] PREFIXES = new String[] {"", "contrib/", "non-free/"}; private static final String[] BASIC_SECTIONS = new String[] {"admin", "base", "comm", "devel", "doc", "editors", "electronics", "embedded", "games", "gnome", "graphics", "hamradio", "interpreters", "kde", "libs", "libdevel", "mail", "math", "misc", "net", "news", "oldlibs", "otherosfs", "perl", "python", "science", "shells", "sound", "tex", "text", "utils", "web", "x11"}; private List sections = new ArrayList (PREFIXES.length * BASIC_SECTIONS.length); public Section () { for (int i = 0; i < PREFIXES.length; i++) { String prefix = PREFIXES[i]; for (int j = 0; j < BASIC_SECTIONS.length; j++) { String basicSection = BASIC_SECTIONS[j]; sections.add (prefix + basicSection); } } } public String[] getValues () { return (String[]) sections.toArray (new String[]{}); } } public static class Priority extends EnumeratedAttribute { public String[] getValues () { return new String[] {"required", "important", "standard", "optional", "extra"}; } } private File _toDir; private String _package; private String _version; private Deb.Version _versionObj; private String _section; private String _priority = "extra"; private String _architecture = "all"; private String _depends; private String _preDepends; private String _recommends; private String _suggests; private String _enhances; private String _conflicts; private String _maintainer; private Deb.Maintainer _maintainerObj; private Deb.Description _description; private Set _conffiles = new HashSet (); private List _data = new ArrayList(); private File _preinst; private File _postinst; private File _prerm; private File _postrm; private File _config; private File _templates; private File _tempFolder; private long _installedSize = 0; private SortedSet _dataFolders; private static final Tar.TarCompressionMethod GZIP_COMPRESSION_METHOD = new Tar.TarCompressionMethod (); private static final Tar.TarLongFileMode GNU_LONGFILE_MODE = new Tar.TarLongFileMode (); static { GZIP_COMPRESSION_METHOD.setValue ("gzip"); GNU_LONGFILE_MODE.setValue(Tar.TarLongFileMode.GNU); } public void setToDir (File toDir) { _toDir = toDir; } public void setPackage (String packageName) { if (!PACKAGE_NAME_PATTERN.matcher(packageName).matches()) throw new BuildException("Invalid package name!"); _package = packageName; } public void setVersion (String version) { _version = version; } public void setSection (Section section) { _section = section.getValue(); } public void setPriority (Priority priority) { _priority = priority.getValue(); } public void setArchitecture (String architecture) { _architecture = architecture; } public void setDepends (String depends) { _depends = depends; } public void setPreDepends (String preDepends) { _preDepends = preDepends; } public void setRecommends (String recommends) { _recommends = recommends; } public void setSuggests (String suggests) { _suggests = suggests; } public void setEnhances (String enhances) { _enhances = enhances; } public void setConflicts (String conflicts) { _conflicts = conflicts; } public void setMaintainer (String maintainer) { _maintainer = maintainer; } public void setPreinst (File preinst) { _preinst = preinst; } public void setPostinst (File postinst) { _postinst = postinst; } public void setPrerm (File prerm) { _prerm = prerm; } public void setPostrm (File postrm) { _postrm = postrm; } public void setConfig (File config) { _config = config; } public void setTemplates (File templates) { _templates = templates; } public void addConfFiles (TarFileSet conffiles) { _conffiles.add (conffiles); _data.add (conffiles); } public void addDescription (Deb.Description description) { _description = description; } public void add (TarFileSet resourceCollection) { _data.add(resourceCollection); } public void addVersion(Deb.Version version) { _versionObj = version; } public void addMaintainer(Deb.Maintainer maintainer) { _maintainerObj = maintainer; } private void writeControlFile (File controlFile, long installedSize) throws FileNotFoundException { log ("Generating control file to: " + controlFile.getAbsolutePath (), Project.MSG_VERBOSE); PrintWriter control = new UnixPrintWriter (controlFile); control.print ("Package: "); control.println (_package); control.print ("Version: "); control.println (_version); if (_section != null) { control.print ("Section: "); control.println (_section); } if (_priority != null) { control.print ("Priority: "); control.println (_priority); } control.print ("Architecture: "); control.println (_architecture); if (_depends != null) { control.print ("Depends: "); control.println (_depends); } if (_preDepends != null) { control.print ("Pre-Depends: "); control.println (_preDepends); } if (_recommends != null) { control.print ("Recommends: "); control.println (_recommends); } if (_suggests != null) { control.print ("Suggests: "); control.println (_suggests); } if (_enhances != null) { control.print ("Enhances: "); control.println (_enhances); } if (_conflicts != null) { control.print ("Conflicts: "); control.println (_conflicts); } if (installedSize > 0) { control.print ("Installed-Size: "); control.println (installedSize / 1024L); } control.print ("Maintainer: "); control.println (_maintainer); control.print ("Description: "); control.println (_description.getSynopsis ()); control.println (_description.getExtendedFormatted ()); control.close (); } private File createMasterControlFile () throws IOException { File controlFile = new File (_tempFolder, "control"); writeControlFile (controlFile, _installedSize); File md5sumsFile = new File (_tempFolder, "md5sums"); File conffilesFile = new File (_tempFolder, "conffiles"); File masterControlFile = new File (_tempFolder, "control.tar.gz"); Tar controlTar = new Tar (); controlTar.setProject (getProject ()); controlTar.setTaskName (getTaskName ()); controlTar.setDestFile (masterControlFile); controlTar.setCompression (GZIP_COMPRESSION_METHOD); addFileToTar (controlTar, controlFile, "control", "644"); addFileToTar (controlTar, md5sumsFile, "md5sums", "644"); if (conffilesFile.length () > 0) addFileToTar (controlTar, conffilesFile, "conffiles", "644"); if (_preinst != null) addFileToTar (controlTar, _preinst, "preinst", "755"); if (_postinst != null) addFileToTar (controlTar, _postinst, "postinst", "755"); if (_prerm != null) addFileToTar (controlTar, _prerm, "prerm", "755"); if (_postrm != null) addFileToTar (controlTar, _postrm, "postrm", "755"); if (_config != null) addFileToTar (controlTar, _config, "config", "755"); if (_templates != null) addFileToTar (controlTar, _templates, "templates", "644"); controlTar.perform (); controlFile.delete (); return masterControlFile; } private void addFileToTar(Tar tar, File file, String fullpath, String fileMode) { TarFileSet controlFileSet = tar.createTarFileSet (); controlFileSet.setFile (file); controlFileSet.setFullpath (fullpath); controlFileSet.setFileMode (fileMode); } public void execute () throws BuildException { try { if (_versionObj != null) _version = _versionObj.toString (); if (_maintainerObj != null) _maintainer = _maintainerObj.toString (); _tempFolder = createTempFolder(); scanData (); File debFile = new File (_toDir, _package + "_" + _version + "_" + _architecture + ".deb"); File dataFile = createDataFile (); File masterControlFile = createMasterControlFile (); log ("Writing deb file to: " + debFile.getAbsolutePath()); BuildDeb.buildDeb (debFile, masterControlFile, dataFile); masterControlFile.delete (); dataFile.delete (); } catch (IOException e) { throw new BuildException (e); } } private File createDataFile () throws IOException { File dataFile = new File (_tempFolder, "data.tar.gz"); Tar dataTar = new Tar (); dataTar.setProject (getProject ()); dataTar.setTaskName (getTaskName ()); dataTar.setDestFile (dataFile); dataTar.setCompression (GZIP_COMPRESSION_METHOD); dataTar.setLongfile(GNU_LONGFILE_MODE); // add folders for (Iterator dataFoldersIter = _dataFolders.iterator (); dataFoldersIter.hasNext ();) { String targetFolder = (String) dataFoldersIter.next (); TarFileSet targetFolderSet = dataTar.createTarFileSet (); targetFolderSet.setFile (_tempFolder); targetFolderSet.setFullpath (targetFolder); } // add actual data for (int i = 0; i < _data.size (); i++) dataTar.add ((TarFileSet) _data.get (i)); dataTar.execute (); return dataFile; } private File createTempFolder() throws IOException { File tempFile = File.createTempFile ("deb", ".dir"); String tempFolderName = tempFile.getAbsolutePath (); tempFile.delete (); tempFile = new File (tempFolderName, "removeme"); tempFile.mkdirs (); tempFile.delete (); log ("Temp folder: " + tempFolderName, Project.MSG_VERBOSE); return new File (tempFolderName); } private void scanData() { try { Set existingDirs = new HashSet (); _installedSize = 0; PrintWriter md5sums = new UnixPrintWriter (new File (_tempFolder, "md5sums")); PrintWriter conffiles = new UnixPrintWriter (new File (_tempFolder, "conffiles")); _dataFolders = new TreeSet (); Iterator filesets = _data.iterator(); while (filesets.hasNext()) { TarFileSet fileset = (TarFileSet) filesets.next(); String fullPath = fileset.getFullpath (getProject ()); String prefix = fileset.getPrefix (getProject ()); if (prefix.length () > 0 && !prefix.endsWith ("/")) prefix += '/'; String [] fileNames = getFileNames(fileset); for (int i = 0; i < fileNames.length; i++) { String targetName; String fileName = fileNames[i]; File file = new File (fileset.getDir (getProject ()), fileName); if (fullPath.length () > 0) targetName = fullPath; else targetName = prefix + fileName; if (file.isDirectory ()) { log ("existing dir: " + targetName, Project.MSG_DEBUG); existingDirs.add (targetName); } else { // calculate installed size in bytes _installedSize += file.length (); // calculate and collect md5 sums md5sums.print (getFileMd5 (file)); md5sums.print (' '); md5sums.println (targetName.replace (File.separatorChar, '/')); // get target folder names, and collect them (to be added to _data) File targetFile = new File(targetName); File parentFolder = targetFile.getParentFile () ; while (parentFolder != null) { String parentFolderPath = parentFolder.getPath (); if (!existingDirs.contains (parentFolderPath) && !_dataFolders.contains (parentFolderPath)) { log ("adding dir: " + parentFolderPath + " for " + targetName, Project.MSG_DEBUG); _dataFolders.add (parentFolderPath); } parentFolder = parentFolder.getParentFile (); } // write conffiles if (_conffiles.contains (fileset)) conffiles.println (targetName); } } } for (Iterator iterator = existingDirs.iterator (); iterator.hasNext ();) { String existingDir = (String) iterator.next (); if (_dataFolders.contains (existingDir)) { log ("removing existing dir " + existingDir, Project.MSG_DEBUG); _dataFolders.remove (existingDir); } } md5sums.close (); conffiles.close (); } catch (Exception e) { throw new BuildException (e); } } private String[] getFileNames(FileSet fs) { DirectoryScanner ds = fs.getDirectoryScanner(fs.getProject()); String[] directories = ds.getIncludedDirectories(); String[] filesPerSe = ds.getIncludedFiles(); String[] files = new String [directories.length + filesPerSe.length]; System.arraycopy(directories, 0, files, 0, directories.length); System.arraycopy(filesPerSe, 0, files, directories.length, filesPerSe.length); return files; } private String getFileMd5(File file) { try { MessageDigest md5 = MessageDigest.getInstance ("MD5"); FileInputStream inputStream = new FileInputStream (file); byte[] buffer = new byte[1024]; while (true) { int read = inputStream.read (buffer); if (read == -1) break; md5.update (buffer, 0, read); } byte[] md5Bytes = md5.digest (); StringBuffer md5Buffer = new StringBuffer (md5Bytes.length * 2); for (int i = 0; i < md5Bytes.length; i++) { String hex = Integer.toHexString (md5Bytes[i] & 0x00ff); if (hex.length () == 1) md5Buffer.append ('0'); md5Buffer.append (hex); } return md5Buffer.toString (); } catch (Exception e) { throw new BuildException(e); } } }
// vim: et sw=4 sts=4 tabstop=4 package com.issc.ui; import com.issc.Bluebit; import com.issc.gatt.Gatt; import com.issc.gatt.GattCharacteristic; import com.issc.gatt.GattDescriptor; import com.issc.gatt.GattService; import com.issc.impl.LeService; import com.issc.impl.GattTransaction; import com.issc.R; import com.issc.util.Log; import com.issc.util.Util; import com.issc.util.TransactionQueue; import java.io.FileOutputStream; import java.io.File; import java.io.OutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Iterator; import java.util.UUID; import java.util.List; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.content.ServiceConnection; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.text.method.ScrollingMovementMethod; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Spinner; import android.widget.TabHost; import android.widget.TextView; import android.widget.ToggleButton; public class ActivityTransparent extends Activity implements TransactionQueue.Consumer<GattTransaction> { private LeService mService; private BluetoothDevice mDevice; private Gatt.Listener mListener; private SrvConnection mConn; private ProgressDialog mConnectionDialog; private ProgressDialog mTimerDialog; protected ViewHandler mViewHandler; private OutputStream mStream; private TransactionQueue mQueue; private final static int PAYLOAD_MAX = 20; // 90 bytes might be max private final static int CONNECTION_DIALOG = 1; private final static int TIMER_DIALOG = 2; private final static int CHOOSE_FILE = 0x101; private final static int COMPARE_FILE = 0x102; private final static int MENU_CLEAR = 0x501; private final static String INFO_CONTENT = "the_information_body"; private final static String ECHO_ENABLED = "echo_function_is_enabled"; private final static int SHOW_CONNECTION_DIALOG = 0x1000; private final static int DISMISS_CONNECTION_DIALOG = 0x1001; private final static int CONSUME_TRANSACTION = 0x1002; private final static int DISMISS_TIMER_DIALOG = 0x1003; private final static int APPEND_MESSAGE = 0x1004; private final static int ECHO_STATE = 0x1005; private TabHost mTabHost; private TextView mMsg; private EditText mInput; private Button mBtnSend; private ToggleButton mToggleEcho; private ToggleButton mToggleResponse; private CompoundButton mEchoIndicator; private Spinner mSpinnerDelta; private Spinner mSpinnerSize; private Spinner mSpinnerRepeat; private int[] mValueDelta; private int[] mValueSize; private int[] mValueRepeat; private GattCharacteristic mTransTx; private GattCharacteristic mTransRx; private int mSuccess = 0; private int mFail = 0; private Calendar mStartTime; private final static int MAX_LINES = 50; private ArrayList<CharSequence> mLogBuf; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_trans); mQueue = new TransactionQueue(this); mMsg = (TextView)findViewById(R.id.trans_msg); mInput = (EditText)findViewById(R.id.trans_input); mBtnSend = (Button)findViewById(R.id.trans_btn_send); mToggleEcho = (ToggleButton)findViewById(R.id.echo_toggle); mToggleResponse = (ToggleButton)findViewById(R.id.trans_type); mEchoIndicator = (CompoundButton)findViewById(R.id.echo_indicator); mViewHandler = new ViewHandler(); mTabHost = (TabHost) findViewById(R.id.tabhost); mTabHost.setup(); addTab(mTabHost, "Tab1", "Raw", R.id.tab_raw); addTab(mTabHost, "Tab2", "Timer", R.id.tab_timer); addTab(mTabHost, "Tab3", "Echo", R.id.tab_echo); mMsg.setMovementMethod(ScrollingMovementMethod.getInstance()); registerForContextMenu(mMsg); mDevice = getIntent().getParcelableExtra(Bluebit.CHOSEN_DEVICE); mListener = new GattListener(); initSpinners(); mLogBuf = new ArrayList<CharSequence>(); /* Transparent is not a leaf activity. connect service in onCreate*/ mConn = new SrvConnection(); bindService(new Intent(this, LeService.class), mConn, 0); } @Override public void onDestroy() { super.onDestroy(); mQueue.clear(); closeStream(); mViewHandler.removeCallbacksAndMessages(null); /* Transparent is not a leaf activity. disconnect/unregister-listener in onDestroy*/ mService.rmListener(mListener); mService = null; unbindService(mConn); } private void initSpinners() { Resources res = getResources(); mSpinnerDelta = (Spinner)findViewById(R.id.timer_delta); mSpinnerSize = (Spinner)findViewById(R.id.timer_size); mSpinnerRepeat = (Spinner)findViewById(R.id.timer_repeat); mValueDelta = res.getIntArray(R.array.delta_value); mValueSize = res.getIntArray(R.array.size_value); mValueRepeat = res.getIntArray(R.array.repeat_value); initSpinner(R.array.delta_text, mSpinnerDelta); initSpinner(R.array.size_text, mSpinnerSize); initSpinner(R.array.repeat_text, mSpinnerRepeat); mSpinnerDelta.setSelection(3); // supposed to select 1000ms mSpinnerSize.setSelection(19); // supposed to select 20bytes mSpinnerRepeat.setSelection(0); // supposed to select Unlimited } private void initSpinner(int textArrayId, Spinner spinner) { ArrayAdapter<CharSequence> adapter; adapter = ArrayAdapter.createFromResource( this, textArrayId, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } private void addTab(TabHost host, String tag, CharSequence text, int viewResource) { View indicator = getLayoutInflater().inflate(R.layout.tab_indicator, null); TextView tv = (TextView)indicator.findViewById(R.id.indicator_text); tv.setText(text); TabHost.TabSpec spec = host.newTabSpec(tag); spec.setIndicator(indicator); spec.setContent(viewResource); host.addTab(spec); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info) { super.onCreateContextMenu(menu, v, info); if (v == mMsg) { menu.setHeaderTitle("Message Area"); menu.add(0, MENU_CLEAR, Menu.NONE, "Clear"); } } @Override public boolean onContextItemSelected(MenuItem item) { int id = item.getItemId(); if (id == MENU_CLEAR) { mLogBuf.clear(); mMsg.setText(""); mMsg.scrollTo(0, 0); } return true; } public void onClickSend(View v) { CharSequence cs = mInput.getText(); msgShow("send", cs); write(cs); } public void onClickStartTimer(View v) { showDialog(TIMER_DIALOG); startTimer(); } public void onClickCompare(View v) { Intent i = new Intent(this, ActivityFileChooser.class); i.putExtra(Bluebit.CHOOSE_PATH, Bluebit.DATA_DIR); startActivityForResult(i, COMPARE_FILE); } public void onClickChoose(View v) { Intent i = new Intent(this, ActivityFileChooser.class); i.putExtra(Bluebit.CHOOSE_PATH, Bluebit.DATA_DIR); startActivityForResult(i, CHOOSE_FILE); } public void onClickType(View v) { onSetType(mToggleResponse.isChecked()); } public void onClickEcho(View v) { onSetEcho(mToggleEcho.isChecked()); } private void onSetType(boolean withResponse) { Log.d("set write with response:" + withResponse); } private void onSetEcho(boolean enable) { if (enable) { enableNotification(); openStream(Bluebit.DEFAULT_LOG); } else { disableNotification(); closeStream(); } } private void enableNotification() { boolean set = mService.setCharacteristicNotification(mTransTx, true); Log.d("set notification:" + set); GattDescriptor dsc = mTransTx.getDescriptor(Bluebit.DES_CLIENT_CHR_CONFIG); dsc.setValue(dsc.getConstantBytes(GattDescriptor.ENABLE_NOTIFICATION_VALUE)); boolean success = mService.writeDescriptor(dsc); Log.d("writing enable descriptor:" + success); } private void disableNotification() { boolean set = mService.setCharacteristicNotification(mTransTx, false); Log.d("set notification:" + set); GattDescriptor dsc = mTransTx.getDescriptor(Bluebit.DES_CLIENT_CHR_CONFIG); dsc.setValue(dsc.getConstantBytes(GattDescriptor.DISABLE_NOTIFICATION_VALUE)); boolean success = mService.writeDescriptor(dsc); Log.d("writing disable descriptor:" + success); } private void openStream(String path) { try { File file = new File(path); if (!file.exists()) { Log.w("Target file does not exist, create: " + path); File parent = file.getParentFile(); Log.w("make dirs:" + parent.getPath()); parent.mkdirs(); file.createNewFile(); } mStream = new FileOutputStream(file, false); } catch (IOException e) { msgShow("open stream fail", e.toString()); e.printStackTrace(); } } private void closeStream() { try { if (mStream != null) { mStream.flush(); mStream.close(); } } catch (IOException e) { msgShow("close stream fail", e.toString()); e.printStackTrace(); } mStream = null; } private void writeToStream(byte[] data) { if (mStream != null) { try { mStream.write(data, 0, data.length); mStream.flush(); } catch (IOException e) { msgShow("write fail", e.toString()); e.printStackTrace(); } } } private void compareFile(String pathA, String pathB) { try { String md5A = Util.getMD5FromBytes(Util.readBytesFromFile(pathA)); String md5B = Util.getMD5FromBytes(Util.readBytesFromFile(pathB)); msgShow(pathA, md5A); msgShow(pathB, md5B); if (md5A.equals(md5B)) { msgShow("compare", "Match"); } else { msgShow("compare", "Not Match"); } } catch (IOException e) { msgShow("comapre fail", e.toString()); e.printStackTrace(); } } /** * Received data from remote when enabling Echo. * * Display the data and transfer back to device. */ private void onEcho(byte[] data) { StringBuffer sb = new StringBuffer(); if (data == null) { sb.append("Received empty data"); } else { String recv = new String(data); msgShow("recv", recv); write(data); writeToStream(data); msgShow("echo", recv); } Bundle msg = new Bundle(); msg.putCharSequence(INFO_CONTENT, sb); updateView(APPEND_MESSAGE, msg); } @Override protected void onActivityResult(int request, int result, Intent data) { if (request == CHOOSE_FILE) { if (result == Activity.RESULT_OK) { Uri uri = data.getData(); String filePath = uri.getPath(); Log.d("chosen file:" + filePath); try { mStartTime = Calendar.getInstance(); write(Util.readBytesFromFile(filePath)); msgShow("send", filePath); } catch (IOException e) { e.printStackTrace(); Log.d("IO Exception"); } } } else if (request == COMPARE_FILE) { if (data != null) { Uri uri = data.getData(); String filePath = uri.getPath(); compareFile(filePath, Bluebit.DEFAULT_LOG); } } } private void msgShow(CharSequence prefix, CharSequence cs) { StringBuffer sb = new StringBuffer(); sb.append(prefix); sb.append(": "); sb.append(cs); Log.d(sb.toString()); Bundle msg = new Bundle(); msg.putCharSequence(INFO_CONTENT, sb.toString()); updateView(APPEND_MESSAGE, msg); } /** * Write string to remote device. */ private void write(CharSequence cs) { byte[] bytes = cs.toString().getBytes(); write(bytes); } /** * Write data to remote device. */ private void write(byte[] bytes) { ByteBuffer buf = ByteBuffer.allocate(bytes.length); buf.put(bytes); buf.position(0); while(buf.remaining() != 0) { int size = (buf.remaining() > PAYLOAD_MAX) ? PAYLOAD_MAX: buf.remaining(); byte[] dst = new byte[size]; buf.get(dst, 0, size); GattTransaction t = new GattTransaction(mTransRx, dst); mQueue.add(t); } } @Override protected Dialog onCreateDialog(int id, Bundle args) { /*FIXME: this function is deprecated. */ if (id == CONNECTION_DIALOG) { mConnectionDialog = new ProgressDialog(this); mConnectionDialog.setMessage(this.getString(R.string.connecting)); mConnectionDialog.setCancelable(true); return mConnectionDialog; } else if (id == TIMER_DIALOG) { mTimerDialog = new ProgressDialog(this); mTimerDialog.setMessage("Timer is running"); mTimerDialog.setOnCancelListener(new Dialog.OnCancelListener() { public void onCancel(DialogInterface dialog) { Log.d("some one canceled me"); stopTimer(); } }); return mTimerDialog; } return null; } private void onTimerSend(int count, int size) { /* max is 20 */ String out = String.format("%020d", count); if (out.length() > size) { // if too long out = out.substring(out.length() - size); } msgShow("send", out); write(out); } private boolean mRunning; private void startTimer() { final int delta = mValueDelta[mSpinnerDelta.getSelectedItemPosition()]; final int size = mValueSize[mSpinnerSize.getSelectedItemPosition()]; final int repeat = mValueRepeat[mSpinnerRepeat.getSelectedItemPosition()]; mRunning = true; Thread runner = new Thread() { public void run() { int counter = 0; try { while(mRunning) { if (repeat != 0 && repeat == counter) { stopTimer(); } else { onTimerSend(counter, size); sleep(delta); counter++; } } } catch (Exception e) { e.printStackTrace(); } updateView(DISMISS_TIMER_DIALOG, null); } }; runner.start(); } private void stopTimer() { mRunning = false; } /** * Add message to UI. */ private void appendMsg(CharSequence msg) { StringBuffer sb = new StringBuffer(); sb.append(msg); sb.append("\n"); mLogBuf.add(sb); // we don't want to display too many lines if (mLogBuf.size() > MAX_LINES) { mLogBuf.remove(0); } StringBuffer text = new StringBuffer(); for (int i = 0; i < mLogBuf.size(); i++) { text.append(mLogBuf.get(i)); } mMsg.setText(text); } private void onConnected() { List<GattService> list = mService.getServices(mDevice); if ((list == null) || (list.size() == 0)) { Log.d("no services, do discovery"); mService.discoverServices(mDevice); } else { onDiscovered(); } } private void onDisconnected() { Log.d("disconnected, connecting to device"); updateView(SHOW_CONNECTION_DIALOG, null); mStartTime = null; mQueue.clear(); mService.connectGatt(this, false, mDevice); mService.connect(mDevice, false); } private void onDiscovered() { updateView(DISMISS_CONNECTION_DIALOG, null); GattService proprietary = mService.getService(mDevice, Bluebit.SERVICE_ISSC_PROPRIETARY); mTransTx = proprietary.getCharacteristic(Bluebit.CHR_ISSC_TRANS_TX); mTransRx = proprietary.getCharacteristic(Bluebit.CHR_ISSC_TRANS_RX); Log.d(String.format("found Tx:%b, Rx:%b", mTransTx != null, mTransRx != null)); onSetEcho(mToggleEcho.isChecked()); } @Override public void onTransact(GattTransaction t) { t.chr.setValue(t.value); if (t.isWrite) { int type = mToggleResponse.isChecked() ? GattCharacteristic.WRITE_TYPE_DEFAULT: GattCharacteristic.WRITE_TYPE_NO_RESPONSE; t.chr.setWriteType(type); mService.writeCharacteristic(t.chr); } else { mService.readCharacteristic(t.chr); } } public void updateView(int tag, Bundle info) { if (info == null) { info = new Bundle(); } Message msg = mViewHandler.obtainMessage(tag); msg.what = tag; msg.setData(info); mViewHandler.sendMessage(msg); } class ViewHandler extends Handler { public void handleMessage(Message msg) { Bundle bundle = msg.getData(); if (bundle == null) { Log.d("ViewHandler handled a message without information"); return; } int tag = msg.what; if (tag == SHOW_CONNECTION_DIALOG) { showDialog(CONNECTION_DIALOG); } else if (tag == DISMISS_CONNECTION_DIALOG) { if (mConnectionDialog != null && mConnectionDialog.isShowing()) { dismissDialog(CONNECTION_DIALOG); } } else if (tag == DISMISS_TIMER_DIALOG) { if (mTimerDialog != null && mTimerDialog.isShowing()) { dismissDialog(TIMER_DIALOG); } } else if (tag == CONSUME_TRANSACTION) { // mQueue itself will consume next transaction //mQueue.process(); } else if (tag == APPEND_MESSAGE) { CharSequence content = bundle.getCharSequence(INFO_CONTENT); if (content != null) { appendMsg(content); /*fot automaticaly scrolling to end*/ final int amount = mMsg.getLayout().getLineTop(mMsg.getLineCount()) - mMsg.getHeight(); if (amount > 0) { mMsg.scrollTo(0, amount); } } } else if (tag == ECHO_STATE) { mEchoIndicator.setChecked(bundle.getBoolean(ECHO_ENABLED, false)); } } } class GattListener extends Gatt.ListenerHelper { GattListener() { super("ActivityTransparent"); } @Override public void onConnectionStateChange(Gatt gatt, int status, int newState) { if (!mDevice.getAddress().equals(gatt.getDevice().getAddress())) { // not the device I care about return; } if (newState == BluetoothProfile.STATE_CONNECTED) { onConnected(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { onDisconnected(); } } @Override public void onServicesDiscovered(Gatt gatt, int status) { onDiscovered(); } @Override public void onCharacteristicRead(Gatt gatt, GattCharacteristic charac, int status) { Log.d("read char, uuid=" + charac.getUuid().toString()); byte[] value = charac.getValue(); Log.d("get value, byte length:" + value.length); for (int i = 0; i < value.length; i++) { Log.d("[" + i + "]" + Byte.toString(value[i])); } mQueue.onConsumed(); } @Override public void onCharacteristicChanged(Gatt gatt, GattCharacteristic chrc) { Log.d("on chr changed" ); if (chrc.getUuid().equals(Bluebit.CHR_ISSC_TRANS_TX)) { onEcho(chrc.getValue()); } } @Override public void onCharacteristicWrite(Gatt gatt, GattCharacteristic charac, int status) { if (status == Gatt.GATT_SUCCESS) { mSuccess +=charac.getValue().length; } else { mFail += charac.getValue().length; } String s = String.format("%d bytes, success= %d, fail= %d, pending= %d", charac.getValue().length, mSuccess, mFail, mQueue.size()); msgShow("wrote", s); mQueue.onConsumed(); if (mQueue.size() == 0 && mStartTime != null) { long elapse = Calendar.getInstance().getTimeInMillis() - mStartTime.getTimeInMillis(); msgShow("time", "spent " + (elapse / 1000) + " seconds"); mStartTime = null; } updateView(CONSUME_TRANSACTION, null); } @Override public void onDescriptorWrite(Gatt gatt, GattDescriptor dsc, int status) { if (status == Gatt.GATT_SUCCESS) { byte[] value = dsc.getValue(); if (Arrays.equals(value, dsc.getConstantBytes(GattDescriptor.ENABLE_NOTIFICATION_VALUE))) { Bundle state = new Bundle(); state.putBoolean(ECHO_ENABLED, true); updateView(ECHO_STATE, state); } else if (Arrays.equals(value, dsc.getConstantBytes(GattDescriptor.DISABLE_NOTIFICATION_VALUE))) { Bundle state = new Bundle(); state.putBoolean(ECHO_ENABLED, false); updateView(ECHO_STATE, state); } } } } class SrvConnection implements ServiceConnection { @Override public void onServiceConnected(ComponentName componentName, IBinder service) { mService = ((LeService.LocalBinder)service).getService(); mService.addListener(mListener); int conn = mService.getConnectionState(mDevice); if (conn == BluetoothProfile.STATE_DISCONNECTED) { onDisconnected(); } else { Log.d("already connected"); onConnected(); } } @Override public void onServiceDisconnected(ComponentName componentName) { Log.e("Gatt Service disconnected"); } } }
package com.jmex.awt.swingui; import java.awt.AWTEvent; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.KeyboardFocusManager; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ContainerEvent; import java.awt.event.ContainerListener; import java.awt.event.FocusEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.beans.PropertyVetoException; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JComponent; import javax.swing.JDesktopPane; import javax.swing.JInternalFrame; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JViewport; import javax.swing.Popup; import javax.swing.PopupFactory; import javax.swing.RepaintManager; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.basic.BasicInternalFrameUI; import com.jme.bounding.OrientedBoundingBox; import com.jme.image.Texture; import com.jme.image.Texture2D; import com.jme.input.InputHandler; import com.jme.input.KeyInput; import com.jme.input.MouseInput; import com.jme.input.action.InputAction; import com.jme.input.action.InputActionEvent; import com.jme.math.Ray; import com.jme.math.Vector2f; import com.jme.math.Vector3f; import com.jme.renderer.Renderer; import com.jme.scene.Node; import com.jme.scene.shape.Quad; import com.jme.scene.state.BlendState; import com.jme.scene.state.TextureState; import com.jme.system.DisplaySystem; import com.jmex.awt.input.AWTKeyInput; import com.jmex.awt.input.AWTMouseInput; import com.jmex.awt.swingui.dnd.JMEDragAndDrop; public class JMEDesktop extends Quad { private static final Logger logger = Logger.getLogger(JMEDesktop.class .getName()); private static final long serialVersionUID = 1L; private ImageGraphics graphics; private JDesktopPane desktop; private Texture texture; private boolean initialized; private int width; private int height; private boolean showingJFrame = false; private final Frame awtWindow; private int desktopWidth; private int desktopHeight; private static final int DOUBLE_CLICK_TIME = 300; private final InputHandler inputHandler; private JMEDesktop.XUpdateAction xUpdateAction; private JMEDesktop.YUpdateAction yUpdateAction; private WheelUpdateAction wheelUpdateAction; private JMEDesktop.ButtonAction allButtonsUpdateAction; private InputAction keyUpdateAction; private JMEDragAndDrop dragAndDropSupport; /** * @return JMEDragAndDrop used for this desktop */ public JMEDragAndDrop getDragAndDropSupport() { return dragAndDropSupport; } /** * @param dragAndDropSupport JMEDragAndDrop to be used for this desktop * @see JMEDragAndDrop#setDesktop(JMEDesktop) */ public void setDragAndDropSupport( JMEDragAndDrop dragAndDropSupport ) { this.dragAndDropSupport = dragAndDropSupport; } /** * @see #setShowingJFrame * @return true if frame is displayed */ public boolean isShowingJFrame() { return showingJFrame; } /** * @param showingJFrame true to display the desktop in a JFrame instead on this quad. * @deprecated for debuggin only */ public void setShowingJFrame( boolean showingJFrame ) { this.showingJFrame = showingJFrame; awtWindow.setVisible( showingJFrame ); awtWindow.repaint(); } /** * Allows to disable input for the whole desktop and to add custom input actions. * * @return this desktops input hander for input bindings * @see #getXUpdateAction() * @see #getYUpdateAction() * @see #getWheelUpdateAction() * @see #getButtonUpdateAction(int) * @see #getKeyUpdateAction() */ public InputHandler getInputHandler() { return inputHandler; } /** * Create a quad with a Swing-Texture. Creates the quad and the JFrame but do not setup the rest. * Call {@link #setup(int, int, boolean, InputHandler)} to finish setup. * * @param name name of this desktop */ public JMEDesktop( String name ) { super( name ); inputHandler = new InputHandler(); awtWindow = new Frame() { private static final long serialVersionUID = 1L; public boolean isShowing() { return true; } public boolean isVisible() { // if ( new Throwable().getStackTrace()[1].getMethodName().startsWith( "requestFocus" ) ) { // logger.info( "requestFocus" ); if ( awtWindow.isFocusableWindow() && new Throwable().getStackTrace()[1].getMethodName().startsWith( "requestFocus" ) ) { return false; } return initialized || super.isVisible(); } public Graphics getGraphics() { if ( !showingJFrame ) { return graphics == null ? super.getGraphics() : graphics.create(); } return super.getGraphics(); } public boolean isFocused() { return true; } }; awtWindow.setFocusableWindowState( false ); Container contentPane = awtWindow; awtWindow.setUndecorated( true ); dontDrawBackground( contentPane ); // ( (JComponent) contentPane ).setOpaque( false ); desktop = new JDesktopPane() { private static final long serialVersionUID = 1L; public void paint( Graphics g ) { if ( !isShowingJFrame() ) { g.clearRect( 0, 0, getWidth(), getHeight() ); } super.paint( g ); } public boolean isOptimizedDrawingEnabled() { return false; } }; new ScrollPaneRepaintFixListener().addTo( desktop ); final Color transparent = new Color( 0, 0, 0, 0 ); desktop.setBackground( transparent ); desktop.setFocusable( true ); desktop.addMouseListener( new MouseAdapter() { public void mousePressed( MouseEvent e ) { desktop.requestFocusInWindow(); } } ); // this internal frame is a workaround for key binding problems in JDK1.5 // todo: this workaround does not seem to work on mac if ( System.getProperty( "os.name" ).toLowerCase().indexOf( "mac" ) < 0 ) { final JInternalFrame internalFrame = new JInternalFrame(); internalFrame.setUI( new BasicInternalFrameUI( internalFrame ) { protected void installComponents() { } } ); internalFrame.setOpaque( false ); internalFrame.setBackground( null ); internalFrame.getContentPane().setLayout( new BorderLayout() ); internalFrame.getContentPane().add( desktop, BorderLayout.CENTER ); internalFrame.setVisible( true ); internalFrame.setBorder( null ); contentPane.add( internalFrame ); } else { // this would have suited for JDK1.4: contentPane.add( desktop, BorderLayout.CENTER ); } awtWindow.pack(); RepaintManager.currentManager( null ).setDoubleBufferingEnabled( false ); } /** * Create a quad with a Swing-Texture. * Note that for the texture a width and height that is a power of 2 is used if the graphics card does * not support the specified size for textures. E.g. this results in a 1024x512 * texture for a 640x480 desktop (consider using a 512x480 desktop in that case). * * @param name name of the spatial * @param width desktop width * @param height desktop height * @param inputHandlerParent InputHandler where the InputHandler of this desktop should be added as subhandler, * may be null to provide custom input handling or later adding of InputHandler(s) * @see #getInputHandler() */ public JMEDesktop( String name, final int width, final int height, InputHandler inputHandlerParent ) { this( name, width, height, false, inputHandlerParent ); } /** * Create a quad with a Swing-Texture. * Note that for the texture a width and height that is a power of 2 is used if the graphics card does * not support the specified size for textures or mipMapping is true. E.g. this results in a 1024x512 * texture for a 640x480 desktop (consider using a 512x480 desktop in that case). * * @param name name of the spatial * @param width desktop width * @param height desktop hieght * @param mipMapping true to compute mipmaps for the desktop (not recommended), false for creating * a single image texture * @param inputHandlerParent InputHandler where the InputHandler of this desktop should be added as subhandler, * may be null to provide custom input handling or later adding of InputHandler(s) * @see #getInputHandler() */ public JMEDesktop( String name, final int width, final int height, boolean mipMapping, InputHandler inputHandlerParent ) { this( name ); setup( width, height, mipMapping, inputHandlerParent ); } /** * Set up the desktop quad - may be called only once. * Note that for the texture a width and height that is a power of 2 is used if the graphics card does * not support the specified size for textures or mipMapping is true. E.g. this results in a 1024x512 * texture for a 640x480 desktop (consider using a 512x480 desktop in that case). * * @param width desktop width * @param height desktop hieght * @param mipMapping true to compute mipmaps for the desktop (not recommended), false for creating * a single image texture * @param inputHandlerParent InputHandler where the InputHandler of this desktop should be added as subhandler, * may be null to provide custom input handling or later adding of InputHandler(s) * @see #getInputHandler() */ public void setup( int width, int height, boolean mipMapping, InputHandler inputHandlerParent ) { reconstruct( null, null, null, null ); if ( inputHandlerParent != null ) { inputHandlerParent.addToAttachedHandlers( inputHandler ); } if ( initialized ) { throw new IllegalStateException( "may be called only once" ); } initialize( powerOf2SizeIfNeeded( width, mipMapping ), powerOf2SizeIfNeeded( height, mipMapping ) ); this.width = powerOf2SizeIfNeeded( width, mipMapping ); this.height = powerOf2SizeIfNeeded( height, mipMapping ); setModelBound( new OrientedBoundingBox() ); updateModelBound(); desktop.setPreferredSize( new Dimension( width, height ) ); desktopWidth = width; desktopHeight = height; awtWindow.pack(); TextureState ts = DisplaySystem.getDisplaySystem().getRenderer().createTextureState(); ts.setCorrectionType( TextureState.CorrectionType.Perspective ); texture = new Texture2D(); texture.setMagnificationFilter( Texture.MagnificationFilter.Bilinear ); texture.setMinificationFilter( mipMapping ? Texture.MinificationFilter.Trilinear : Texture.MinificationFilter.BilinearNoMipMaps ); texture.setWrap( Texture.WrapMode.Repeat ); graphics = ImageGraphics.createInstance( this.width, this.height, mipMapping ? 2 : 0 ); enableAntiAlias( graphics ); graphics.translate( ( this.width - width ) * 0.5f, ( this.height - height ) * 0.5f ); texture.setImage( graphics.getImage() ); texture.setScale( new Vector3f( 1, -1, 1 ) ); ts.setTexture( texture ); this.setRenderState( ts ); BlendState alpha = DisplaySystem.getDisplaySystem().getRenderer().createBlendState(); alpha.setEnabled( true ); alpha.setBlendEnabled( true ); alpha.setSourceFunction( BlendState.SourceFunction.SourceAlpha ); alpha.setDestinationFunction( BlendState.DestinationFunction.OneMinusSourceAlpha ); alpha.setTestEnabled( true ); alpha.setTestFunction( BlendState.TestFunction.GreaterThan ); this.setRenderState( alpha ); // Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener() { // public void eventDispatched( AWTEvent event ) { // if ( isShowingJFrame() ) { // logger.info( event ); // }, 0xFFFFFFFFFFFFFFFFl ); xUpdateAction = new XUpdateAction(); yUpdateAction = new YUpdateAction(); wheelUpdateAction = new WheelUpdateAction(); wheelUpdateAction.setSpeed( AWTMouseInput.WHEEL_AMP ); allButtonsUpdateAction = new ButtonAction( InputHandler.BUTTON_ALL ); keyUpdateAction = new KeyUpdateAction(); setupDefaultInputBindings(); if ( desktopsUsed == 0 ) { PopupFactory.setSharedInstance( new MyPopupFactory() ); } desktopsUsed++; SwingUtilities.invokeLater( new Runnable() { public void run() { JMEDesktop.this.setFocusOwner( desktop ); } } ); initialized = true; setSynchronizingThreadsOnUpdate( true ); } private static int desktopsUsed = 0; protected void setupDefaultInputBindings() { getInputHandler().addAction( getButtonUpdateAction( InputHandler.BUTTON_ALL ), InputHandler.DEVICE_MOUSE, InputHandler.BUTTON_ALL, InputHandler.AXIS_NONE, false ); getInputHandler().addAction( getXUpdateAction(), InputHandler.DEVICE_MOUSE, InputHandler.BUTTON_NONE, 0, false ); getInputHandler().addAction( getYUpdateAction(), InputHandler.DEVICE_MOUSE, InputHandler.BUTTON_NONE, 1, false ); getInputHandler().addAction( getWheelUpdateAction(), InputHandler.DEVICE_MOUSE, InputHandler.BUTTON_NONE, 2, false ); getInputHandler().addAction( getKeyUpdateAction(), InputHandler.DEVICE_KEYBOARD, InputHandler.BUTTON_ALL, InputHandler.AXIS_NONE, false ); } //todo: reuse the runnables //todo: possibly reuse events, too? public void onKey( final char character, final int keyCode, final boolean pressed ) { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { sendAWTKeyEvent( keyCode, pressed, character ); } } ); } catch ( InterruptedException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "onKey(character, keyCode, pressed)", "Exception", e); } catch ( InvocationTargetException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "onKey(character, keyCode, pressed)", "Exception", e); } } public void onButton( final int swingButton, final boolean pressed, final int x, final int y ) { convert( x, y, location ); final int awtX = (int) location.x; final int awtY = (int) location.y; try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { sendAWTMouseEvent( awtX, awtY, pressed, swingButton ); } } ); } catch ( InterruptedException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "onButton(swingButton, pressed, x, y)", "Exception", e); } catch ( InvocationTargetException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "onButton(swingButton, pressed, x, y)", "Exception", e); } } public void onWheel( final int wheelDelta, final int x, final int y ) { convert( x, y, location ); final int awtX = (int) location.x; final int awtY = (int) location.y; try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { sendAWTWheelEvent( wheelDelta, awtX, awtY ); } } ); } catch ( InterruptedException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "onWheel(wheelDelta, x, y)", "Exception", e); } catch ( InvocationTargetException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "onWheel(wheelDelta, x, y)", "Exception", e); } } public void onMove( int xDelta, int yDelta, final int newX, final int newY ) { convert( newX, newY, location ); final int awtX = (int) location.x; final int awtY = (int) location.y; try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { sendAWTMouseEvent( awtX, awtY, false, MouseEvent.NOBUTTON ); } } ); } catch ( InterruptedException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "onMove(xDelta, yDelta, newX, newY)", "Exception", e); } catch ( InvocationTargetException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "onMove(xDelta, yDelta, newX, newY)", "Exception", e); } } private boolean synchronizingThreadsOnUpdate; /** * @return true if update and swing thread should be synchronized (avoids flickering, eats some performance) */ public boolean isSynchronizingThreadsOnUpdate() { return synchronizingThreadsOnUpdate; } /** * Choose if update and swing thread should be synchronized (avoids flickering, eats some performance) * * @param synchronizingThreadsOnUpdate true to synchronize */ public void setSynchronizingThreadsOnUpdate( boolean synchronizingThreadsOnUpdate ) { if ( this.synchronizingThreadsOnUpdate != synchronizingThreadsOnUpdate ) { this.synchronizingThreadsOnUpdate = synchronizingThreadsOnUpdate; } } private void enableAntiAlias( Graphics2D graphics ) { RenderingHints hints = graphics.getRenderingHints(); if ( hints == null ) { hints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); } else { hints.put( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); } graphics.setRenderingHints( hints ); } /** * @return an action that should be invoked to generate an awt event when the mouse x-coordinate is changed */ public XUpdateAction getXUpdateAction() { return xUpdateAction; } /** * @return an action that should be invoked to generate an awt event when the mouse y-coordinate is changed */ public YUpdateAction getYUpdateAction() { return yUpdateAction; } /** * @return an action that should be invoked to generate an awt event when the mouse wheel position is changed */ public WheelUpdateAction getWheelUpdateAction() { return wheelUpdateAction; } /** * @param swingButtonIndex button index sent in generated swing event, InputHandler.BUTTON_ALL for using * trigger index + 1 * @return an action that should be invoked to generate an awt event for a pressed/released mouse button */ public ButtonAction getButtonUpdateAction( int swingButtonIndex ) { if ( swingButtonIndex == InputHandler.BUTTON_ALL ) { return allButtonsUpdateAction; } return new ButtonAction( swingButtonIndex ); } /** * @return an action that should be invoked to generate an awt event for a pressed/released key */ public InputAction getKeyUpdateAction() { return keyUpdateAction; } private static class LightWeightPopup extends Popup { private static final Integer INTEGER_MAX_VALUE = Integer.MAX_VALUE; public LightWeightPopup( JComponent desktop ) { this.desktop = desktop; new ScrollPaneRepaintFixListener().addTo( panel ); } private final JComponent desktop; JPanel panel = new JPanel( new BorderLayout() ); public void adjust( Component owner, Component contents, int x, int y ) { panel.setVisible( false ); desktop.add( panel, INTEGER_MAX_VALUE ); panel.removeAll(); panel.add( contents, BorderLayout.CENTER ); if ( contents instanceof JComponent ) { JComponent jComponent = (JComponent) contents; jComponent.setDoubleBuffered( false ); } panel.setSize( panel.getPreferredSize() ); y = Math.min( y, desktop.getHeight() - panel.getHeight() ); x = Math.min( x, desktop.getWidth() - panel.getWidth() ); panel.setLocation( x, y ); contents.invalidate(); panel.validate(); } public void show() { panel.setVisible( true ); } public void hide() { Rectangle bounds = panel.getBounds(); desktop.remove( panel ); desktop.repaint( bounds ); } } private void sendAWTKeyEvent( int keyCode, boolean pressed, char character ) { keyCode = AWTKeyInput.toAWTCode( keyCode ); if ( keyCode != 0 ) { Component focusOwner = getFocusOwner(); if ( focusOwner == null ) { focusOwner = desktop; } if ( character == '\0' ) { character = KeyEvent.CHAR_UNDEFINED; } if ( focusOwner != null ) { if ( pressed ) { KeyEvent event = new KeyEvent( focusOwner, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), getCurrentModifiers( -1 ), keyCode, character ); dispatchEvent( focusOwner, event ); anInt.value = keyCode; Char c = characters.get( anInt ); if ( c == null ) { characters.put( new Int( keyCode ), new Char( character ) ); } else { c.value = character; } if ( character != KeyEvent.CHAR_UNDEFINED ) { dispatchEvent( focusOwner, new KeyEvent( focusOwner, KeyEvent.KEY_TYPED, System.currentTimeMillis(), getCurrentModifiers( -1 ), 0, character ) ); } } if ( !pressed ) { anInt.value = keyCode; Char c = characters.get( anInt ); if ( c != null ) { character = c.value; //TODO: repeat input // if ( character != KeyEvent.CHAR_UNDEFINED ) { // dispatchEvent( focusOwner, new KeyEvent( focusOwner, KeyEvent.KEY_TYPED, // System.currentTimeMillis(), getCurrentModifiers( -1 ), // 0, character ) ); } dispatchEvent( focusOwner, new KeyEvent( focusOwner, KeyEvent.KEY_RELEASED, System.currentTimeMillis(), getCurrentModifiers( -1 ), keyCode, character ) ); } } } } private void dispatchEvent( final Component receiver, final AWTEvent event ) { if ( getModalComponent() == null || SwingUtilities.isDescendingFrom( receiver, getModalComponent() ) ) { if ( !SwingUtilities.isEventDispatchThread() ) { throw new IllegalStateException( "not in swing thread!" ); } receiver.dispatchEvent( event ); } } private static Int anInt = new Int( 0 ); private static class Int { public Int( int value ) { this.value = value; } public boolean equals( Object obj ) { return obj instanceof Int && ( (Int) obj ).value == value; } public int hashCode() { return value; } int value; } private static class Char { public Char( char value ) { this.value = value; } char value; } /** * From keyCode (Int) to character (Char) */ private Map<Int,Char> characters = new HashMap<Int,Char>(); private static void dontDrawBackground( Container container ) { if ( container != null ) { container.setBackground( null ); if ( container instanceof JComponent ) { final JComponent component = ( (JComponent) container ); component.setOpaque( false ); } dontDrawBackground( container.getParent() ); } } private static int powerOf2SizeIfNeeded( int size, boolean generateMipMaps ) { if ( generateMipMaps || !TextureState.isNonPowerOfTwoTextureSupported() ) { int powerOf2Size = 1; while ( powerOf2Size < size ) { powerOf2Size <<= 1; } return powerOf2Size; } return size; } private Component lastComponent; private Component grabbedMouse; private int grabbedMouseButton; private int downX = 0; private int downY = 0; private long lastClickTime = 0; private int clickCount = 0; private static final int MAX_CLICKED_OFFSET = 4; private Vector2f location = new Vector2f(); private void sendAWTWheelEvent( int wheelDelta, int x, int y ) { Component comp = lastComponent != null ? lastComponent : componentAt( x, y, desktop, false ); if ( comp == null ) { comp = desktop; } final Point pos = convertPoint( desktop, x, y, comp ); final MouseWheelEvent event = new MouseWheelEvent( comp, MouseEvent.MOUSE_WHEEL, System.currentTimeMillis(), getCurrentModifiers( -1 ), pos.x, pos.y, 1, false, MouseWheelEvent.WHEEL_UNIT_SCROLL, Math.abs( wheelDelta ), wheelDelta > 0 ? -1 : 1 ); dispatchEvent( comp, event ); } private boolean useConvertPoint = true; private Point convertPoint( Component parent, int x, int y, Component comp ) { if ( useConvertPoint ) { try { return SwingUtilities.convertPoint( parent, x, y, comp ); } catch ( InternalError e ) { useConvertPoint = false; } } if ( comp != null ) { while ( comp != parent ) { x -= comp.getX(); y -= comp.getY(); if ( comp.getParent() == null ) { break; } comp = comp.getParent(); } } return new Point( x, y ); } private void sendAWTMouseEvent( int x, int y, boolean pressed, int swingButton ) { Component comp = componentAt( x, y, desktop, false ); final int eventType; if ( swingButton > MouseEvent.NOBUTTON ) { eventType = pressed ? MouseEvent.MOUSE_PRESSED : MouseEvent.MOUSE_RELEASED; } else { eventType = getButtonMask( MouseEvent.NOBUTTON ) == 0 ? MouseEvent.MOUSE_MOVED : MouseEvent.MOUSE_DRAGGED; } final long time = System.currentTimeMillis(); if ( lastComponent != comp ) { //enter/leave events while ( lastComponent != null && ( comp == null || !SwingUtilities.isDescendingFrom( comp, lastComponent ) ) ) { final Point pos = convertPoint( desktop, x, y, lastComponent ); sendExitedEvent( lastComponent, getCurrentModifiers( swingButton ), pos ); lastComponent = lastComponent.getParent(); } final Point pos = convertPoint( desktop, x, y, lastComponent ); if ( lastComponent == null ) { lastComponent = desktop; } sendEnteredEvent( comp, lastComponent, getCurrentModifiers( swingButton ), pos ); lastComponent = comp; downX = Integer.MIN_VALUE; downY = Integer.MIN_VALUE; lastClickTime = 0; } if ( comp != null ) { boolean clicked = false; if ( swingButton > MouseEvent.NOBUTTON ) { if ( pressed ) { grabbedMouse = comp; grabbedMouseButton = swingButton; downX = x; downY = y; setFocusOwner( componentAt( x, y, desktop, true ) ); } else if ( grabbedMouseButton == swingButton && grabbedMouse != null ) { comp = grabbedMouse; grabbedMouse = null; if ( Math.abs( downX - x ) <= MAX_CLICKED_OFFSET && Math.abs( downY - y ) < MAX_CLICKED_OFFSET ) { if ( lastClickTime + DOUBLE_CLICK_TIME > time ) { clickCount++; } else { clickCount = 1; } clicked = true; lastClickTime = time; } downX = Integer.MIN_VALUE; downY = Integer.MIN_VALUE; } } else if ( grabbedMouse != null ) { comp = grabbedMouse; } final Point pos = convertPoint( desktop, x, y, comp ); final MouseEvent event = new MouseEvent( comp, eventType, time, getCurrentModifiers( swingButton ), pos.x, pos.y, clickCount, swingButton == MouseEvent.BUTTON2 && pressed, // todo: should this be platform dependent? (e.g. mac) swingButton >= 0 ? swingButton : 0 ); dispatchEvent( comp, event ); if ( clicked ) { // CLICKED seems to need special glass pane handling o_O comp = componentAt( x, y, desktop, true ); final Point clickedPos = convertPoint( desktop, x, y, comp ); final MouseEvent clickedEvent = new MouseEvent( comp, MouseEvent.MOUSE_CLICKED, time, getCurrentModifiers( swingButton ), clickedPos.x, clickedPos.y, clickCount, false, swingButton ); dispatchEvent( comp, clickedEvent ); } } else if ( pressed ) { // clicked no component at all setFocusOwner( null ); } } private boolean focusCleared = false; public void setFocusOwner( Component comp ) { if ( comp == null || comp.isFocusable() ) { for ( Component p = comp; p != null; p = p.getParent() ) { if ( p instanceof JInternalFrame ) { try { ( (JInternalFrame) p ).setSelected( true ); } catch ( PropertyVetoException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "setFocusOwner(Component comp)", "Exception", e); } } } awtWindow.setFocusableWindowState( true ); Component oldFocusOwner = getFocusOwner(); if ( comp == desktop ) { comp = null; } if ( oldFocusOwner != comp ) { if ( oldFocusOwner != null ) { dispatchEvent( oldFocusOwner, new FocusEvent( oldFocusOwner, FocusEvent.FOCUS_LOST, false, comp ) ); } KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner(); if ( comp != null ) { dispatchEvent( comp, new FocusEvent( comp, FocusEvent.FOCUS_GAINED, false, oldFocusOwner ) ); } } awtWindow.setFocusableWindowState( false ); } focusCleared = comp == null; } private int getCurrentModifiers( int swingBtton ) { int modifiers = 0; if ( isKeyDown( KeyInput.KEY_LMENU ) ) { modifiers |= InputEvent.ALT_DOWN_MASK; modifiers |= InputEvent.ALT_MASK; } if ( isKeyDown( KeyInput.KEY_RMENU ) ) { modifiers |= InputEvent.ALT_GRAPH_DOWN_MASK; modifiers |= InputEvent.ALT_GRAPH_MASK; } if ( isKeyDown( KeyInput.KEY_LCONTROL ) || isKeyDown( KeyInput.KEY_RCONTROL ) ) { modifiers |= InputEvent.CTRL_DOWN_MASK; modifiers |= InputEvent.CTRL_MASK; } if ( isKeyDown( KeyInput.KEY_LSHIFT ) || isKeyDown( KeyInput.KEY_RSHIFT ) ) { modifiers |= InputEvent.SHIFT_DOWN_MASK; modifiers |= InputEvent.SHIFT_MASK; } return modifiers | getButtonMask( swingBtton ); } private boolean isKeyDown( int key ) { return KeyInput.get().isKeyDown( key ); } private int getButtonMask( int swingButton ) { int buttonMask = 0; if ( MouseInput.get().isButtonDown( 0 ) || swingButton == MouseEvent.BUTTON1 ) { buttonMask |= InputEvent.BUTTON1_MASK; buttonMask |= InputEvent.BUTTON1_DOWN_MASK; } if ( MouseInput.get().isButtonDown( 1 ) || swingButton == MouseEvent.BUTTON2 ) { buttonMask |= InputEvent.BUTTON2_MASK; buttonMask |= InputEvent.BUTTON2_DOWN_MASK; } if ( MouseInput.get().isButtonDown( 2 ) || swingButton == MouseEvent.BUTTON3 ) { buttonMask |= InputEvent.BUTTON3_MASK; buttonMask |= InputEvent.BUTTON3_DOWN_MASK; } return buttonMask; } private int lastXin = -1; private int lastXout = -1; private int lastYin = -1; private int lastYout = -1; private Ray pickRay = new Ray(); private Vector3f bottomLeft = new Vector3f(); private Vector3f topLeft = new Vector3f(); private Vector3f topRight = new Vector3f(); private Vector3f bottomRight = new Vector3f(); private Vector3f tuv = new Vector3f(); /** * Convert mouse coordinates from jME screen to JMEDesktop coordinates (Swing). * @param x jME x coordinate * @param y jME y coordinate * @param store resulting JDesktop coordinates */ public void convert( int x, int y, Vector2f store ) { if ( lastXin == x && lastYin == y ) { store.x = lastXout; store.y = lastYout; } else { lastXin = x; lastYin = y; if ( getRenderQueueMode() == Renderer.QUEUE_ORTHO ) { //TODO: occlusion by other quads (JMEFrames) x = (int) ( x - getWorldTranslation().x + desktopWidth / 2 ); y = (int) ( desktopHeight / 2 - ( y - getWorldTranslation().y ) ); } else { store.set( x, y ); DisplaySystem.getDisplaySystem().getWorldCoordinates( store, 0, pickRay.origin ); DisplaySystem.getDisplaySystem().getWorldCoordinates( store, 0.3f, pickRay.direction ).subtractLocal( pickRay.origin ).normalizeLocal(); applyWorld( bottomLeft.set( -width * 0.5f, -height * 0.5f, 0 ) ); applyWorld( topLeft.set( -width * 0.5f, height * 0.5f, 0 ) ); applyWorld( topRight.set( width * 0.5f, height * 0.5f, 0 ) ); applyWorld( bottomRight.set( width * 0.5f, -height * 0.5f, 0 ) ); if ( pickRay.intersectWherePlanarQuad( topLeft, topRight, bottomLeft, tuv ) ) { x = (int) ( ( tuv.y - 0.5f ) * width ) + desktopWidth / 2; y = (int) ( ( tuv.z - 0.5f ) * height ) + desktopHeight / 2; } else { x = -1; y = -1; } } lastYout = y; lastXout = x; store.set( x, y ); } } private void applyWorld( Vector3f point ) { getWorldRotation().multLocal( point.multLocal( getWorldScale() ) ).addLocal( getWorldTranslation() ); } /** * Find a component at specified desktop position. * * @param x x coordinate in Swing coordinate space * @param y y coordinate in Swing coordinate space * @return the top most component at specified location, null if no child component is found at that location */ public Component componentAt( int x, int y ) { Component component = componentAt( x, y, desktop, true ); if ( component != desktop ) { return component; } return null; } private Component componentAt( int x, int y, Component parent, boolean scanRootPanes ) { if ( scanRootPanes && parent instanceof JRootPane ) { JRootPane rootPane = (JRootPane) parent; parent = rootPane.getContentPane(); } Component child = parent; if ( !parent.contains( x, y ) ) { child = null; } else { synchronized ( parent.getTreeLock() ) { if ( parent instanceof Container ) { Container container = (Container) parent; int ncomponents = container.getComponentCount(); for ( int i = 0; i < ncomponents; i++ ) { Component comp = container.getComponent( i ); if ( comp != null && comp.isVisible() && ( dragAndDropSupport == null || !dragAndDropSupport.isDragPanel(comp) ) && comp.contains( x - comp.getX(), y - comp.getY() ) ) { child = comp; break; } } } } } if ( child != null ) { if ( parent instanceof JTabbedPane && child != parent ) { child = ( (JTabbedPane) parent ).getSelectedComponent(); } x -= child.getX(); y -= child.getY(); } return child != parent && child != null ? componentAt( x, y, child, scanRootPanes ) : child; } private void sendEnteredEvent( Component comp, Component lastComponent, int buttonMask, Point pos ) { if ( comp != null && comp != lastComponent ) { sendEnteredEvent( comp.getParent(), lastComponent, buttonMask, pos ); pos = convertPoint( lastComponent, pos.x, pos.y, comp ); final MouseEvent event = new MouseEvent( comp, MouseEvent.MOUSE_ENTERED, System.currentTimeMillis(), buttonMask, pos.x, pos.y, 0, false, 0 ); dispatchEvent( comp, event ); } } private void sendExitedEvent( Component lastComponent, int buttonMask, Point pos ) { final MouseEvent event = new MouseEvent( lastComponent, MouseEvent.MOUSE_EXITED, System.currentTimeMillis(), buttonMask, pos.x, pos.y, 1, false, 0 ); dispatchEvent( lastComponent, event ); } private final LockRunnable paintLockRunnable = new LockRunnable(); public void draw( Renderer r ) { if ( graphics.isDirty() ) { final boolean synchronizingThreadsOnUpdate = this.synchronizingThreadsOnUpdate; if ( synchronizingThreadsOnUpdate ) { synchronized ( paintLockRunnable ) { try { paintLockRunnable.wait = true; SwingUtilities.invokeLater( paintLockRunnable ); paintLockRunnable.wait( 100 ); } catch ( InterruptedException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "draw(Renderer r)", "Exception", e); } } } try { if ( graphics != null && texture.getTextureId() > 0) { graphics.update( texture ); } } finally { if ( synchronizingThreadsOnUpdate ) { synchronized ( paintLockRunnable ) { paintLockRunnable.notifyAll(); } } } } super.draw( r ); } public JDesktopPane getJDesktop() { return desktop; } public Component getFocusOwner() { if ( !focusCleared ) { return this.awtWindow.getFocusOwner(); } return null; } private class LockRunnable implements Runnable { private boolean wait = false; public void run() { synchronized ( paintLockRunnable ) { notifyAll(); if ( wait ) { try { //wait for repaint to finish wait = false; paintLockRunnable.wait( 200 ); } catch ( InterruptedException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "run()", "Exception", e); } } } } } private static class MyPopupFactory extends PopupFactory { private final PopupFactory defaultPopupFactory = new PopupFactory(); public Popup getPopup( Component owner, Component contents, int x, int y ) throws IllegalArgumentException { while ( !( owner instanceof JDesktopPane ) ) { owner = owner.getParent(); if ( owner == null ) { logger.warning("jME Popup creation failed, default popup created - desktop not found in component hierarchy of " + owner); return defaultPopupFactory.getPopup( owner, contents, x, y ); } } JMEDesktop.LightWeightPopup popup = new JMEDesktop.LightWeightPopup( (JComponent) owner ); popup.adjust( owner, contents, x, y ); return popup; } } private class ButtonAction extends InputAction { private final int swingButtonIndex; /** * @param swingButtonIndex button index sent in generated swing event, * InputHandler.BUTTON_ALL for mapping 0: MouseEvent.BUTTON1, 1: MouseEvent.BUTTON2, 2: MouseEvent.BUTTON3 */ public ButtonAction( int swingButtonIndex ) { this.swingButtonIndex = swingButtonIndex; } public void performAction( InputActionEvent evt ) { onButton( swingButtonIndex != InputHandler.BUTTON_ALL ? swingButtonIndex : getSwingButtonIndex( evt.getTriggerIndex() ), evt.getTriggerPressed(), lastXin, lastYin ); } } private int getSwingButtonIndex( int jmeButtonIndex ) { switch ( jmeButtonIndex ) { case 0: return MouseEvent.BUTTON1; case 1: return MouseEvent.BUTTON2; case 2: return MouseEvent.BUTTON3; default: return MouseEvent.NOBUTTON; //todo: warn here? } } private class XUpdateAction extends InputAction { public XUpdateAction() { setSpeed( 1 ); } public void performAction( InputActionEvent evt ) { int screenWidth = DisplaySystem.getDisplaySystem().getWidth(); onMove( (int) ( screenWidth * evt.getTriggerDelta() * getSpeed() ), 0, (int) ( screenWidth * evt.getTriggerPosition() * getSpeed() ), lastYin ); } } private class YUpdateAction extends InputAction { public YUpdateAction() { setSpeed( 1 ); } public void performAction( InputActionEvent evt ) { int screenHeight = DisplaySystem.getDisplaySystem().getHeight(); onMove( 0, (int) ( screenHeight * evt.getTriggerDelta() * getSpeed() ), lastXin, (int) ( screenHeight * evt.getTriggerPosition() * getSpeed() ) ); } } private class WheelUpdateAction extends InputAction { public WheelUpdateAction() { setSpeed( 1 ); } public void performAction( InputActionEvent evt ) { onWheel( (int) ( evt.getTriggerDelta() * getSpeed() ), lastXin, lastYin ); } } private class KeyUpdateAction extends InputAction { public void performAction( InputActionEvent evt ) { onKey( evt.getTriggerCharacter(), evt.getTriggerIndex(), evt.getTriggerPressed() ); } } /** * @return current modal component * @see #setModalComponent(java.awt.Component) */ public Component getModalComponent() { return this.modalComponent; } /** * @see #setModalComponent(java.awt.Component) */ private Component modalComponent; /** * Filter the swing event to allow events to the specified component and its children only. * Note: this does not prevent shortcuts and mnemonics to work for the other components! * * @param value component that can be exclusively accessed (including children) */ public void setModalComponent( final Component value ) { this.modalComponent = value; } protected void setParent( Node parent ) { if ( desktop != null ) { super.setParent( parent ); } else { throw new IllegalStateException( "already disposed" ); } } /** * Call this method of the desktop is no longer needed. Removes this from the scenegraph, later use is not * possible any more. */ public void dispose() { if ( desktop != null ) { if ( getParent() != null ) { getParent().detachChild( this ); } inputHandler.removeAllActions(); if ( inputHandler.getParent() != null ) { inputHandler.getParent().removeFromAttachedHandlers( inputHandler ); } try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { desktop.removeAll(); awtWindow.dispose(); } } ); } catch ( InterruptedException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "dispose()", "Exception", e); } catch ( InvocationTargetException e ) { logger.logp(Level.SEVERE, this.getClass().toString(), "dispose()", "Exception", e); } desktop = null; desktopsUsed if ( desktopsUsed == 0 ) { PopupFactory.setSharedInstance( new PopupFactory() ); } } } private static class ScrollPaneRepaintFixListener implements ContainerListener { public void componentAdded( ContainerEvent e ) { Component child = e.getChild(); componentAdded( child ); } private void componentAdded( Component child ) { if ( child instanceof Container ) { Container container = (Container) child; addTo( container ); container.addContainerListener( this ); } if ( child instanceof JScrollPane ) { final JScrollPane scrollPane = (JScrollPane) child; // note: the listener added here is only a fix for repaint problems with scrolling subscribeRepaintListener( scrollPane.getViewport() ); } } private void addTo( Container container ) { container.addContainerListener( this ); for ( int i = 0; i < container.getComponentCount(); i++ ) { componentAdded( container.getComponent( i ) ); } } private void removeFrom( Container container ) { container.removeContainerListener( this ); for ( int i = 0; i < container.getComponentCount(); i++ ) { componentRemoved( container.getComponent( i ) ); } } private void subscribeRepaintListener( JViewport viewport ) { for ( int i = 0; i < viewport.getChangeListeners().length; i++ ) { ChangeListener listener = viewport.getChangeListeners()[i]; if ( listener instanceof ScrollPaneRepaintChangeListener ) { // listener already subscribed return; } } viewport.addChangeListener( new ScrollPaneRepaintChangeListener( viewport ) ); } public void componentRemoved( ContainerEvent e ) { Component child = e.getChild(); componentRemoved( child ); } private void componentRemoved( Component child ) { if ( child instanceof Container ) { Container container = (Container) child; removeFrom( container ); } } private static class ScrollPaneRepaintChangeListener implements ChangeListener { private final Component component; public ScrollPaneRepaintChangeListener( Component component ) { this.component = component; } public void stateChanged( ChangeEvent e ) { component.repaint(); } } } /** * not supported. * @param width - * @param height - */ public void resize( float width, float height ) { //TODO: implement resizing? throw new UnsupportedOperationException( "resizing JMEDesktop not yet implemented!" ); } }
package com.miviclin.droidengine2d; import android.app.Activity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import com.miviclin.droidengine2d.graphics.GLView; import com.miviclin.droidengine2d.graphics.cameras.Camera; import com.miviclin.droidengine2d.graphics.cameras.OrthographicCamera; import com.miviclin.droidengine2d.graphics.sprites.SpriteBatch; import com.miviclin.droidengine2d.graphics.textures.TextureManager; /** * Game.<br> * Clase base que representa un juego. * * @author Miguel Vicente Linares * */ public abstract class Game implements OnClickListener, OnLongClickListener, OnKeyListener, OnTouchListener { private final String name; private final Activity activity; private final GLView glView; private final TextureManager textureManager; private Camera camera; /** * Constructor * * @param name Nombre del juego * @param activity Activity en la que se ejecuta el juego */ public Game(String name, Activity activity) { this(name, new GLView(activity), activity); } /** * Constructor * * @param name Nombre del juego * @param glView GLView en la que se representara el juego * @param activity Activity en la que se ejecuta el juego */ public Game(String name, GLView glView, Activity activity) { if (activity == null) { throw new IllegalArgumentException("The Activity can not be null"); } this.name = name; this.activity = activity; this.glView = glView; this.textureManager = new TextureManager(activity); this.camera = new OrthographicCamera(); } /** * Devuelve el nombre del juego * * @return */ public String getName() { return name; } /** * Devuelve la Activity en la que se ejecuta el juego * * @return Activity en la que se ejecuta el juego */ public Activity getActivity() { return activity; } /** * Devuelve el ancho del View en el que se representa el juego * * @return ancho del View en el que se representa el juego */ public int getGameViewWidth() { return glView.getWidth(); } /** * Devuelve el alto del View en el que se representa el juego * * @return alto del View en el que se representa el juego */ public int getGameViewHeight() { return glView.getHeight(); } /** * Devuelve el GLView en el que se representa el juego.<br> * Este metodo se utiliza internamente en el engine para configurar el GLView. * * @return GLView en el que se representa el juego */ GLView getGLView() { return glView; } /** * Devuelve el TextureManager. * * @return TextureManager */ public TextureManager getTextureManager() { return textureManager; } /** * Devuelve la camara. * * @return Camera */ public Camera getCamera() { return camera; } /** * Asigna una nueva camara al juego. * * @param camera Nueva camara. No puede ser null */ public void setCamera(Camera camera) { if (camera == null) { throw new IllegalArgumentException("The camera can not be null"); } this.camera = camera; } /** * Registra este juego para que sea notificado cuando se produzcan eventos Click sobre la View en el que se desarrolla el juego. */ public void enableClickListener() { glView.setOnClickListener(this); } /** * Si este juego estaba registrado para ser notificado de los eventos Click que se produjeran en la View en la que se desarrolla el * juego, dejara de estarlo tras llamar a este metodo. */ public void disableClickListener() { glView.setOnClickListener(null); } /** * Registra este juego para que sea notificado cuando se produzcan eventos LongClick sobre la View en el que se desarrolla el juego. */ public void enableLongClickListener() { glView.setOnLongClickListener(this); } /** * Si este juego estaba registrado para ser notificado de los eventos LongClick que se produjeran en la View en la que se desarrolla el * juego, dejara de estarlo tras llamar a este metodo. */ public void disableLongClickListener() { glView.setOnLongClickListener(null); } /** * Registra este juego para que sea notificado cuando se produzcan eventos Key sobre la View en el que se desarrolla el juego. */ public void enableKeyListener() { glView.setOnKeyListener(this); } /** * Si este juego estaba registrado para ser notificado de los eventos Key que se produjeran en la View en la que se desarrolla el juego, * dejara de estarlo tras llamar a este metodo. */ public void disableKeyListener() { glView.setOnKeyListener(null); } /** * Registra este juego para que sea notificado cuando se produzcan eventos Touch sobre la View en el que se desarrolla el juego. */ public void enableTouchListener() { glView.setOnTouchListener(this); } /** * Si este juego estaba registrado para ser notificado de los eventos Touch que se produjeran en la View en la que se desarrolla el * juego, dejara de estarlo tras llamar a este metodo. */ public void disableTouchListener() { glView.setOnTouchListener(null); } /** * Se llama cuando en la View en la que se produce un evento Click.<br> * Para que este metodo sea llamado, se debe haber registrado este juego para que reciba eventos Click mediante una llamada a * {@link Game#enableClickListener()}<br> * Por defecto este metodo no realiza ninguna accion. Sobreescribir si es necesario. * * @param v La View en la que se ha hecho click */ @Override public void onClick(View v) { } /** * Se llama cuando en la View en la que se produce un evento LongClick.<br> * Para que este metodo sea llamado, se debe haber registrado este juego para que reciba eventos LongClick mediante una llamada a * {@link Game#enableLongClickListener()}<br> * Por defecto este metodo no realiza ninguna accion. Sobreescribir si es necesario. * * @param v La View en la que se ha hecho click * @return true si el callback consume el evento, false en caso contrario */ @Override public boolean onLongClick(View v) { return false; } /** * Se llama cuando en la View en la que se produce un evento Key.<br> * Para que este metodo sea llamado, se debe haber registrado este juego para que reciba eventos Key mediante una llamada a * {@link Game#enableKeyListener()}<br> * Por defecto este metodo no realiza ninguna accion. Sobreescribir si es necesario. * * @param v La View en la que se ha hecho click * @param keyCode Codigo que identifica la tecla fisica pulsada * @param event KeyEvent que contiene la informacion del evento * @return true si el listener consume el evento, false en caso contrario */ @Override public boolean onKey(View v, int keyCode, KeyEvent event) { return false; } /** * Se llama cuando en la View en la que se produce un evento Touch.<br> * Para que este metodo sea llamado, se debe haber registrado este juego para que reciba eventos Key mediante una llamada a * {@link Game#enableTouchListener()}<br> * Por defecto este metodo no realiza ninguna accion. Sobreescribir si es necesario. * * @param v La View en la que se ha hecho click * @param event MotionEvent que contiene la informacion del evento * @return true si el listener consume el evento, false en caso contrario */ @Override public boolean onTouch(View v, MotionEvent event) { return false; } /** * Llamado por {@link Engine#onBackPressed()}<br> * Destruye la Activity en la que se ejecuta el juego.<br> * Sobreescribir este metodo para implementar acciones que deban ejecutarse al pulsar el boton BACK del dispositivo */ public void onBackPressed() { getActivity().finish(); } /** * Se llama cuando se pausa el GameThread, normalmente debido a que la Activity recibe una llamada a onPause() */ public abstract void onEnginePaused(); /** * Se llama cuando se reanuda el GameThread tras haber sido pausado, normalmente debido a que la Activity recibe una llamada a * onResume() */ public abstract void onEngineResumed(); /** * Se llama cuando se para el GameThread, normalmente debido a que la Activity ha sido destruida. */ public abstract void onEngineDisposed(); /** * Actualiza la logica del juego.<br> * Este metodo es llamado periodicamente por GameThread. * * @param delta Tiempo transcurrido, en milisegundos, desde la ultima actualizacion. */ public abstract void update(float delta); /** * Renderiza los elementos del juego de forma que puedan verse en pantalla.<br> * Este metodo se ejecuta en el hilo del GLRenderer tras ejecutar {@link #update(float)} en el GameThread */ public abstract void draw(SpriteBatch spriteBatch); }
package com.relteq.sirius.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.apache.commons.configuration.BaseConfiguration; public class Parameters { /** The database type: <code>derby</code>, <code>postgresql</code>, etc */ private String driver; private String db_name; private String host; private String port; private String user; private String password; private static final String default_db_name = "sirius"; private static final String default_host = "localhost"; /** * @return the driver */ public String getDriver() { return driver; } /** * @param driver the driver to set */ public void setDriver(String driver) { this.driver = driver; } /** * @return the database name */ public String getDb_name() { return db_name; } /** * @param db_name the database name to set */ public void setDb_name(String db_name) { this.db_name = db_name; } /** * @return the host */ public String getHost() { return host; } /** * @param host the host to set */ public void setHost(String host) { this.host = host; } /** * @return the port */ public String getPort() { return port; } /** * @param port the port to set */ public void setPort(String port) { this.port = port; } /** * @return the user */ public String getUser() { return user; } /** * @param user the user to set */ public void setUser(String user) { this.user = user; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } private Parameters() {} /** * Initializes the DB parameters from the environment * @return the parameters */ public static Parameters get() { Parameters params = new Parameters(); String driver = System.getenv("SIRIUS_DB"); if (null == driver) driver = "derby"; params.setDriver(driver); String db_name = System.getenv("SIRIUS_DB_NAME"); if (null == db_name) db_name = default_db_name; params.setDb_name(db_name); params.setHost(System.getenv("SIRIUS_DB_HOST")); params.setPort(System.getenv("SIRIUS_DB_PORT")); if (null == params.getHost() && null != params.getPort()) params.setHost(default_host); params.setUser(System.getenv("SIRIUS_DB_USER")); params.setPassword(System.getenv("SIRIUS_DB_PASSWORD")); return params; } /** * @return the database connection URL */ public String getUrl() { StringBuilder url = new StringBuilder("jdbc:"); url.append(driver).append(":"); if (driver.equals("postgresql") && (null != host)) { url.append("//").append(host); if (null != port) url.append(":").append(port); url.append("/"); } url.append(db_name); if (driver.equals("derby")) url.append(";create=true"); return url.toString(); } /** * @return a list of connection arguments, such as "user" and "password" */ public Properties getConnectionProperties() { Properties props = new Properties(); if (null != getUser()) props.put("user", getUser()); if (null != getPassword()) props.put("password", getPassword()); return props; } /** * Establishes a database connection * @return a database connection * @throws SQLException */ public Connection getConnection() throws SQLException { return DriverManager.getConnection(getUrl(), getConnectionProperties()); } public org.apache.commons.configuration.Configuration toConfiguration() { BaseConfiguration conf = new BaseConfiguration(); conf.addProperty("torque.database.default", "sirius"); conf.addProperty("torque.database.sirius.adapter", getDriver()); conf.addProperty("torque.dsfactory.sirius.factory", "org.apache.torque.dsfactory.SharedPoolDataSourceFactory"); conf.addProperty("torque.dsfactory.sirius.connection.url", getUrl()); if (null != getUser()) conf.addProperty("torque.dsfactory.sirius.connection.user", getUser()); if (null != getPassword()) conf.addProperty("torque.dsfactory.sirius.connection.password", getPassword()); return conf; } }
package com.spiral.gallery; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.imageaware.ImageAware; import android.content.Context; import android.graphics.Bitmap; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; public class AlbumAdapter extends BaseAdapter { private static final String TAG = "AlbumAdapter"; /* Fields of every JSONObject contained in the JSONArray data */ public static final String URI_THUMBNAIL = "src_small"; public static final String URI_BIG = "src_big"; public static final String URI_CAPTION = "caption"; /* Context needed to get hold of system services */ private Context mContext; /* The actual data source, containing all url for the images */ private JSONArray mArray; /* Image loader */ private ImageLoader mImageLoader; /* Customized options for the image loading procedure */ private DisplayImageOptions options; public AlbumAdapter(Context context, ImageLoader l){ mContext = context; mImageLoader = l; } public AlbumAdapter(Context context, ImageLoader l, JSONArray array){ mContext = context; mImageLoader = l; mArray = array; } public void setData(JSONArray array){ mArray = array; } private void setupOptions(){ /* Options specify different properties of the dynamic image loading procedure */ options = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_stub) .showImageForEmptyUri(R.drawable.ic_empty) .showImageOnFail(R.drawable.ic_error) .cacheInMemory(true) .cacheOnDisc(true) // .considerExifParams(true) .bitmapConfig(Bitmap.Config.RGB_565) .build(); } @Override public int getCount() { if(mArray == null) return 0; else return mArray.length(); } @Override public Object getItem(int position) { Object element = null; try { element = mArray.get(position); } catch (JSONException e) { Log.e(TAG,"JSONException. Msg: "+e.getMessage()); } catch(NullPointerException e){ Log.e(TAG,"NullPointerException. Msg: "+e.getMessage()); } return element; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if(convertView == null){ LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageView = (ImageView) inflater.inflate(R.layout.item_grid_image, parent, false); }else{ imageView = (ImageView) convertView; imageView.setImageResource(R.drawable.ic_empty); } try { JSONObject element; element = (JSONObject) mArray.get(position); String uri = element.getString(URI_THUMBNAIL); if(mImageLoader.getMemoryCache().get(uri) != null){ Log.d(TAG, "Getting image from cache"); imageView.setImageBitmap(mImageLoader.getMemoryCache().get(uri)); }else{ mImageLoader.displayImage(uri, imageView, options); Log.d(TAG,"Getting image from network. Mem cache has size: "+mImageLoader.getMemoryCache().keys().size()); } } catch (JSONException e) { Log.e(TAG,"JSONException at calling the get method on an JSONArray. Msg: "+e.getMessage()); } return imageView; } }
package com.untamedears.civchat; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; /* * Coded by Rourke750 & ibbignerd */ public class CivChat extends JavaPlugin implements Listener { private ChatManager chat = null; private ChatListener cl = null; private FileConfiguration config = null; public void onEnable() { config = getConfig(); initConfig(); this.saveConfig(); chat = new ChatManager(this); cl = new ChatListener(chat); registerEvents(); Commands commands = new Commands(chat, this); for (String command : getDescription().getCommands().keySet()) { getCommand(command).setExecutor(commands); } } public void initConfig() { config.options().header("Authors: Rourke750, ibbignerd" + "\n Last updated on 06/20/13" + "\nThis plugin was designed for use by Civcraft" + "\n \n " + "variation: The range from 0-value added to the garble to make it more random" + "\n defaultcolor: Default color of chat. Must use a ChatColor.COLOR option" + "\n greyscale: Chat changes for reciever based on distance. Configured below" + "\n yvariation: The higher the sender is, the farther the max chat range." + "\n noGarbLevel: At what y level (and above) will the yvariation come into effect?" + "\n shout: Expand max range based on number of shout chars" + "\n char: character uesd at the beginning of the message" + "\n distanceAdded: Amount added to the max range to make chat go further" + "\n hungerreduced: Amount of hunger reduced per shout char." + "\n whisper: Reduced chat range when whisper char is used" + "\n char: Character used at the beginning of the message" + "\n distance: set distance a whisper is heard" + "\n color: configurable color for whisper messages" + "\n range: currently has 3 configurable distances" + "\n distance: subtraced from maxrange (e.g. maxrange = 1000, " + "\n distance = 100, from 900-1000 is the range)" + "\n garble: Integer as a percent. (garble: 5 = 5% of string will be garbled)" + "\n color: Color of chat for this range" + "\n maxrange: Max distance a player can be heard"); if (!config.contains("chat.garblevariation")) { config.set("chat.variation", 5); } if (!config.contains("chat.defaultcolor")) { config.set("chat.defaultcolor", "WHITE"); } if (!config.contains("chat.greyscale")) { config.set("chat.greyscale", false); } if (!config.contains("chat.yvariation.enabled")) { config.set("chat.yvariation.enabled", true); } if (!config.contains("chat.yvariation.noGarbLevel")) { config.set("chat.yvariation.noGarbLevel", 70); } if (!config.contains("chat.shout.enabled")) { config.set("chat.shout.enabled", true); } if (!config.contains("chat.shout.char")) { config.set("chat.shout.char", "!"); } if (!config.contains("chat.shout.distanceAdded")) { config.set("chat.shout.distanceAdded", 100); } if (!config.contains("chat.shout.hungerreduced")) { config.set("chat.shout.hungerreduced", 2); } if (!config.contains("chat.whisper.enabled")) { config.set("chat.whisper.enabled", true); } if (!config.contains("chat.whisper.char")) { config.set("chat.whisper.char", " } if (!config.contains("chat.whisper.distance")) { config.set("chat.whisper.distance", 50); } if (!config.contains("chat.whisper.color")) { config.set("chat.whisper.color", "WHITE"); } if (!config.contains("chat.range.0.distance")) { config.set("chat.range.0.distance", 500); } if (!config.contains("chat.range.0.garble")) { config.set("chat.range.0.garble", 5); } if (!config.contains("chat.range.0.color")) { config.set("chat.range.0.color", "GRAY"); } if (!config.contains("chat.range.1.distance")) { config.set("chat.range.1.distance", 350); } if (!config.contains("chat.range.1.garble")) { config.set("chat.range.1.garble", 15); } if (!config.contains("chat.range.1.color")) { config.set("chat.range.1.color", "GRAY"); } if (!config.contains("chat.range.2.distance")) { config.set("chat.range.2.distance", 200); } if (!config.contains("chat.range.2.garble")) { config.set("chat.range.2.garble", 35); } if (!config.contains("chat.range.2.color")) { config.set("chat.range.2.color", "DARK_GRAY"); } if (!config.contains("chat.range.maxrange")) { config.set("chat.range.maxrange", 1000); } } private void registerEvents() { getServer().getPluginManager().registerEvents(cl, this); } }
package com.willhains.equality; import static java.util.stream.Collectors.*; import java.lang.reflect.*; import java.util.*; import java.util.function.*; import java.util.stream.*; /** * A fast, safe, helpful utility for implementing {@link Object#equals} and * {@link Object#hashCode} easily and correctly. See {@link #ofProperties} for * usage. * <p> * Note: {@link #equals}, {@link #hashCode}, and {@link #toString} all throw * {@link UnsupportedOperationException}, to avoid accidental incorrect usage. * * @param <T> your class. * @author willhains */ public final class Equality<T> { private final Function<T, ?>[] _properties; private Equality(final Function<T, ?>[] properties) { _properties = properties; } /** * Create an {@link Equality} instance for your class, by supplying an array * of functions for retrieving the values of significant instance variables. * <pre> * private static final Equality&lt;MyClass&gt; EQ = Equality.ofProperties( * $ -> $.instanceVariable1, * $ -> $.instanceVariable2); // etc. * </pre> * See {@link #compare} and {@link #hash} for how to use this in your * {@link Object#equals} and {@link Object#hashCode} implementations. */ @SafeVarargs public static <T> Equality<T> ofProperties(final Function<T, ?>... properties) { return new Equality<>(properties); } /** @see #ofProperties(Function...) */ public static <T> Equality<T> ofProperties(final Function<T, ?> property) { final Function<T, ?>[] properties = new Function[] {property}; return ofProperties(properties); } /** * Reflection-based alternative to {@link #ofProperties}. * Using this method has the advantage that new properties added to your * class later will be automatically included, and the disadvantage that * performance may be slower due to reflection overhead. * <pre> * private static final Equality&lt;MyClass&gt; EQ = Equality.reflect(MyClass.class); * </pre> * * @see #ofProperties(Function...) */ public static <T> Equality<T> reflect(final Class<T> type) { final Function<Field, Function<T, ?>> fieldToPropertyAccessor = field -> instance -> { try { return field.get(instance); } catch(final IllegalAccessException e) { // No choice but to convert to runtime exception throw new RuntimeException(e); } }; final Function<T, ?>[] properties = Arrays .stream(type.getDeclaredFields()) .filter(field -> !Modifier.isStatic(field.getModifiers())) .map(fieldToPropertyAccessor) .toArray(Function[]::new); return ofProperties(properties); } /** * Compare {@code self} to {@code other} for equality. * <pre> * public boolean equals(Object other) { return EQ.compare(this, other); } * </pre> */ public boolean compare(final T self, final Object other) { if(other == self) return true; if(other == null) return false; if(!self.getClass().equals(other.getClass())) return false; final T that = (T)other; for(final Function<T, ?> property : _properties) { final Object v1 = property.apply(self); final Object v2 = property.apply(that); if(v1 == v2) continue; if(v1 == null || v2 == null) return false; if(v1.equals(v2)) continue; if(v1 instanceof boolean[] && Arrays.equals((boolean[])v1, (boolean[])v2)) continue; if(v1 instanceof byte[] && Arrays.equals((byte[])v1, (byte[])v2)) continue; if(v1 instanceof short[] && Arrays.equals((short[])v1, (short[])v2)) continue; if(v1 instanceof char[] && Arrays.equals((char[])v1, (char[])v2)) continue; if(v1 instanceof int[] && Arrays.equals((int[])v1, (int[])v2)) continue; if(v1 instanceof long[] && Arrays.equals((long[])v1, (long[])v2)) continue; if(v1 instanceof float[] && Arrays.equals((float[])v1, (float[])v2)) continue; if(v1 instanceof double[] && Arrays.equals((double[])v1, (double[])v2)) continue; if(v1 instanceof Object[] && Arrays.deepEquals((Object[])v1, (Object[])v2)) continue; return false; } return true; } /** * Compute a hash code for {@code self}. * <pre> * public int hashCode() { return EQ.hash(this); } * </pre> */ public int hash(final T self) { // Modified form of Joshua Bloch's hash algorithm int hash = 17; hash += 13 * self.getClass().hashCode(); for(final Function<T, ?> property : _properties) { final Object value = property.apply(self); final int propertyHash; if(value == null) propertyHash = 7; else if(value instanceof Object[]) propertyHash = Arrays.deepHashCode((Object[])value); else if(value instanceof int[]) propertyHash = Arrays.hashCode((int[])value); else if(value instanceof long[]) propertyHash = Arrays.hashCode((long[])value); else if(value instanceof boolean[]) propertyHash = Arrays.hashCode((boolean[])value); else if(value instanceof double[]) propertyHash = Arrays.hashCode((double[])value); else if(value instanceof float[]) propertyHash = Arrays.hashCode((float[])value); else if(value instanceof char[]) propertyHash = Arrays.hashCode((char[])value); else if(value instanceof byte[]) propertyHash = Arrays.hashCode((byte[])value); else if(value instanceof short[]) propertyHash = Arrays.hashCode((short[])value); else propertyHash = value.hashCode(); hash = 37 * hash + propertyHash; } return hash; } /** * Build a simple, pipe-delimited string representation for {@code self}, * useful for {@link Object#toString()} implementations. * <pre> * public String toString() { return EQ.format(this); } * </pre> */ public String format(final T self) { return Stream.of(_properties) .map($ -> $.apply(self)) .map(value -> { if(value == null) return "null"; else if(value instanceof Object[]) return Arrays.toString((Object[])value); else if(value instanceof int[]) return Arrays.toString((int[])value); else if(value instanceof long[]) return Arrays.toString((long[])value); else if(value instanceof boolean[]) return Arrays.toString((boolean[])value); else if(value instanceof double[]) return Arrays.toString((double[])value); else if(value instanceof float[]) return Arrays.toString((float[])value); else if(value instanceof char[]) return Arrays.toString((char[])value); else if(value instanceof byte[]) return Arrays.toString((byte[])value); else if(value instanceof short[]) return Arrays.toString((short[])value); else return String.valueOf(value); }) .collect(joining("|")); } /** * Build a formatted string representation for {@code self}, * using the specified {@linkplain Formatter format string}. * <pre> * public String toString() { return EQ.format(this, "%s: %,d (%s)"); } * </pre> * Note: The properties of {@code self} will be applied to the format string * in the order they are given to {@link #ofProperties}. */ public String format(final T self, final String formatString) { return String.format( formatString, Stream.of(_properties).map($ -> $.apply(self)).toArray(Object[]::new)); } /** * Do not use this method; call {@link #hash(Object) hash(this)} instead! * * @throws UnsupportedOperationException always. * @see #hash(Object) */ @Override public int hashCode() { throw new UnsupportedOperationException("Use hash(this) to compute your hash code"); } /** * Do not use this method; call {@link #compare(Object, Object) * compare(this, other)} instead! * * @throws UnsupportedOperationException always * @see #compare(Object, Object) */ @Override public boolean equals(final Object obj) { throw new UnsupportedOperationException("Use compare(this, other) to test for equality"); } /** * Do not use this method; call {@link #format(Object) format(this)} or * {@link #format(Object, String) format(this, "format string"} * instead! * * @throws UnsupportedOperationException always * @see #format(Object) * @see #format(Object, String) */ @Override public String toString() { throw new UnsupportedOperationException("Use format(this) to build your string"); } }
package org.lwjgl.opengl; public abstract class GLContext { final ContextCapabilities capabilities; protected GLContext(ContextCapabilities capabilities) { this.capabilities = capabilities; GL.setCurrent(this); } public ContextCapabilities getCapabilities() { return capabilities; } public void makeCurrent() { makeCurrentImpl(); GL.setCurrent(this); } protected abstract void makeCurrentImpl(); public abstract boolean isCurrent(); public void destroy() { // Clean-up callbacks if ( capabilities.GL_AMD_debug_output && capabilities.__AMDDebugOutput.DEBUGPROCAMD != 0L ) AMDDebugOutput.glDebugMessageCallbackAMD(null); if ( capabilities.OpenGL43 && capabilities.__GL43.DEBUGPROC != 0L ) GL43.glDebugMessageCallback(null); destroyImpl(); } public abstract void destroyImpl(); }
package de.st_ddt.crazylogin; import java.io.File; import java.security.NoSuchAlgorithmException; import java.util.List; import org.bukkit.OfflinePlayer; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import de.st_ddt.crazylogin.crypt.AuthMeCrypt; import de.st_ddt.crazylogin.crypt.CrazyCrypt1; import de.st_ddt.crazylogin.crypt.CustomEncryptor; import de.st_ddt.crazylogin.crypt.DefaultCrypt; import de.st_ddt.crazylogin.crypt.Encryptor; import de.st_ddt.crazylogin.crypt.PlainCrypt; import de.st_ddt.crazylogin.crypt.WhirlPoolCrypt; import de.st_ddt.crazylogin.databases.CrazyLoginConfigurationDatabase; import de.st_ddt.crazylogin.databases.CrazyLoginFlatDatabase; import de.st_ddt.crazylogin.databases.CrazyLoginMySQLDatabase; import de.st_ddt.crazyplugin.CrazyPlugin; import de.st_ddt.crazyplugin.exceptions.CrazyCommandException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandExecutorException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandNoSuchException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandParameterException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandPermissionException; import de.st_ddt.crazyplugin.exceptions.CrazyCommandUsageException; import de.st_ddt.crazyplugin.exceptions.CrazyException; import de.st_ddt.crazyutil.ChatHelper; import de.st_ddt.crazyutil.ObjectSaveLoadHelper; import de.st_ddt.crazyutil.PairList; import de.st_ddt.crazyutil.databases.Database; import de.st_ddt.crazyutil.databases.MySQLConnection; public class CrazyLogin extends CrazyPlugin { private static CrazyLogin plugin; protected final PairList<String, LoginPlayerData> datas = new PairList<String, LoginPlayerData>(); private CrazyLoginPlayerListener playerListener; private CrazyLoginVehicleListener vehicleListener; protected boolean alwaysNeedPassword; protected boolean autoLogout; protected int autoKick; protected List<String> commandWhiteList; protected boolean autoKickCommandUsers; protected String uniqueIDKey; protected boolean doNotSpamRequests; protected boolean forceSingleSession; protected Encryptor encryptor; // Database protected String saveType; protected String tableName; protected Database<LoginPlayerData> database; public static CrazyLogin getPlugin() { return plugin; } @Override public void onEnable() { plugin = this; registerHooks(); super.onEnable(); } public void registerHooks() { this.playerListener = new CrazyLoginPlayerListener(this); this.vehicleListener = new CrazyLoginVehicleListener(this); PluginManager pm = this.getServer().getPluginManager(); pm.registerEvents(playerListener, this); pm.registerEvents(vehicleListener, this); } @Override public void load() { super.load(); FileConfiguration config = getConfig(); autoLogout = config.getBoolean("autoLogout", false); alwaysNeedPassword = config.getBoolean("alwaysNeedPassword", true); autoKick = Math.max(config.getInt("autoKick", -1), -1); doNotSpamRequests = config.getBoolean("doNotSpamRequests", false); commandWhiteList = config.getStringList("commandWhitelist"); autoKickCommandUsers = config.getBoolean("autoKickCommandUsers", false); forceSingleSession = config.getBoolean("forceSingleSession", true); if (commandWhiteList.size() == 0) { commandWhiteList.add("/login"); commandWhiteList.add("/register"); commandWhiteList.add("/crazylogin password"); } uniqueIDKey = config.getString("uniqueIDKey"); String algorithm = config.getString("algorithm", "CrazyCrypt1"); if (algorithm.equalsIgnoreCase("CrazyCrypt1")) { encryptor = new CrazyCrypt1(); } else if (algorithm.equalsIgnoreCase("Whirlpool")) { encryptor = new WhirlPoolCrypt(); } else if (algorithm.equalsIgnoreCase("Plaintext")) { encryptor = new PlainCrypt(); } else if (algorithm.equalsIgnoreCase("AuthMe")) { encryptor = new AuthMeCrypt(); } else if (algorithm.equalsIgnoreCase("Custom")) { String encryption = config.getString("customEncryptor.class"); encryptor = ObjectSaveLoadHelper.load(encryption, CustomEncryptor.class, new Class[0], new Object[0]); } else { try { encryptor = new DefaultCrypt(algorithm); } catch (NoSuchAlgorithmException e) { broadcastLocaleMessage(true, false, "crazylogin.warnalgorithm", "ALGORITHM.MISSING", algorithm); encryptor = new CrazyCrypt1(); } } setupDatabase(); datas.clear(); if (database != null) for (LoginPlayerData data : database.getAllEntries()) datas.setDataVia1(data.getName().toLowerCase(), data); } public void setupDatabase() { FileConfiguration config = getConfig(); saveType = config.getString("database.saveType", "flat").toLowerCase(); tableName = config.getString("database.tableName", "players"); // Columns String colName = config.getString("database.columns.name", "name"); config.set("database.columns.name", colName); String colPassword = config.getString("database.columns.password", "password"); config.set("database.columns.password", colPassword); String colIPs = config.getString("database.columns.ips", "ips"); config.set("database.columns.ips", colIPs); try { if (saveType.equals("config")) { database = new CrazyLoginConfigurationDatabase(config, tableName, colName, colPassword, colIPs); } else if (saveType.equals("mysql")) { String host = config.getString("database.host", "localhost"); config.set("database.host", host); String port = config.getString("database.port", "3306"); config.set("database.port", port); String databasename = config.getString("database.dbname", "Crazy"); config.set("database.dbname", databasename); String user = config.getString("database.user", "root"); config.set("database.user", user); String password = config.getString("database.password", ""); config.set("database.password", password); MySQLConnection connection = new MySQLConnection(host, port, databasename, user, password); database = new CrazyLoginMySQLDatabase(connection, tableName, colName, colPassword, colIPs); } else if (saveType.equals("flat")) { File file = new File(getDataFolder().getPath() + "/" + tableName + ".db"); database = new CrazyLoginFlatDatabase(file, colName, colPassword, colIPs); } } catch (Exception e) { e.printStackTrace(); database = null; } finally { if (database == null) broadcastLocaleMessage(true, false, "crazylogin.warndatabase", "CRAZYLOGIN.DATABASE.ACCESSWARN", saveType); } } @Override public void save() { FileConfiguration config = getConfig(); config.set("database.saveType", saveType); config.set("database.tableName", tableName); if (database != null) database.saveAll(datas.getData2List()); saveConfiguration(); super.save(); } public void saveConfiguration() { ConfigurationSection config = getConfig(); config.set("alwaysNeedPassword", alwaysNeedPassword); config.set("autoLogout", autoLogout); config.set("autoKick", autoKick); config.set("doNotSpamRequests", doNotSpamRequests); config.set("commandWhitelist", commandWhiteList); config.set("autoKickCommandUsers", autoKickCommandUsers); config.set("uniqueIDKey", uniqueIDKey); config.set("algorithm", encryptor.getAlgorithm()); } @Override public boolean command(final CommandSender sender, final String commandLabel, final String[] args) throws CrazyException { if (commandLabel.equalsIgnoreCase("login")) { commandLogin(sender, args); return true; } if (commandLabel.equalsIgnoreCase("logout")) { commandLogout(sender, args); return true; } if (commandLabel.equalsIgnoreCase("register")) { commandMainPassword(sender, args); return true; } return false; } private void commandLogin(final CommandSender sender, final String[] args) throws CrazyCommandException { if (sender instanceof ConsoleCommandSender) throw new CrazyCommandExecutorException(false); if (args.length == 0) throw new CrazyCommandUsageException("/login <Passwort...>"); Player player = (Player) sender; String password = ChatHelper.listToString(args); LoginPlayerData data = datas.findDataVia1(player.getName().toLowerCase()); if (data == null) { sendLocaleMessage("REGISTER.HEADER", player); sendLocaleMessage("REGISTER.MESSAGE", player); return; } if (!data.login(password)) { sendLocaleMessage("LOGIN.FAILED", player); broadcastLocaleMessage(true, false, "crazylogin.warnloginfailure", "LOGIN.FAILEDWARN", player.getName(), player.getAddress().getAddress().getHostAddress()); return; } sendLocaleMessage("LOGIN.SUCCESS", player); data.addIP(player.getAddress().getAddress().getHostAddress()); if (database != null) database.save(data); } private void commandLogout(final CommandSender sender, final String[] args) throws CrazyCommandException { if (sender instanceof ConsoleCommandSender) throw new CrazyCommandExecutorException(false); Player player = (Player) sender; if (!isLoggedIn(player)) throw new CrazyCommandPermissionException(); LoginPlayerData data = datas.findDataVia1(player.getName().toLowerCase()); if (data != null) data.logout(); player.kickPlayer(locale.getLanguageEntry("LOGOUT.SUCCESS").getLanguageText(player)); if (database != null) database.save(data); } @Override public boolean commandMain(final CommandSender sender, final String commandLabel, final String[] args) throws CrazyException { if (commandLabel.equalsIgnoreCase("password")) { commandMainPassword(sender, args); return true; } if (commandLabel.equalsIgnoreCase("admin")) { commandMainAdmin(sender, args); return true; } if (commandLabel.equalsIgnoreCase("mode")) { commandMainMode(sender, args); return true; } return false; } private void commandMainPassword(final CommandSender sender, final String[] args) throws CrazyCommandException { if (sender instanceof ConsoleCommandSender) throw new CrazyCommandExecutorException(false); Player player = (Player) sender; if (!isLoggedIn(player) && hasAccount(player)) throw new CrazyCommandPermissionException(); if (args.length == 0) { if (alwaysNeedPassword) throw new CrazyCommandUsageException("/crazylogin password <Passwort...>"); datas.removeDataVia1(player.getName().toLowerCase()); sendLocaleMessage("PASSWORDDELETE.SUCCESS", sender); if (database != null) database.delete(player.getName()); return; } LoginPlayerData data = datas.findDataVia1(player.getName().toLowerCase()); if (data == null) { if (!sender.hasPermission("crazylogin.register")) throw new CrazyCommandPermissionException(); data = new LoginPlayerData(player); datas.setDataVia1(player.getName().toLowerCase(), data); } String password = ChatHelper.listToString(args); data.setPassword(password); data.login(password); sendLocaleMessage("PASSWORDCHANGE.SUCCESS", player); if (database != null) database.save(data); } private void commandMainAdmin(final CommandSender sender, final String[] args) throws CrazyCommandException { if (sender instanceof Player) { Player player = (Player) sender; if (!isLoggedIn(player)) throw new CrazyCommandPermissionException(); } if (!sender.hasPermission("crazylogin.admin")) throw new CrazyCommandPermissionException(); switch (args.length) { case 0: throw new CrazyCommandUsageException("/crazylogin admin <Player> <Passwort...>"); case 1: OfflinePlayer target = getServer().getPlayerExact(args[0]); if (target == null) { target = getServer().getPlayer(args[0]); if (target == null) target = getServer().getOfflinePlayer(args[0]); } if (target == null) throw new CrazyCommandNoSuchException("Player", args[0]); datas.removeDataVia1(target.getName().toLowerCase()); sendLocaleMessage("PASSWORDDELETE.SUCCESS", sender); if (database != null) database.delete(target.getName()); return; } OfflinePlayer target = getServer().getPlayerExact(args[0]); if (target == null) { target = getServer().getPlayer(args[0]); if (target == null) target = getServer().getOfflinePlayer(args[0]); } if (target == null) throw new CrazyCommandNoSuchException("Player", args[0]); LoginPlayerData data = datas.findDataVia1(target.getName().toLowerCase()); if (data == null) throw new CrazyCommandNoSuchException("Player", args[0]); String password = ChatHelper.listToString(ChatHelper.shiftArray(args, 1)); data.setPassword(password); sendLocaleMessage("PASSWORDCHANGE.SUCCESS", sender); if (database != null) database.save(data); } private void commandMainMode(final CommandSender sender, final String[] args) throws CrazyCommandException { if (sender instanceof Player) { Player player = (Player) sender; if (!isLoggedIn(player)) throw new CrazyCommandPermissionException(); } if (!sender.hasPermission("crazylogin.mode")) throw new CrazyCommandPermissionException(); switch (args.length) { case 2: if (args[0].equalsIgnoreCase("alwaysNeedPassword")) { boolean newValue = false; if (args[1].equalsIgnoreCase("1") || args[1].equalsIgnoreCase("true") || args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("yes")) newValue = true; alwaysNeedPassword = newValue; sendLocaleMessage("MODE.CHANGE", sender, "alwaysNeedPassword", alwaysNeedPassword ? "True" : "False"); saveConfiguration(); return; } else if (args[0].equalsIgnoreCase("autoLogout")) { boolean newValue = false; if (args[1].equalsIgnoreCase("1") || args[1].equalsIgnoreCase("true") || args[1].equalsIgnoreCase("on") || args[1].equalsIgnoreCase("yes")) newValue = true; autoLogout = newValue; sendLocaleMessage("MODE.CHANGE", sender, "autoLogout", autoLogout ? "True" : "False"); saveConfiguration(); return; } else if (args[0].equalsIgnoreCase("autoKick")) { int time = autoKick; try { time = Integer.parseInt(args[1]); } catch (NumberFormatException e) { throw new CrazyCommandParameterException(1, "Integer", "-1 = disabled", "Time in Seconds > 60"); } autoKick = time; sendLocaleMessage("MODE.CHANGE", sender, "autoKick", autoKick == -1 ? "disabled" : autoKick + " seconds"); saveConfiguration(); return; } else if (args[0].equalsIgnoreCase("saveType")) { String newValue = args[1]; boolean changed = saveType.equals(newValue); if (newValue.equalsIgnoreCase("config")) saveType = "config"; else if (newValue.equalsIgnoreCase("mysql")) saveType = "mysql"; else if (newValue.equalsIgnoreCase("flat")) saveType = "flat"; else throw new CrazyCommandNoSuchException("SaveType", newValue); sendLocaleMessage("MODE.CHANGE", sender, "saveType", saveType); if (changed) return; getConfig().set("database.saveType", saveType); setupDatabase(); save(); return; } throw new CrazyCommandNoSuchException("Mode", args[0]); case 1: if (args[0].equalsIgnoreCase("alwaysNeedPassword")) { sendLocaleMessage("MODE.CHANGE", sender, "alwaysNeedPassword", alwaysNeedPassword ? "True" : "False"); return; } else if (args[0].equalsIgnoreCase("autoLogout")) { sendLocaleMessage("MODE.CHANGE", sender, "autoLogout", autoLogout ? "True" : "False"); return; } else if (args[0].equalsIgnoreCase("autoKick")) { sendLocaleMessage("MODE.CHANGE", sender, "autoKick", autoKick == -1 ? "disabled" : autoKick + " seconds"); return; } else if (args[0].equalsIgnoreCase("algorithm")) { sendLocaleMessage("MODE.CHANGE", sender, "algorithm", encryptor.getAlgorithm()); return; } else if (args[0].equalsIgnoreCase("saveType")) { sendLocaleMessage("MODE.CHANGE", sender, "saveType", saveType); return; } throw new CrazyCommandNoSuchException("Mode", args[0]); default: throw new CrazyCommandUsageException("/crazylogin mode <Mode> <Value>"); } } public boolean isLoggedIn(final Player player) { LoginPlayerData data = datas.findDataVia1(player.getName().toLowerCase()); if (data == null) return !alwaysNeedPassword; return data.isOnline() && player.isOnline(); } public boolean hasAccount(final OfflinePlayer player) { return (datas.findDataVia1(player.getName().toLowerCase()) != null); } public boolean isAlwaysNeedPassword() { return alwaysNeedPassword; } public boolean isAutoLogoutEnabled() { return autoLogout; } public int getAutoKick() { return autoKick; } public List<String> getCommandWhiteList() { return commandWhiteList; } public boolean isAutoKickCommandUsers() { return autoKickCommandUsers; } public String getUniqueIDKey() { if (uniqueIDKey == null) try { uniqueIDKey = new CrazyCrypt1().encrypt(getServer().getName(), null, "randomKeyGen" + (Math.random() * Integer.MAX_VALUE) + "V:" + getServer().getBukkitVersion() + "'_+' } catch (Exception e) { e.printStackTrace(); return null; } return uniqueIDKey; } public Encryptor getEncryptor() { return encryptor; } public PairList<String, LoginPlayerData> getPlayerData() { return datas; } public void requestLogin(Player player) { if (doNotSpamRequests) return; if (datas.findDataVia1(player.getName().toLowerCase()) == null) sendLocaleMessage("REGISTER.REQUEST", player); else sendLocaleMessage("LOGIN.REQUEST", player); } public boolean isForceSingleSessionEnabled() { return forceSingleSession; } }
package codearea.demo; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.stage.Stage; import codearea.control.CodeArea; public class JavaKeywords extends Application { private static final String[] KEYWORDS = new String[] { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "try", "void", "volatile", "while" }; private static final Pattern KEYWORD = Pattern.compile("\\b(" + String.join("|", KEYWORDS) + ")\\b"); private static final Set<String> KW_CLASSES = new HashSet<String>(1); static { KW_CLASSES.add("keyword"); } private static final String sampleCode = String.join("\n", new String[] { "package com.example;", "", "import java.util.*;", "", "public class Foo extends Bar implements Baz {", "", " public static void main(String[] args) {", " for(String arg: args) {", " if(arg.length() != 0)", " System.out.println(arg);", " else", " System.err.println(\"Warning: empty string as argument\");", " }", " }", "", "}" }); public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { final CodeArea codeArea = new CodeArea(); codeArea.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldText, String newText) { Matcher matcher = KEYWORD.matcher(newText); int lastKwEnd = 0; while(matcher.find()) { codeArea.setStyleClasses(lastKwEnd, matcher.start(), Collections.EMPTY_SET); codeArea.setStyleClasses(matcher.start(), matcher.end(), KW_CLASSES); lastKwEnd = matcher.end(); } codeArea.setStyleClasses(lastKwEnd, newText.length(), Collections.EMPTY_SET); } }); codeArea.replaceText(0, 0, sampleCode); StackPane root = new StackPane(); root.getChildren().add(codeArea); Scene scene = new Scene(root, 600, 400); scene.getStylesheets().add(JavaKeywords.class.getResource("java-keywords.css").toExternalForm()); primaryStage.setScene(scene); codeArea.requestFocus(); primaryStage.show(); } }
package pkgSwing; import javax.swing.*; class Main { public static void main(String[] args) { //entry point SwingUtilities.invokeLater(MainFrame::new); System.out.println("This might well be displayed before the other message."); //some server changes 1 } }
/* * Singleton class representing the Brackets of the tournament, with getters for size, number and brackets */ public class Brackets { private Brackets(){} private static Bracket[] brackets; private static int bSize; public static void setBrackets(int num, int size) { bSize = size; brackets = new Bracket[num]; for(int i = 0; i < num; i++) brackets[i] = new Bracket(size,""+(i+1)); } public static Bracket getBracket(int num) { if(num>=brackets.length) return null; return brackets[num]; } public static Bracket[] getAllBrackets(){ return brackets; } public static int getNum() { return brackets.length; } public static int getSize(){ return bSize; } public static int indexOf(Bracket bracket){ for(int i=0;i<bSize;i++) if(brackets[i] == bracket) return i; return -1; } }
package ui; import javafx.beans.InvalidationListener; import javafx.beans.property.ReadOnlyStringWrapper; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.RadioMenuItem; import javafx.scene.control.SplitPane; import javafx.scene.control.ToggleGroup; import javafx.scene.control.TreeCell; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableColumn; import javafx.scene.control.TreeTableColumn.CellDataFeatures; import javafx.scene.control.TreeTableView; import javafx.scene.control.TreeView; import javafx.scene.input.*; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.util.Callback; import logic.TurboIssue; public class Demo extends Application { private static final String STYLE_YELLOW_BORDERS = "-fx-background-color: #FFFA73; -fx-border-color: #000000; -fx-border-width: 1px;"; public static final String STYLE_BORDERS = "-fx-border-color: #000000; -fx-border-width: 1px;"; private Stage mainStage; private HBox columns; private final ArrayList<BorderPane> items = new ArrayList<>(); private BorderPane createItem(String text3) { BorderPane item = new BorderPane(); items.add(item); final int index = items.size() - 1; Text text = new Text(text3); Text text2 = new Text("" + index); item.setLeft(text2); item.setCenter(text); final String style = STYLE_BORDERS; item.setStyle(style); item.setOnDragDetected((MouseEvent event) -> { Dragboard db = item.startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); DragData dd = new DragData(DragSource.PANEL_MILESTONES); dd.index = index; content.putString(dd.serialize()); db.setContent(content); event.consume(); }); item.setOnDragDone((DragEvent event) -> { if (event.getTransferMode() == TransferMode.MOVE) { } event.consume(); }); item.setOnDragOver((DragEvent event) -> { if (event.getGestureSource() != item && event.getDragboard().hasString()) { event.acceptTransferModes(TransferMode.COPY_OR_MOVE); } event.consume(); }); item.setOnDragEntered((DragEvent event) -> { if (event.getGestureSource() != item && event.getDragboard().hasString()) { item.setStyle(STYLE_YELLOW_BORDERS); } event.consume(); }); item.setOnDragExited((DragEvent event) -> { item.setStyle(style); event.consume(); }); item.setOnDragDropped((DragEvent event) -> { Dragboard db = event.getDragboard(); boolean success = false; if (db.hasString()) { success = true; DragData dd = DragData.deserialize(db.getString()); if (dd.source == DragSource.PANEL_MILESTONES) { text.setText(text.getText() + "\n" + "added item " + dd.index); } else if (dd.source == DragSource.TREE_ISSUES) { text.setText(text.getText() + "\n" + "added issue " + dd.text); } else if (dd.source == DragSource.TREE_LABELS) { text.setText(text.getText() + "\n" + "added label " + dd.text); } else if (dd.source == DragSource.TREE_CONTRIBUTORS) { text.setText(text.getText() + "\n" + "added contributors " + dd.text); } } event.setDropCompleted(success); event.consume(); }); return item; } boolean done = false; private IssuePanel createIssuePanel() { IssuePanel issuePanel = new IssuePanel(); // col.setPadding(new Insets(15, 12, 15, 12)); // col.setSpacing(10); issuePanel.setPrefWidth(400); HBox.setHgrow(issuePanel, Priority.ALWAYS); issuePanel.setStyle(STYLE_BORDERS); issuePanel.setAlignment(Pos.TOP_CENTER); return issuePanel; } private Parent createTreeView() { final TreeItem<String> treeRoot = new TreeItem<>("root"); TreeItem<String> milestones = new TreeItem<>("Milestones"); TreeItem<String> issues = new TreeItem<>("Issues"); TreeItem<String> contributors = new TreeItem<>("Contributors"); TreeItem<String> labels = new TreeItem<>("Labels"); treeRoot.getChildren().addAll( Arrays.asList(milestones, issues, contributors, labels)); milestones.getChildren().addAll( Arrays.asList(new TreeItem<String>("v1.0.1"), new TreeItem<String>("v1.0.2"))); issues.getChildren().addAll( Arrays.asList(new TreeItem<String>("#2 Main page won't load"), new TreeItem<String>("#45 Input validation fails"))); contributors.getChildren().addAll( Arrays.asList(new TreeItem<String>("Ben"), new TreeItem<String>("Jerry"))); labels.getChildren().addAll( Arrays.asList(new TreeItem<String>("Status"), new TreeItem<String>("Urgency"))); labels.getChildren() .get(0) .getChildren() .addAll(Arrays.asList(new TreeItem<String>("Accepted"), new TreeItem<String>("Fixing"))); labels.getChildren() .get(1) .getChildren() .addAll(Arrays.asList(new TreeItem<String>("Urgent"), new TreeItem<String>("Low"))); final TreeView<String> treeView = new TreeView<>(); treeView.setRoot(treeRoot); treeView.setShowRoot(false); treeRoot.setExpanded(true); treeView.setPrefWidth(180); treeRoot.getChildren().stream().forEach((child) -> { child.setExpanded(true); child.getChildren().stream().forEach((TreeItem<String> child1) -> { child1.setExpanded(true); }); }); treeView.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() { @Override public TreeCell<String> call(TreeView<String> stringTreeView) { return new CustomTreeCell<String>(mainStage); } }); return treeView; } private void changePanelCount(int to) { // // TODO the panels aren't ordered in insertion order? watch out for // that // ObservableList<Node> panels = columns.getChildren(); // int panelSize = panels.size(); // if (panelSize == to) { // return; // if (panelSize < to) { // for (int i = 0; i < to - panelSize; i++) { // panels.add(createIssuePanel()); // } else { // panels.size() > to // int numberToRemove = panels.size() - to; // panels.remove(panels.size() - 1 - numberToRemove, panels.size() - 1); test.setTitle("new title"); } private void setUpHotkeys(Scene scene) { scene.getAccelerators().put( new KeyCodeCombination(KeyCode.DIGIT1, KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN), (Runnable) () -> changePanelCount(1)); scene.getAccelerators().put( new KeyCodeCombination(KeyCode.DIGIT2, KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN), (Runnable) () -> changePanelCount(2)); scene.getAccelerators().put( new KeyCodeCombination(KeyCode.DIGIT3, KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN), (Runnable) () -> changePanelCount(3)); scene.getAccelerators().put( new KeyCodeCombination(KeyCode.DIGIT4, KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN), (Runnable) () -> changePanelCount(4)); scene.getAccelerators().put( new KeyCodeCombination(KeyCode.DIGIT5, KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN), (Runnable) () -> changePanelCount(5)); scene.getAccelerators().put( new KeyCodeCombination(KeyCode.DIGIT6, KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN), (Runnable) () -> changePanelCount(6)); scene.getAccelerators().put( new KeyCodeCombination(KeyCode.DIGIT7, KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN), (Runnable) () -> changePanelCount(7)); scene.getAccelerators().put( new KeyCodeCombination(KeyCode.DIGIT8, KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN), (Runnable) () -> changePanelCount(8)); scene.getAccelerators().put( new KeyCodeCombination(KeyCode.DIGIT9, KeyCombination.SHIFT_DOWN, KeyCombination.ALT_DOWN), (Runnable) () -> changePanelCount(9)); } TurboIssue test; private Parent createRoot() { MenuBar menuBar = createMenuBar(); BorderPane root = new BorderPane(); columns = new HBox(); // columns.setPadding(new Insets(15, 12, 15, 12)); // columns.setSpacing(10); IssuePanel col1 = createIssuePanel(); IssuePanel col2 = createIssuePanel(); IssuePanel col3 = createIssuePanel(); col1.getItems().add(test = new TurboIssue("kasjldjkdl", "desc")); col1.getItems().add(new TurboIssue("luihhjgsdf", "desc")); // VBox col3 = createColumn(); // col1.getChildren().addAll(createItem(), createItem()); columns.getChildren().addAll(col1, col2 , col3); // SplitPane splitPane = new SplitPane(); // splitPane.getItems().addAll(createTreeView(), columns); // splitPane.setDividerPositions(0.2); root.setCenter(columns); root.setTop(menuBar); return root; } private MenuBar createMenuBar() { MenuBar menuBar = new MenuBar(); Menu projects = new Menu("Projects"); MenuItem login = new MenuItem("Login"); initLoginForm(login); MenuItem config = new MenuItem("Configuration"); projects.getItems().addAll(login, config); Menu milestones = new Menu("Milestones"); MenuItem newMilestone = new MenuItem("New Milestone"); milestones.getItems().addAll(newMilestone); Menu issues = new Menu("Issues"); MenuItem newIssue = new MenuItem("New Issue"); issues.getItems().addAll(newIssue); Menu labels = new Menu("Labels"); MenuItem newLabel = new MenuItem("New Label"); labels.getItems().addAll(newLabel); Menu view = new Menu("View"); Menu columns = new Menu("Change number of columns...."); view.getItems().addAll(columns); final ToggleGroup numberOfCols = new ToggleGroup(); for (int i = 2; i <= 9; i++) { RadioMenuItem item = new RadioMenuItem(Integer.toString(i)); item.setUserData(i); item.setToggleGroup(numberOfCols); columns.getItems().add(item); if (i == 3) item.setSelected(true); } menuBar.getMenus().addAll(projects, milestones, issues, labels, view); return menuBar; } private void initLoginForm(MenuItem login) { login.setOnAction((e) -> { Stage secondStage = new Stage(); secondStage.setTitle("Github Login"); secondStage.setTitle("JavaFX Welcome"); GridPane grid = new GridPane(); grid.setAlignment(Pos.CENTER); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(25, 25, 25, 25)); Text sceneTitle = new Text("Welcome"); sceneTitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20)); grid.add(sceneTitle, 0, 0, 2, 1); Label userName = new Label("User Name:"); grid.add(userName, 0, 1); TextField userTextField = new TextField(); grid.add(userTextField, 1, 1); Label pw = new Label("Password:"); grid.add(pw, 0, 2); PasswordField pwBox = new PasswordField(); grid.add(pwBox, 1, 2); Button btn = new Button("Sign in"); HBox hbBtn = new HBox(10); hbBtn.setAlignment(Pos.BOTTOM_RIGHT); hbBtn.getChildren().add(btn); grid.add(hbBtn, 1, 4); final Text actiontarget = new Text(); grid.add(actiontarget, 1, 6); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { // add login logic here System.out.println("sign in button pressed"); } }); Scene scene = new Scene(grid, 300, 275); secondStage.setScene(scene); secondStage.initOwner(mainStage); secondStage.initModality(Modality.APPLICATION_MODAL);; secondStage.setX(mainStage.getX()); secondStage.setY(mainStage.getY()); secondStage.show(); }); } @Override public void start(Stage stage) { Scene scene = new Scene(createRoot(), 800, 600); setUpHotkeys(scene); mainStage = stage; stage.setTitle("Demo"); stage.setMinWidth(800); stage.setMinHeight(600); stage.setScene(scene); stage.show(); } public static void main(String[] args) { Application.launch(args); } }
package analysis; import java.text.NumberFormat; import java.util.HashMap; import main.Gui; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.ArrayRealVector; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.linear.RealVector; import org.sbml.libsbml.FbcModelPlugin; import org.sbml.libsbml.FluxBound; import org.sbml.libsbml.Reaction; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.Species; import org.sbml.libsbml.SpeciesReference; import com.joptimizer.solvers.*; import com.joptimizer.optimizers.*; import com.joptimizer.functions.*; import com.joptimizer.util.*; public class FluxBalanceAnalysis { private JOptimizer jop; private String sbmlFileName; private SBMLDocument sbml; private FbcModelPlugin fbc; private NumberFormat nf; public FluxBalanceAnalysis(String sbmlFileName) { // Load the SBML file this.sbmlFileName = sbmlFileName; sbml = Gui.readSBML(this.sbmlFileName); fbc = (FbcModelPlugin)sbml.getModel().getPlugin("fbc"); //Set number of digits after decimal point nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(4); nf.setGroupingUsed(false); } public String vectorToString(double[] objective, HashMap<String,Integer> reactionIndex) { String result = ""; for (String reaction : reactionIndex.keySet()) { double value = objective[reactionIndex.get(reaction)]; if (value == 1) { if (!result.equals("")) result += " + "; result += reaction; } else if (value == -1) { if (!result.equals("")) result += " + "; result += "-" + reaction; } else if (value != 0) { if (!result.equals("")) result += " + "; result += value + "*" + reaction; } } return result; } public int PerformFluxBalanceAnalysis(){ if (fbc != null) { HashMap<String, Integer> reactionIndex = new HashMap<String, Integer>(); int kp = 0; for(int l =0;l<fbc.getNumFluxBounds();l++){ if(!reactionIndex.containsKey(fbc.getFluxBound(l).getReaction())){ reactionIndex.put(fbc.getFluxBound(l).getReaction(), kp); kp++; } } for (long i = 0; i < fbc.getNumObjectives(); i++) { double [] objective = new double[(int) sbml.getModel().getNumReactions()]; for (int j = 0; j < fbc.getObjective(i).getNumFluxObjectives(); j++) { if (fbc.getObjective(i).getType().equals("minimize")) { objective [(int) reactionIndex.get(fbc.getObjective(i).getFluxObjective(j).getReaction())] = fbc.getObjective(i).getFluxObjective(j).getCoefficient(); } else { objective [(int) reactionIndex.get(fbc.getObjective(i).getFluxObjective(j).getReaction())] = (-1)*fbc.getObjective(i).getFluxObjective(j).getCoefficient(); } } LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(objective, 0); System.out.println("Minimize: " + vectorToString(objective,reactionIndex)); System.out.println("Subject to:"); ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[(int)(fbc.getNumFluxBounds())]; for (long j = 0; j < fbc.getNumFluxBounds(); j++) { FluxBound bound = fbc.getFluxBound(j); double R [] = new double [reactionIndex.size()]; if(reactionIndex.containsKey(bound.getReaction())){ if(bound.getOperation().equals("greaterEqual")) { R[reactionIndex.get(bound.getReaction())]=-1; } else { R[reactionIndex.get(bound.getReaction())]=1; } } double boundVal = bound.getValue(); if(bound.getOperation().equals("greaterEqual")){ inequalities[(int) j] = new LinearMultivariateRealFunction(R, boundVal); if (boundVal!=0) boundVal=(-1)*boundVal; System.out.println(" " + vectorToString(R,reactionIndex) + " <= " + boundVal); } else if(bound.getOperation().equals("lessEqual")){ System.out.println(" " + vectorToString(R,reactionIndex) + " <= " + boundVal); if (boundVal!=0) boundVal=(-1)*boundVal; inequalities[(int) j] = new LinearMultivariateRealFunction(R, boundVal); } } int m = 0; int nonBoundarySpeciesCount = 0; for (int j = 0; j < sbml.getModel().getNumSpecies(); j++) { if (!sbml.getModel().getSpecies(j).getBoundaryCondition()) nonBoundarySpeciesCount++; } double[][] stoch = new double [nonBoundarySpeciesCount][(int) (sbml.getModel().getNumReactions())]; double[] zero = new double [nonBoundarySpeciesCount]; for (long j = 0; j < sbml.getModel().getNumSpecies(); j++) { Species species = sbml.getModel().getSpecies(j); if (species.getBoundaryCondition()) continue; zero[m] = 0; for (long k = 0; k < sbml.getModel().getNumReactions(); k++) { Reaction r = sbml.getModel().getReaction(k); for (long l = 0; l < r.getNumReactants(); l++) { SpeciesReference sr = r.getReactant(l); if (sr.getSpecies().equals(species.getId())) { stoch[m][(int) (reactionIndex.get(r.getId()))]=(-1)*sr.getStoichiometry(); } } for (long l = 0; l < r.getNumProducts(); l++) { SpeciesReference sr = r.getProduct(l); if (sr.getSpecies().equals(species.getId())) { stoch[m][(int) (reactionIndex.get(r.getId()))]=sr.getStoichiometry(); } } } //inequalities[(int) (m + fbc.getNumFluxBounds())] = new LinearMultivariateRealFunction(stoch, 0); System.out.println(" " + vectorToString(stoch[m],reactionIndex) + " = 0" + " (" + species.getId() + ")"); m++; } //optimization problem OptimizationRequest or = new OptimizationRequest(); or.setF0(objectiveFunction); or.setFi(inequalities); or.setA(stoch); or.setB(zero); //zero = new double[reactionIndex.size()]; //for (int j = 0; j < reactionIndex.size(); j++) { // zero[j] = 0; //or.setInitialPoint(zero);//initial feasible point, not mandatory or.setToleranceFeas(1.E-9); or.setTolerance(1.E-9); //optimization jop = new JOptimizer(); jop.setOptimizationRequest(or); try { jop.optimize(); double [] sol = jop.getOptimizationResponse().getSolution(); for (int j = 0; j < sol.length; j++) { System.out.print(sol[j]+" "); } System.out.println(); } catch (Exception e) { e.printStackTrace(); } } return 0; } else { System.out.println("No flux balance constraints"); return 0; } } /** * @return */ public int PerformFluxBalanceAnalysis2(){ // Fill the objective array if (fbc != null) { for (long i = 0; i < fbc.getNumObjectives(); i++) { HashMap<String, Integer> reactionIndex = new HashMap<String, Integer>(); int kp = 0; for(int l =0;l<fbc.getNumFluxBounds();l++){ if(!reactionIndex.containsKey(fbc.getFluxBound(l).getReaction())){ reactionIndex.put(fbc.getFluxBound(l).getReaction(), kp); kp++; } } System.out.println(reactionIndex); //Set the array to be the max it will ever be, Min & max for each + possible reversible reactions double [] objective = new double[(int) sbml.getModel().getNumReactions()]; for (int j = 0; j < fbc.getObjective(i).getNumFluxObjectives(); j++) { objective [(int) reactionIndex.get(fbc.getObjective(i).getFluxObjective(j).getReaction())] = fbc.getObjective(i).getFluxObjective(j).getCoefficient(); System.out.println(fbc.getObjective(i).getFluxObjective(j).getReaction() + " " + fbc.getObjective(i).getFluxObjective(j).getColumn()); // Insert the coefficient in the array in the appropriate location for the reaction in this flux objective } String printTest = ""; for (int j = 0; j < objective.length; j++) { printTest += (objective[j] + " "); } System.out.println(printTest); // [ 0 0 ... 1.0 ] //LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(objective, 0); //TODO: Positive = minimum, negative = maximum??? LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(new double[] {-1.,-1.}, 0); //Note: Doesn't like multiple objectives... two objectives needs 4 equalities? // Construct set of inequalities which is number of flux bounds (+ locations for equal bounds) + 2*number of species //inequalities (polyhedral feasible set G.X<H ) //ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[(int) (2*(sbml.getModel().getNumSpecies()) + fbc.getNumFluxBounds())]; ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[4]; //TODO: If G is negative it sets a minimum, positive = maximum..... F always negative? Elaboration: no, F must be positive to set a min with a positive number //Does the position in G correspond with objctivefunction? //F/G=limit, Ex. G=-0.5 F=-100 minimum value >= -200. //Ex. for positive: G = 1 , F = -10 Max <= 10 double[][] G = new double[][] {{1,1}, {3,1}, {2, 1.}, {0.5, 1.}}; double[] F = new double[] {2., 1./2., 2., 1./2.}; //Set Maximum inequalities[0] = new LinearMultivariateRealFunction(G[0], -15); //Set Minimum inequalities[1] = new LinearMultivariateRealFunction(G[1], -90); inequalities[2] = new LinearMultivariateRealFunction(G[2], -30); inequalities[3] = new LinearMultivariateRealFunction(G[3], -5); System.out.println(fbc.getNumFluxBounds()); for (long j = 0; j < fbc.getNumFluxBounds(); j++) { FluxBound bound = fbc.getFluxBound(j); double R [] = new double [reactionIndex.size()]; if(reactionIndex.containsKey(bound.getReaction())){ if(bound.getOperation().equals("greaterEqual")) { R[reactionIndex.get(bound.getReaction())]=-1; } else { R[reactionIndex.get(bound.getReaction())]=1; } } if(bound.getOperation().equals("greaterEqual")){ //inequalities[(int) j] = new LinearMultivariateRealFunction(R, bound.getValue()); } else if(bound.getOperation().equals("lessEqual")){ //inequalities[(int) j] = new LinearMultivariateRealFunction(R, bound.getValue()); } String secondTest = ""; for (int k = 0; k < R.length; k++) { secondTest += (R[k]+" "); } System.out.println(secondTest); System.out.println(bound.getReaction() + " " + bound.getOperation() + " " + bound.getValue()); // Create a vector R size number of reactions where the entry is 1.0 for the reaction for this bound and 0 otherwise // rSign/hSign is determined by the operation, <= +/-, >= -/+ // inequalities[j] = new LinearMultivariateRealFunction(rSign * R, hSign * value); } for (long j = 0; j < sbml.getModel().getNumSpecies(); j++) { double[] stoch = new double [(int) (sbml.getModel().getNumReactions())]; Species species = sbml.getModel().getSpecies(j); System.out.println(species.getId()); // Construct a stoch vector size of number of reactions, init with 0's for (long k = 0; k < sbml.getModel().getNumReactions(); k++) { Reaction r = sbml.getModel().getReaction(k); for (long l = 0; l < r.getNumReactants(); l++) { SpeciesReference sr = r.getReactant(l); if (sr.getSpecies().equals(species.getId())) { System.out.println(r.getId() + ":" + (-1)*sr.getStoichiometry()); stoch[(int) (reactionIndex.get(r.getId()))]=(-1)*sr.getStoichiometry(); } } for (long l = 0; l < r.getNumProducts(); l++) { SpeciesReference sr = r.getProduct(l); if (sr.getSpecies().equals(species.getId())) { System.out.println(r.getId() + ":" + sr.getStoichiometry()); stoch[(int) (reactionIndex.get(r.getId()))]=sr.getStoichiometry(); } } // Do same for products // Insert (product stoch - reactant stoch) into appropriate location in the vector } //inequalities[(int) (2*j + fbc.getNumFluxBounds())] = new LinearMultivariateRealFunction(stoch, 0); for(int k = 0; k<stoch.length;k++){ stoch[k] = -1*stoch[k]; } //inequalities[(int) (2*j + 1 + fbc.getNumFluxBounds())] = new LinearMultivariateRealFunction(stoch, 0); } //optimization problem OptimizationRequest or = new OptimizationRequest(); or.setF0(objectiveFunction); or.setFi(inequalities); //or.setInitialPoint(new double[] {0.0, 0.0});//initial feasible point, not mandatory or.setToleranceFeas(1.E-9); or.setTolerance(1.E-9); //optimization jop = new JOptimizer(); jop.setOptimizationRequest(or); try { jop.optimize(); //TODO: Need to fill inequalities? double [] sol = jop.getOptimizationResponse().getSolution(); for (long j = 0; j < fbc.getNumObjectives(); j++) { //TODO: Add for loop per each FluxObjective System.out.println(fbc.getObjective(j).getFluxObjective(0).getReaction() + " = " + sol[(int) j]); System.out.println(fbc.getObjective(j).getFluxObjective(0).getReaction() + " = " + sol[(int) 1]); } } catch (Exception e) { e.printStackTrace(); } } return 0; } else { System.out.println("No flux balance constraints"); return 0; } // // Objective function (plane) // LinearMultivariateRealFunction objectiveFunction = new LinearMultivariateRealFunction(new double[] { -1., -1. }, 4); // //inequalities (polyhedral feasible set G.X<H ) // ConvexMultivariateRealFunction[] inequalities = new ConvexMultivariateRealFunction[4]; // double[][] G = new double[][] {{4./3., -1}, {-1./2., 1.}, {-2., -1.}, {1./3., 1.}}; // double[] H = new double[] {2., 1./2., 2., 1./2.}; // inequalities[0] = new LinearMultivariateRealFunction(G[0], -H[0]); // inequalities[1] = new LinearMultivariateRealFunction(G[1], -H[1]); // inequalities[2] = new LinearMultivariateRealFunction(G[2], -H[2]); // inequalities[3] = new LinearMultivariateRealFunction(G[3], -H[3]); // //optimization problem // OptimizationRequest or = new OptimizationRequest(); // or.setF0(objectiveFunction); // or.setFi(inequalities); // //or.setInitialPoint(new double[] {0.0, 0.0});//initial feasible point, not mandatory // or.setToleranceFeas(1.E-9); // or.setTolerance(1.E-9); // //optimization // jop = new JOptimizer(); // jop.setOptimizationRequest(or); // try { // jop.optimize(); // } catch (Exception e) { // e.printStackTrace(); // double [] sol = jop.getOptimizationResponse().getSolution(); // System.out.println(nf.format(sol[0])); // System.out.println(nf.format(sol[1])); // return (int) sol[0]; } }
package hex; import hex.quantile.Quantile; import hex.quantile.QuantileModel; import water.*; import water.fvec.Chunk; import water.fvec.Frame; import water.fvec.Vec; import water.util.MathUtils; import water.util.PrettyPrint; import water.util.TwoDimTable; import java.util.Arrays; public class GainsLift extends Iced { private static int GROUPS = 10; private double[] _quantiles; //INPUT public Vec _labels; public Vec _preds; public Vec _weights; //OUTPUT public float[] response_rates; public float avg_response_rate; public long[] positive_responses; TwoDimTable table; public GainsLift(Vec preds, Vec labels) { _preds = preds; _labels = labels; } private void init() throws IllegalArgumentException { _labels = _labels.toCategoricalVec(); if( _labels ==null || _preds ==null ) throw new IllegalArgumentException("Missing actualLabels or predictedProbs!"); if (_labels.length() != _preds.length()) throw new IllegalArgumentException("Both arguments must have the same length ("+ _labels.length()+"!="+ _preds.length()+")!"); if (!_labels.isInt()) throw new IllegalArgumentException("Actual column must be integer class labels!"); if (_labels.cardinality() != -1 && _labels.cardinality() != 2) throw new IllegalArgumentException("Actual column must contain binary class labels, but found cardinality " + _labels.cardinality() + "!"); if (_preds.isCategorical()) throw new IllegalArgumentException("predictedProbs cannot be class labels, expect probabilities."); if (_weights != null && !_weights.isNumeric()) throw new IllegalArgumentException("weight must be numeric."); // The vectors are from different groups => align them, but properly delete it after computation if (!_labels.group().equals(_preds.group())) { _preds = _labels.align(_preds); Scope.track(_preds._key); if (_weights !=null) { _weights = _labels.align(_weights); Scope.track(_weights._key); } } boolean fast = false; if (fast) { //get specific pre-computed quantiles (deciles) from rollupstats //First check that rollups still uses the convention we rely on (hardcoded indexing below) assert(Arrays.equals(Vec.PERCENTILES, // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15, 16 new double[]{0.001, 0.01, 0.1, 0.2, 0.25, 0.3, 1.0 / 3.0, 0.4, 0.5, 0.6, 2.0 / 3.0, 0.7, 0.75, 0.8, 0.9, 0.99, 0.999})); //HACK: hardcoded quantiles for simplicity (0.9,0.8,...,0.1,0) double[] rq = _preds.pctiles(); //might do a full pass over the Vec _quantiles = new double[]{ rq[14], rq[13], rq[11], rq[9], rq[8], rq[7], rq[5], rq[3], rq[2], 0 /*ignored*/ }; } else { QuantileModel.QuantileParameters qp = new QuantileModel.QuantileParameters(); Frame fr = new Frame(Key.make(), new String[]{"predictions"}, new Vec[]{_preds}); DKV.put(fr); qp._train = fr._key; qp._probs = new double[GROUPS]; for (int i = 0; i < GROUPS; ++i) { qp._probs[i] = (GROUPS - i - 1.) / GROUPS; } if (_weights != null) throw H2O.unimpl("Quantile cannot handle weights yet."); Quantile q = new Quantile(qp); QuantileModel qm = q.trainModel().get(); _quantiles = qm._output._quantiles[0]; qm.remove(); DKV.remove(fr._key); } } public void exec() { Scope.enter(); init(); //check parameters and obtain _quantiles from _preds try { GainsLiftBuilder gt = new GainsLiftBuilder(_quantiles); gt = (_weights != null) ? gt.doAll(_labels, _preds, _weights) : gt.doAll(_labels, _preds); response_rates = gt.response_rates(); avg_response_rate = gt.avg_response_rate(); positive_responses = gt.responses(); } finally { // Delete adaptation vectors Scope.exit(); } } @Override public String toString() { return createTwoDimTable().toString(); } public TwoDimTable createTwoDimTable() { if (response_rates == null) return null; TwoDimTable table = new TwoDimTable( "Gains/Lift Table", "Avg response rate: " + PrettyPrint.formatPct(avg_response_rate), new String[GROUPS], new String[]{"Decile", "Lower threshold", "Response rate", "Lift", "Cumulative Lift"}, new String[]{"int", "double", "double", "double", "double"}, new String[]{"%d", "%5f", "%5f", "%5f", "%5f"}, ""); float cumulativelift = 0; for (int i = 0; i < GROUPS; ++i) { table.set(i,0,i+1); table.set(i,1,_quantiles[i]); table.set(i,2,response_rates[i]); final float lift = response_rates[i]/ avg_response_rate; cumulativelift += lift/ GROUPS; table.set(i,3,lift); table.set(i,4,cumulativelift); } return this.table = table; } // Compute Gains table via MRTask public static class GainsLiftBuilder extends MRTask<GainsLiftBuilder> { /* @OUT response_rates */ public final float[] response_rates() { return _response_rates; } public final float avg_response_rate() { return _avg_response_rate; } public final long[] responses(){ return _responses; } /* @IN quantiles/thresholds */ final private double[] _thresh; private long[] _responses; private long _avg_response; private float _avg_response_rate; private float[] _response_rates; private long _count; public GainsLiftBuilder(double[] thresh) { _thresh = thresh.clone(); } @Override public void map( Chunk ca, Chunk cp, Chunk w) { throw H2O.unimpl("GainsLiftBuilder with weights not yet implemented - requires weighted quantiles as well."); } @Override public void map( Chunk ca, Chunk cp ) { final double w = 1.0; _responses = new long[_thresh.length]; _avg_response = 0; final int len = Math.min(ca._len, cp._len); for( int i=0; i < len; i++ ) { if (ca.isNA(i)) continue; final int a = (int)ca.at8(i); if (a != 0 && a != 1) throw new IllegalArgumentException("Invalid values in actualLabels: must be binary (0 or 1)."); if (cp.isNA(i)) continue; final double pr = cp.atd(i); perRow(pr, a, w); } } public void perRow(double pr, int a, double w) { if (w!=1.0) throw H2O.unimpl("GainsLiftBuilder perRow cannot handle weights != 1 for now"); if (Double.isNaN(pr)) return; if (a != 0 && a != 1) throw new IllegalArgumentException("Invalid values in actualLabels: must be binary (0 or 1)."); for( int t=0; t < _thresh.length; t++ ) { if (a==0) continue; if (t==0) { if (pr >= _thresh[t]) _responses[t]++; } else if (t==_thresh.length-1) { //bottom decile if (pr < _thresh[t-1]) _responses[t]++; } else { //in between if (pr >= _thresh[t] && pr < _thresh[t-1]) _responses[t]++; } } if (a == 1) _avg_response++; _count++; } @Override public void reduce(GainsLiftBuilder other) { for( int i=0; i<_responses.length; ++i) { _responses[i] += other._responses[i]; } _avg_response += other._avg_response; _count += other._count; } @Override public void postGlobal(){ _response_rates = new float[_thresh.length]; for (int i=0; i<_response_rates.length; ++i) { _response_rates[i] = (float) _responses[i]; } MathUtils.div(_response_rates, (float) _count / _thresh.length); for (int i=0; i<_response_rates.length; ++i) { // spill over to next bucket - needed due to tie breaking in quantiles if(_response_rates[i] > 1 && i<_response_rates.length-1) { _response_rates[i+1] += (_response_rates[i]-1); _response_rates[i] -= (_response_rates[i]-1); } } _avg_response_rate = (float)_avg_response / _count; } } }
package water; import static org.junit.Assert.*; import org.junit.*; import java.util.concurrent.ExecutionException; import jsr166y.CountedCompleter; import water.fvec.Chunk; import water.fvec.FileVec; import water.fvec.Vec; public class MRThrow extends TestUtil { @BeforeClass static public void setup() { stall_till_cloudsize(5);} @Test public void testLots() { for( int i=0; i<10; i++ ) testInvokeThrow(); } // Map in h2o.jar - a multi-megabyte file - into Arraylets. // Run a distributed byte histogram. Throw an exception in *some* map call, // and make sure it's forwarded to the invoke. @Test public void testInvokeThrow() { int sz = H2O.CLOUD.size(); Vec vec = Vec.makeZero((sz+1)*FileVec.DFLT_CHUNK_SIZE+1); try { for(int i = 0; i < sz; ++i) { ByteHistoThrow bh = new ByteHistoThrow(H2O.CLOUD._memary[i]); Throwable ex=null; try { bh.doAll(vec); // invoke should throw DistributedException wrapped up in RunTimeException } catch( RuntimeException e ) { ex = e; assertTrue(e.getMessage().contains("test") || e.getCause().getMessage().contains("test")); } catch( Throwable e2 ) { (ex=e2).printStackTrace(); fail("Expected RuntimeException, got " + ex.toString()); } if( ex == null ) fail("should've thrown"); } } finally { if( vec != null ) vec.remove(); // remove from DKV } } @Test public void testContinuationThrow() throws InterruptedException, ExecutionException { int sz = H2O.CLOUD.size(); Vec vec = Vec.makeZero((sz+1)*FileVec.DFLT_CHUNK_SIZE+1); try { for(int i = 0; i < H2O.CLOUD._memary.length; ++i){ final ByteHistoThrow bh = new ByteHistoThrow(H2O.CLOUD._memary[i]); final boolean [] ok = new boolean[]{false}; try { CountedCompleter cc = new CountedCompleter() { @Override public void compute() { tryComplete(); } @Override public boolean onExceptionalCompletion(Throwable ex, CountedCompleter cc){ ok[0] = ex.getMessage().contains("test"); return super.onExceptionalCompletion(ex,cc); } }; bh.setCompleter(cc); bh.dfork(vec); // If the chosen file is too small for the cluster, some nodes will have *no* work // and so no exception is thrown. cc.join(); } catch( RuntimeException re ) { assertTrue(re.getMessage().contains("test") || re.getCause().getMessage().contains("test")); // } catch( ExecutionException e ) { // caught on self // assertTrue(e.getMessage().contains("test")); } catch( java.lang.AssertionError ae ) { throw ae; // Standard junit failure reporting assertion } catch(Throwable ex) { ex.printStackTrace(); fail("Unexpected exception" + ex.toString()); } } } finally { if( vec != null ) vec.remove(); // remove from DKV } } // Byte-wise histogram public static class ByteHistoThrow extends MRTask<ByteHistoThrow> { final H2ONode _throwAt; int[] _x; ByteHistoThrow( H2ONode h2o ) { _throwAt = h2o; } // Count occurrences of bytes @Override public void map( Chunk chk ) { _x = new int[256]; // One-time set histogram array byte[] bits = chk.getBytes(); // Raw file bytes for( byte b : bits ) // Compute local histogram _x[b&0xFF]++; if( H2O.SELF.equals(_throwAt) ) throw new RuntimeException("test"); } // ADD together all results @Override public void reduce( ByteHistoThrow bh ) { water.util.ArrayUtils.add(_x,bh._x); } } }
import java.net.URI; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.MapFile; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.lib.IdentityMapper; import org.apache.hadoop.mapred.lib.InputSampler; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.KeyValueTextInputFormat; import org.apache.hadoop.mapred.TextInputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class MRDriver extends Configured implements Tool { public final int MR_TIMEOUT_MILLI = 60000000; public static void main(String args[]) throws Exception { if (args.length != 10) { System.out.println("usage: java MRDriver <epsilon> <delta> <minFreqPercent> <d> <datasetSize> <nodes> <mapper id> <path to input database> " + "<path to output local FIs> <path to output global FIs>"); System.exit(1); } int res = ToolRunner.run(new MRDriver(), args); System.exit(res); } public int run(String args[]) throws Exception { long job_start_time, job_end_time; long job_runtime; float epsilon = Float.parseFloat(args[0]); double delta = Double.parseDouble(args[1]); int minFreqPercent = Integer.parseInt(args[2]); int d = Integer.parseInt(args[3]); int datasetSize = Integer.parseInt(args[4]); int nodes = Integer.parseInt(args[5]); JobConf conf = new JobConf(getConf()); int numSamples = (int) Math.floor(0.95 * nodes * conf.getInt("mapred.tasktracker.tasks.maximum", 10)); double phi = 2 + 4 * Math.log(delta) / numSamples - Math.sqrt(16 * Math.pow(Math.log(delta), 2) / numSamples + 8 * Math.log(delta) / numSamples + 3); assert phi > 0.0 && phi < 1.0; int sampleSize = (int) Math.ceil((2 / Math.pow(epsilon, 2))*(d + Math.log(1/ phi))); double freq = datasetSize / ((double) numSamples * sampleSize); conf.setInt("PARMM.reducersNum", numSamples); conf.setInt("PARMM.datasetSize", datasetSize); conf.setInt("PARMM.minFreqPercent", minFreqPercent); conf.setFloat("PARMM.epsilon", epsilon); conf.setBoolean("mapred.reduce.tasks.speculative.execution", false); conf.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI); conf.setJarByClass(MRDriver.class); conf.setMapOutputKeyClass(IntWritable.class); conf.setMapOutputValueClass(Text.class); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(DoubleWritable.class); FileInputFormat.addInputPath(conf, new Path(args[7])); FileOutputFormat.setOutputPath(conf, new Path(args[8])); // set the mapper classs based on command line option if(args[3].equals("1")) { conf.setMapperClass(FIMMappers.PartitionMapper.class); } else if(args[3].equals("2")) { conf.setMapperClass(FIMMappers.BinomialSamplerMapper.class); } else if(args[3].equals("3")) { conf.setMapperClass(FIMMappers.CoinFlipSamplerMapper.class); } else if(args[3].equals("4")) { conf.setMapperClass(FIMMappers.InputSamplerMapper.class); // create a random sample of size T*m InputSampler.Sampler<LongWritable,Text> sampler = new InputSampler.RandomSampler<LongWritable,Text>(freq, numSamples); LongWritable[] samples = sampler.getSample(new TextInputFormat(), conf); Collections.shuffle(Arrays.asList(samples)); // for each key in the sample, create a list of all T samples to which this key belongs Hashtable<LongWritable, ArrayList<IntWritable>> hashTable = new Hashtable<LongWritable, ArrayList<IntWritable>>(); for (int i=0; i < samples.length; i++) { ArrayList<IntWritable> sampleIDs = null; if (hashTable.contains(samples[i])) sampleIDs = hashTable.get(samples[i]); else sampleIDs = new ArrayList<IntWritable>(); sampleIDs.add(new IntWritable(i % sampleSize)); hashTable.put(samples[i], sampleIDs); } MapFile.Writer writer = null; FileSystem fs = null; try { //writer = MapFile.createWriter(fs, conf, path, LongWritable.class, IntArrayWritable.class); // MapFile.Writer will create 2 files, samplesMap/data and samplesMap/index fs = FileSystem.get(conf); //fs = FileSystem.getLocal(conf); // get the driver's local filesystem writer = new MapFile.Writer(conf, fs, "samplesMap", LongWritable.class, IntArrayWritable.class); // create sorted list of keys (need to append keys to MapFile in sorted order) ArrayList<LongWritable> sorted_keys = new ArrayList<LongWritable>(hashTable.keySet()); Collections.sort(sorted_keys); for(LongWritable key : sorted_keys) //for (LongWritable key : hashTable.keySet()) { ArrayList<IntWritable> sampleIDs = hashTable.get(key); IntArrayWritable sampleIDsIAW = new IntArrayWritable(); sampleIDsIAW.set(sampleIDs.toArray(new IntWritable[1])); writer.append(key, sampleIDsIAW); } } finally { IOUtils.closeStream(writer); } DistributedCache.addCacheFile(new URI(fs.getUri().toString() + "samplesMap/data"), conf); DistributedCache.addCacheFile(new URI(fs.getUri().toString() + "samplesMap/index"), conf); } else { // NOT REACHED } conf.setPartitionerClass(FIMPartitioner.class); conf.setReducerClass(FIMReducer.class); job_start_time = System.currentTimeMillis(); JobClient.runJob(conf); job_end_time = System.currentTimeMillis(); job_runtime = (job_end_time-job_start_time) / 1000; System.out.println("local FIM runtime (seconds): " + job_runtime); JobConf confAggr = new JobConf(getConf()); confAggr.setBoolean("mapred.reduce.tasks.speculative.execution", false); confAggr.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI); confAggr.setJarByClass(MRDriver.class); confAggr.setMapOutputKeyClass(Text.class); confAggr.setMapOutputValueClass(Text.class); confAggr.setOutputKeyClass(Text.class); confAggr.setOutputValueClass(DoubleWritable.class); confAggr.setMapperClass(IdentityMapper.class); confAggr.setReducerClass(AggregateReducer.class); confAggr.setInputFormat(KeyValueTextInputFormat.class); KeyValueTextInputFormat.addInputPath(confAggr, new Path(args[8])); FileOutputFormat.setOutputPath(confAggr, new Path(args[9])); job_start_time = System.currentTimeMillis(); JobClient.runJob(confAggr); job_end_time = System.currentTimeMillis(); job_runtime = (job_end_time-job_start_time) / 1000; System.out.println("aggregation runtime (seconds): " + job_runtime); return 0; } }
package view; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.InputStreamReader; import java.sql.SQLException; import java.util.Scanner; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import data.DataConnection; public class ad extends JFrame implements ActionListener{ static int op; private static DataConnection mc = DataConnection.getInstance(); public JPanel panel; public JButton botones[]; public JLabel label; public JButton button; public JTextArea area; public int contBotonesActual; public JButton atras; public ad() throws SQLException{ super("sistema experto"); this.inicializarComponentes(); this.inicializarFrame(); } public static void main(String[] args) throws Exception { ad a = new ad(); } public void inicializarFrame(){ setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//finaliza el programa cuando se da click en la X setSize(500,350);//configurando tamao de la ventana setVisible(true);//configurando visualizacin de la ventana } public void inicializarComponentes() throws SQLException{ panel = new JPanel(); panel.setLayout(new FlowLayout()); this.contBotonesActual=0; this.botones= new JButton[100]; //inicio for (int i = 0; i < mc.selectIdFromLevel(1000).size(); i++) { this.botones[i]=new JButton(mc.selectNameFromLevel(1000).get(i)); this.botones[i].setName(mc.selectIdFromLevel(1000).get(i)); this.panel.add(this.botones[i]); this.botones[i].addActionListener(this); this.contBotonesActual++; } this.atras= new JButton("atras"); this.atras.setVisible(false); this.atras.addActionListener(this); this.panel.add(this.atras); this.add(panel); } public void eliminarBotones(){ for (int i = 0; i < this.contBotonesActual; i++) { botones[i].removeActionListener(this); botones[i].setVisible(false); panel.remove(botones[i]); } this.contBotonesActual=0; } @Override public void actionPerformed(ActionEvent e) { String aux, aux2, aux3; if(e.getSource()==atras){ aux= botones[0].getName(); eliminarBotones(); try { aux2= mc.selectAntecesorFromId(Integer.parseInt(aux)).get(0);//id antecesor if(Integer.parseInt(aux2)<2000){//primer nivel for (int i = 0; i < mc.selectIdFromLevel(1000).size(); i++) { this.botones[i]=new JButton(mc.selectNameFromLevel(1000).get(i)); this.botones[i].setName(mc.selectIdFromLevel(1000).get(i)); this.panel.add(this.botones[i]); this.botones[i].addActionListener(this); this.contBotonesActual++; } } else { //pedir nuevamente el id antecesor aux= mc.selectAntecesorFromId(Integer.parseInt(aux2)).get(0);//id antecesor2 construirBotones(aux); } } catch (NumberFormatException e1) { e1.printStackTrace(); } catch (SQLException e1) { e1.printStackTrace(); } } else{ try { aux= ((JButton)(e.getSource())).getName(); eliminarBotones(); construirBotones(aux); } catch (SQLException e1) { e1.printStackTrace(); } } System.out.println(contBotonesActual); System.out.println("\n\n"); } private void construirBotones(String aux) throws NumberFormatException, SQLException { String aux2, aux3; for (int i = 0; i < mc.selectSucesoresFromId(Integer.parseInt(aux)).size(); i++) { aux2=mc.selectSucesoresFromId(Integer.parseInt(aux)).get(i); //id sucesor System.out.println(aux2); aux3= mc.selectNombreFromId(Integer.parseInt(aux2)).get(0); //nombre //aux3= (mc.selectNombreFromId(Integer.parseInt(mc.selectSucesoresFromId(Integer.parseInt(aux2)).get(i).toString()))).get(i).toString(); botones[i]= new JButton(aux3); botones[i].setName(aux2); this.panel.add(botones[i]); botones[i].addActionListener(this); botones[i].setVisible(true); this.contBotonesActual++; } if((Integer.parseInt(mc.selectNivelFromId(Integer.parseInt(botones[0].getName())).get(0)))>1999){ atras.setVisible(true); } else { atras.setVisible(false); } } }
package org.skyve.util; import java.util.HashSet; import java.util.List; import java.util.Set; import org.skyve.domain.Bean; import org.skyve.domain.ChildBean; import org.skyve.domain.messages.DomainException; import org.skyve.metadata.MetaDataException; import org.skyve.metadata.customer.Customer; import org.skyve.metadata.model.Attribute; import org.skyve.metadata.model.document.Association; import org.skyve.metadata.model.document.Document; import org.skyve.metadata.model.document.Inverse; import org.skyve.metadata.model.document.Inverse.InverseCardinality; import org.skyve.metadata.model.document.Relation; import org.skyve.metadata.module.Module; public abstract class BeanVisitor { private boolean visitNulls; private boolean visitInverses; private boolean vectorCyclicDetection; /** * Visit the structure of a bean (and it's related graph). * * @param visitNulls Visit a bean's relations including relations that are not defined. * In this method call, the bean can be null, which will visit all bindings defined in the document. * If a component instance is null then the document metadata is used for traversal. * @param visitInverses Visit any inverses defined in the document. * This option is available as inverses are weakly referenced (not validated, not cascaded). * @param vectorCyclicDetection Cyclic dependencies are detected by keeping a breadcrumb list of beans visited. * If the bean has been visited before, it is not visited again. * This guarantees that a bean is visited ONLY ONCE. * But some processing types need to know where the bean was traversed from. * It then keeps a vector of the bean and its traversal direction. * eg visited contact "mike" from User "mike" through the association "contact". * In vector mode, a bean may be visited MORE THAN ONCE if it has multiple references * within the same object graph. * * This visit method is thread-safe - the same instance can be used in multiple threads. */ public BeanVisitor(boolean visitNulls, boolean visitInverses, boolean vectorCyclicDetection) { this.visitNulls = visitNulls; this.visitInverses = visitInverses; this.vectorCyclicDetection = vectorCyclicDetection; } /** * Visit a bean excluding relations that are null. * This method is thread-safe. * * @param document * @param bean * @param customer */ public void visit(Document document, Bean bean, Customer customer) { Set<String> visited = new HashSet<>(); visit("", document, null, null, bean, customer, visited); } private String determineVisitedKey(Bean bean, Document owningDocument, Relation owningRelation) { if (vectorCyclicDetection) { StringBuilder sb = new StringBuilder(128).append(bean.getBizId()); if (owningRelation != null) { sb.append(owningRelation.getName()); } if (owningDocument != null) { sb.append(owningDocument.getName()).append(owningDocument.getOwningModuleName()); } return sb.toString(); } return bean.getBizId(); } private void visit(String binding, Document document, Document owningDocument, Relation owningRelation, Bean bean, Customer customer, Set<String> visited) { if (bean == null) { if (owningRelation != null) { String owningRelationName = owningRelation.getName(); String bindingWithoutThisRelationName = binding.substring(0, binding.length() - owningRelationName.length()); // have we seen a relation with this name before int index = bindingWithoutThisRelationName.lastIndexOf(owningRelationName); if (index >= 0) { index += owningRelationName.length() + 1; String potentialCircularBinding = binding.substring(index) + '.'; if ((index - potentialCircularBinding.length()) >= 0) { // enough in the binding to create the prior binding String bindingPriorToPotentialCircularBinding = binding.substring(index - potentialCircularBinding.length(), index); if (bindingPriorToPotentialCircularBinding.equals(potentialCircularBinding)) { return; } } } } } else { String key = determineVisitedKey(bean, owningDocument, owningRelation); if (visited.contains(key)) { return; } visited.add(key); } StringBuilder sb = new StringBuilder(64); try { if (accept(binding, document, owningDocument, owningRelation, bean)) { Module owningModule = customer.getModule(document.getOwningModuleName()); // NB visit relations in the order they are defined in the documents. for (Attribute attribute : document.getAllAttributes()) { if (attribute instanceof Relation) { if ((! visitInverses) && (attribute instanceof Inverse)) { continue; } String relationName = attribute.getName(); Document relatedDocument = owningModule.getDocument(customer, ((Relation) attribute).getDocumentName()); Relation childRelation = (Relation) attribute; // association or one to one inverse if ((childRelation instanceof Association) || ((childRelation instanceof Inverse) && InverseCardinality.one.equals(((Inverse) childRelation).getCardinality()))) { Bean child = (bean == null) ? null : (Bean) Binder.get(bean, relationName); if ((child != null) || visitNulls) { // If we have a child bean instance, check for a polymorphic reference if (child != null) { String childBizModule = child.getBizModule(); String childBizDocument = child.getBizDocument(); if (! (relatedDocument.getOwningModuleName().equals(childBizModule) && relatedDocument.getName().equals(childBizDocument))) { relatedDocument = customer.getModule(childBizModule).getDocument(customer, childBizDocument); child = Util.deproxy(child); } } sb.setLength(0); if (binding.length() != 0) { sb.append(binding).append('.'); } sb.append(relationName); visit(sb.toString(), relatedDocument, document, childRelation, child, customer, visited); } } else { // collection or many-sided inverse @SuppressWarnings("unchecked") List<Bean> children = (bean == null) ? null : (List<Bean>) Binder.get(bean, relationName); if (children != null) { int i = 0; for (Bean child : children) { if (child != null) { // Check for a polymorphic child reference String childBizModule = child.getBizModule(); String childBizDocument = child.getBizDocument(); if (! (relatedDocument.getOwningModuleName().equals(childBizModule) && relatedDocument.getName().equals(childBizDocument))) { relatedDocument = customer.getModule(childBizModule).getDocument(customer, childBizDocument); child = Util.deproxy(child); } sb.setLength(0); if (binding.length() != 0) { sb.append(binding).append('.'); } sb.append(relationName).append('[').append(i).append(']'); visit(sb.toString(), relatedDocument, document, childRelation, child, customer, visited); } i++; } if ((i == 0) && visitNulls) { // no elements in the collection sb.setLength(0); if (binding.length() != 0) { sb.append(binding).append('.'); } sb.append(relationName); visit(sb.toString(), relatedDocument, document, childRelation, null, customer, visited); } } else { sb.setLength(0); if (binding.length() != 0) { sb.append(binding).append('.'); } sb.append(relationName); visit(sb.toString(), relatedDocument, document, childRelation, null, customer, visited); } } } } Document parentDocument = document.getParentDocument(customer); if ((parentDocument != null) && // child document, not a hierarchical document (! document.getName().equals(parentDocument.getName()))) { Bean parent = (bean == null) ? null : (Bean) Binder.get(bean, ChildBean.PARENT_NAME); if ((parent != null) || visitNulls) { // If we have a parent bean instance, check for a polymorphic reference if (parent != null) { String parentBizModule = parent.getBizModule(); String parentBizDocument = parent.getBizDocument(); if (! (parentDocument.getOwningModuleName().equals(parentBizModule) && parentDocument.getName().equals(parentBizDocument))) { parentDocument = customer.getModule(parentBizModule).getDocument(customer, parentBizDocument); parent = Util.deproxy(parent); } } sb.setLength(0); if (binding.length() != 0) { sb.append(binding).append('.'); } sb.append(ChildBean.PARENT_NAME); visit(sb.toString(), parentDocument, document, null, parent, customer, visited); } } } } catch (MetaDataException e) { throw e; } catch (DomainException e) { throw e; } catch (Exception e) { throw new DomainException(e); } } /** * Accept the reference. * * @param binding * @param document * @param owningDocument The owning document that got us here (by recursion) * @param owningRelation The owning document's relation that got us here (by recursion) * @param bean * @return <code>false</code> to terminate, <code>true</code> to continue. * @throws Exception */ protected abstract boolean accept(String binding, Document document, Document owningDocument, Relation owningRelation, Bean bean) throws Exception; }
package com.intellij.openapi.wm.impl; import com.intellij.ide.DataManager; import com.intellij.ide.GeneralSettings; import com.intellij.ide.RecentProjectsManager; import com.intellij.ide.ui.UISettings; import com.intellij.ide.ui.UISettingsListener; import com.intellij.ide.ui.customization.CustomizableActionsSchemas; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.wm.ex.ActionToolbarEx; import com.intellij.openapi.wm.ex.StatusBarEx; import com.intellij.openapi.wm.impl.status.StatusBarImpl; import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeScreen; import javax.swing.*; import java.awt.*; /** * @author Anton Katilin * @author Vladimir Kondratyev */ // Made public and non-final for Fabrique public class IdeRootPane extends JRootPane{ /** * Toolbar and status bar. */ private JComponent myToolbar; private StatusBarImpl myStatusBar; /** * Current <code>ToolWindowsPane</code>. If there is no such pane then this field is null. */ private ToolWindowsPane myToolWindowsPane; private final MyUISettingsListenerImpl myUISettingsListener; private JPanel myContentPane; private ActionManager myActionManager; private UISettings myUISettings; private static Component myWelcomePane; IdeRootPane(ActionManager actionManager, UISettings uiSettings, DataManager dataManager, KeymapManager keymapManager){ myActionManager = actionManager; myUISettings = uiSettings; updateToolbar(); createStatusBar(); updateStatusBarVisibility(); myContentPane.add(myStatusBar,BorderLayout.SOUTH); myUISettingsListener=new MyUISettingsListenerImpl(); setJMenuBar(new IdeMenuBar(myActionManager, dataManager, keymapManager)); if (!GeneralSettings.getInstance().isReopenLastProject() || RecentProjectsManager.getInstance().getLastProjectPath() == null) { myWelcomePane = WelcomeScreen.createWelcomePanel(); myContentPane.add(myWelcomePane); } } /** * Invoked when enclosed frame is being shown. */ public final void addNotify(){ super.addNotify(); myUISettings.addUISettingsListener(myUISettingsListener); } /** * Invoked when enclosed frame is being disposed. */ public final void removeNotify(){ myUISettings.removeUISettingsListener(myUISettingsListener); super.removeNotify(); } /** * Sets current tool windows pane (panel where all tool windows are located). * If <code>toolWindowsPane</code> is <code>null</code> then the method just removes * the current tool windows pane. */ final void setToolWindowsPane(final ToolWindowsPane toolWindowsPane) { final JComponent contentPane = (JComponent)getContentPane(); if(myToolWindowsPane != null){ contentPane.remove(myToolWindowsPane); } if (myWelcomePane != null) { contentPane.remove(myWelcomePane); myWelcomePane = null; } myToolWindowsPane = toolWindowsPane; if(myToolWindowsPane != null) { contentPane.add(myToolWindowsPane,BorderLayout.CENTER); } else { myWelcomePane = WelcomeScreen.createWelcomePanel(); contentPane.add(myWelcomePane); } contentPane.revalidate(); } protected final Container createContentPane(){ myContentPane = new JPanel(new BorderLayout()); myContentPane.setBackground(Color.GRAY); return myContentPane; } void updateToolbar() { if (myToolbar != null) { myContentPane.remove(myToolbar); } myToolbar = createToolbar(); myContentPane.add(myToolbar,BorderLayout.NORTH); updateToolbarVisibility(); myContentPane.revalidate(); } void updateMainMenuActions(){ ((IdeMenuBar)menuBar).updateMenuActions(); } private JComponent createToolbar() { ActionGroup group = (ActionGroup)CustomizableActionsSchemas.getInstance().getCorrectedAction(IdeActions.GROUP_MAIN_TOOLBAR); final ActionToolbarEx toolBar=(ActionToolbarEx)myActionManager.createActionToolbar( ActionPlaces.MAIN_TOOLBAR, group, true ); toolBar.setLayoutPolicy(ActionToolbarEx.WRAP_LAYOUT_POLICY); return toolBar.getComponent(); } private void createStatusBar() { myStatusBar = new StatusBarImpl(myActionManager, myUISettings); } final StatusBarEx getStatusBar() { return myStatusBar; } private void updateToolbarVisibility(){ myToolbar.setVisible(myUISettings.SHOW_MAIN_TOOLBAR); } private void updateStatusBarVisibility(){ myStatusBar.setVisible(myUISettings.SHOW_STATUS_BAR); } private final class MyUISettingsListenerImpl implements UISettingsListener{ public final void uiSettingsChanged(final UISettings source){ updateToolbarVisibility(); updateStatusBarVisibility(); } } }
/** * @author cdr */ package com.intellij.unscramble; import com.intellij.execution.ExecutionManager; import com.intellij.execution.ExecutionRegistry; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.runners.JavaProgramRunner; import com.intellij.execution.ui.*; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.GuiUtils; import com.intellij.ui.TextFieldWithHistory; import com.intellij.util.ArrayUtil; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class UnscrambleDialog extends DialogWrapper{ @NonNls private static final String PROPERTY_LOG_FILE_HISTORY_URLS = "UNSCRAMBLE_LOG_FILE_URL"; @NonNls private static final String PROPERTY_LOG_FILE_LAST_URL = "UNSCRAMBLE_LOG_FILE_LAST_URL"; @NonNls private static final String PROPERTY_UNSCRAMBLER_NAME_USED = "UNSCRAMBLER_NAME_USED"; private final Project myProject; private JPanel myEditorPanel; private JPanel myLogFileChooserPanel; private JComboBox myUnscrambleChooser; private JPanel myPanel; private Editor myEditor; private TextFieldWithHistory myLogFile; private JCheckBox myUseUnscrambler; private JPanel myUnscramblePanel; public UnscrambleDialog(Project project) { super(false); myProject = project; populateRegisteredUnscramblerList(); myUnscrambleChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { UnscrambleSupport unscrambleSupport = getSelectedUnscrambler(); GuiUtils.enableChildren(myLogFileChooserPanel, unscrambleSupport != null); } }); myUseUnscrambler.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { useUnscramblerChanged(); } }); createLogFileChooser(); createEditor(); reset(); setTitle(IdeBundle.message("unscramble.dialog.title")); init(); } private void useUnscramblerChanged() { boolean selected = myUseUnscrambler.isSelected(); GuiUtils.enableChildren(myUnscramblePanel, selected, myUseUnscrambler); } private void reset() { final List<String> savedUrls = getSavedLogFileUrls(); myLogFile.setHistorySize(10); myLogFile.setHistory(savedUrls); String lastUrl = getLastUsedLogUrl(); if (lastUrl == null && !savedUrls.isEmpty()) { lastUrl = savedUrls.get(savedUrls.size() - 1); } if (lastUrl != null) { myLogFile.setText(lastUrl); myLogFile.setSelectedItem(lastUrl); } final UnscrambleSupport selectedUnscrambler = getSavedUnscrambler(); final int count = myUnscrambleChooser.getItemCount(); int index = 0; if (selectedUnscrambler != null) { for (int i = 0; i < count; i++) { final UnscrambleSupport unscrambleSupport = (UnscrambleSupport)myUnscrambleChooser.getItemAt(i); if (unscrambleSupport != null && Comparing.strEqual(unscrambleSupport.getPresentableName(), selectedUnscrambler.getPresentableName())) { index = i; break; } } } if (count > 0) { myUseUnscrambler.setEnabled(true); myUnscrambleChooser.setSelectedIndex(index); myUseUnscrambler.setSelected(selectedUnscrambler != null); } else { myUseUnscrambler.setEnabled(false); } useUnscramblerChanged(); pasteTextFromClipboard(); } public static String getLastUsedLogUrl() { return PropertiesComponent.getInstance().getValue(PROPERTY_LOG_FILE_LAST_URL); } public static UnscrambleSupport getSavedUnscrambler() { final List<UnscrambleSupport> registeredUnscramblers = getRegisteredUnscramblers(); final String savedUnscramblerName = PropertiesComponent.getInstance().getValue(PROPERTY_UNSCRAMBLER_NAME_USED); UnscrambleSupport selectedUnscrambler = null; for (final UnscrambleSupport unscrambleSupport : registeredUnscramblers) { if (Comparing.strEqual(unscrambleSupport.getPresentableName(), savedUnscramblerName)) { selectedUnscrambler = unscrambleSupport; } } return selectedUnscrambler; } public static List<String> getSavedLogFileUrls() { final List<String> res = new ArrayList<String>(); final String savedUrl = PropertiesComponent.getInstance().getValue(PROPERTY_LOG_FILE_HISTORY_URLS); final String[] strings = savedUrl == null ? ArrayUtil.EMPTY_STRING_ARRAY : savedUrl.split(":::"); for (int i = 0; i != strings.length; ++i) { res.add(strings[i]); } return res; } private void pasteTextFromClipboard() { String text = getTextInClipboard(); if (text != null) { final String text1 = text; Runnable runnable = new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { myEditor.getDocument().insertString(0, StringUtil.convertLineSeparators(text1)); } }); } }; CommandProcessor.getInstance().executeCommand(myProject, runnable, "", this); } } public static String getTextInClipboard() { String text = null; try { Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(UnscrambleDialog.class); if (contents != null) { text = (String)contents.getTransferData(DataFlavor.stringFlavor); } } catch (Exception ex) { } return text; } private UnscrambleSupport getSelectedUnscrambler() { if (!myUseUnscrambler.isSelected()) return null; return (UnscrambleSupport)myUnscrambleChooser.getSelectedItem(); } private void createEditor() { EditorFactory editorFactory = EditorFactory.getInstance(); Document document = editorFactory.createDocument(""); myEditor = editorFactory.createEditor(document); EditorSettings settings = myEditor.getSettings(); settings.setFoldingOutlineShown(false); settings.setLineMarkerAreaShown(false); settings.setLineNumbersShown(false); settings.setRightMarginShown(false); EditorPanel editorPanel = new EditorPanel(myEditor); editorPanel.setPreferredSize(new Dimension(600, 400)); myEditorPanel.setLayout(new BorderLayout()); myEditorPanel.add(editorPanel, BorderLayout.CENTER); } protected Action[] createActions(){ return new Action[]{new NormalizeTextAction(), getOKAction(), getCancelAction(), getHelpAction()}; } private void createLogFileChooser() { myLogFile = new TextFieldWithHistory(); JPanel panel = GuiUtils.constructFieldWithBrowseButton(myLogFile, new ActionListener() { public void actionPerformed(ActionEvent e) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(); VirtualFile[] files = FileChooser.chooseFiles(myLogFile, descriptor); if (files.length != 0) { myLogFile.setText(FileUtil.toSystemDependentName(files[files.length-1].getPath())); } } }); myLogFileChooserPanel.setLayout(new BorderLayout()); myLogFileChooserPanel.add(panel, BorderLayout.CENTER); } private void populateRegisteredUnscramblerList() { List<UnscrambleSupport> unscrambleComponents = getRegisteredUnscramblers(); //myUnscrambleChooser.addItem(null); for (final UnscrambleSupport unscrambleSupport : unscrambleComponents) { myUnscrambleChooser.addItem(unscrambleSupport); } myUnscrambleChooser.setRenderer(new DefaultListCellRenderer() { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); UnscrambleSupport unscrambleSupport = (UnscrambleSupport)value; setText(unscrambleSupport == null ? IdeBundle.message("unscramble.no.unscrambler.item") : unscrambleSupport.getPresentableName()); return this; } }); } private static List<UnscrambleSupport> getRegisteredUnscramblers() { List<UnscrambleSupport> unscrambleComponents = new ArrayList<UnscrambleSupport>(); final UnscrambleSupport[] components = ApplicationManager.getApplication().getComponents(UnscrambleSupport.class); return Arrays.asList(components); } protected JComponent createCenterPanel() { return myPanel; } public void dispose() { EditorFactory editorFactory = EditorFactory.getInstance(); editorFactory.releaseEditor(myEditor); if (isOK()){ final List list = myLogFile.getHistory(); String res = null; for (Object aList : list) { final String s = (String)aList; if (res == null) { res = s; } else { res = res + ":::" + s; } } PropertiesComponent.getInstance().setValue(PROPERTY_LOG_FILE_HISTORY_URLS, res); UnscrambleSupport selectedUnscrambler = getSelectedUnscrambler(); PropertiesComponent.getInstance().setValue(PROPERTY_UNSCRAMBLER_NAME_USED, selectedUnscrambler == null ? null : selectedUnscrambler.getPresentableName()); PropertiesComponent.getInstance().setValue(PROPERTY_LOG_FILE_LAST_URL, myLogFile.getText()); } super.dispose(); } private final class NormalizeTextAction extends AbstractAction { public NormalizeTextAction(){ putValue(Action.NAME, IdeBundle.message("unscramble.normalize.button")); putValue(DEFAULT_ACTION, Boolean.FALSE); } public void actionPerformed(ActionEvent e){ String text = myEditor.getDocument().getText(); text = normalizeText(text); final String newText = text; CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), newText); } }); } }, "", null); } } static String normalizeText(@NonNls String text) { StringBuilder builder = new StringBuilder(text.length()); String[] lines = text.split("\n"); boolean first = true; for (String line : lines) { if (!first && mustHaveNewLineBefore(line)) { builder.append("\n"); if (line.startsWith("\"")) builder.append("\n"); // Additional linebreak for thread names } first = false; builder.append(line); } return builder.toString(); } private static boolean mustHaveNewLineBefore(String line) { final int nonws = CharArrayUtil.shiftForward(line, 0, " \t"); if (nonws < line.length()) { line = line.substring(nonws); } if (line.startsWith("at")) return true; // Start of the new stackframe entry if (line.startsWith("Caused")) return true; // Caused by message if (line.startsWith("- locked")) return true; // Locked a monitor logging if (line.startsWith("\"")) return true; // Start of the new thread (thread name) return false; } private static final class EditorPanel extends JPanel implements DataProvider{ private final Editor myEditor; public EditorPanel(Editor editor) { super(new BorderLayout()); myEditor = editor; add(myEditor.getComponent()); } public Object getData(String dataId) { if (DataConstants.EDITOR.equals(dataId)) { return myEditor; } return null; } } protected void doOKAction() { if (performUnscramble()) { myLogFile.addCurrentTextToHistory(); close(OK_EXIT_CODE); } } public void doHelpAction() { HelpManager.getInstance().invokeHelp("find.analyzeStackTrace"); } private boolean performUnscramble() { UnscrambleSupport selectedUnscrambler = getSelectedUnscrambler(); return showUnscrambledText(selectedUnscrambler, myLogFile.getText(), myProject, myEditor.getDocument().getText()); } static boolean showUnscrambledText(UnscrambleSupport unscrambleSupport, String logName, Project project, String textToUnscramble) { String unscrambledTrace = unscrambleSupport == null ? textToUnscramble : unscrambleSupport.unscramble(project,textToUnscramble, logName); if (unscrambledTrace == null) return false; final ConsoleView consoleView = addConsole(project); consoleView.print(unscrambledTrace+"\n", ConsoleViewContentType.ERROR_OUTPUT); consoleView.performWhenNoDeferredOutput( new Runnable() { public void run() { consoleView.scrollTo(0); } } ); return true; } private static ConsoleView addConsole(final Project project){ final ConsoleView consoleView = new ConsoleViewImpl(project); final JavaProgramRunner defaultRunner = ExecutionRegistry.getInstance().getDefaultRunner(); final DefaultActionGroup toolbarActions = new DefaultActionGroup(); final RunContentDescriptor descriptor = new RunContentDescriptor(consoleView, null, new MyConsolePanel(consoleView, toolbarActions), IdeBundle.message("unscramble.unscrambled.stacktrace.tab")) { public boolean isContentReuseProhibited() { return true; } }; toolbarActions.add(new CloseAction(defaultRunner, descriptor, project)); ExecutionManager.getInstance(project).getContentManager().showRunContent(defaultRunner, descriptor); return consoleView; } private static final class MyConsolePanel extends JPanel { public MyConsolePanel(ExecutionConsole consoleView, ActionGroup toolbarActions) { super(new BorderLayout()); JPanel toolbarPanel = new JPanel(new BorderLayout()); toolbarPanel.add(ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, toolbarActions,false).getComponent()); add(toolbarPanel, BorderLayout.WEST); add(consoleView.getComponent(), BorderLayout.CENTER); } } protected String getDimensionServiceKey(){ return "#com.intellij.unscramble.UnscrambleDialog"; } public JComponent getPreferredFocusedComponent() { return myEditor.getContentComponent(); } }
/** * @author cdr */ package com.intellij.unscramble; import com.intellij.execution.ExecutionManager; import com.intellij.execution.ExecutionRegistry; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.runners.JavaProgramRunner; import com.intellij.execution.ui.*; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.GuiUtils; import com.intellij.ui.TextFieldWithHistory; import com.intellij.util.ArrayUtil; import org.jetbrains.annotations.NonNls; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; public class UnscrambleDialog extends DialogWrapper{ @NonNls private static final String PROPERTY_LOG_FILE_HISTORY_URLS = "UNSCRAMBLE_LOG_FILE_URL"; @NonNls private static final String PROPERTY_LOG_FILE_LAST_URL = "UNSCRAMBLE_LOG_FILE_LAST_URL"; @NonNls private static final String PROPERTY_UNSCRAMBLER_NAME_USED = "UNSCRAMBLER_NAME_USED"; private final Project myProject; private JPanel myEditorPanel; private JPanel myLogFileChooserPanel; private JComboBox myUnscrambleChooser; private JPanel myPanel; private Editor myEditor; private TextFieldWithHistory myLogFile; private JCheckBox myUseUnscrambler; private JPanel myUnscramblePanel; public UnscrambleDialog(Project project) { super(false); myProject = project; populateRegisteredUnscramblerList(); myUnscrambleChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { UnscrambleSupport unscrambleSupport = getSelectedUnscrambler(); GuiUtils.enableChildren(myLogFileChooserPanel, unscrambleSupport != null); } }); myUseUnscrambler.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { useUnscramblerChanged(); } }); createLogFileChooser(); createEditor(); reset(); setTitle(IdeBundle.message("unscramble.dialog.title")); init(); } private void useUnscramblerChanged() { boolean selected = myUseUnscrambler.isSelected(); GuiUtils.enableChildren(myUnscramblePanel, selected, myUseUnscrambler); } private void reset() { final List<String> savedUrls = getSavedLogFileUrls(); myLogFile.setHistorySize(10); myLogFile.setHistory(savedUrls); String lastUrl = getLastUsedLogUrl(); if (lastUrl == null && !savedUrls.isEmpty()) { lastUrl = savedUrls.get(savedUrls.size() - 1); } if (lastUrl != null) { myLogFile.setText(lastUrl); myLogFile.setSelectedItem(lastUrl); } final UnscrambleSupport selectedUnscrambler = getSavedUnscrambler(); final int count = myUnscrambleChooser.getItemCount(); int index = 0; if (selectedUnscrambler != null) { for (int i = 0; i < count; i++) { final UnscrambleSupport unscrambleSupport = (UnscrambleSupport)myUnscrambleChooser.getItemAt(i); if (unscrambleSupport != null && Comparing.strEqual(unscrambleSupport.getPresentableName(), selectedUnscrambler.getPresentableName())) { index = i; break; } } } if (count > 0) { myUseUnscrambler.setEnabled(true); myUnscrambleChooser.setSelectedIndex(index); myUseUnscrambler.setSelected(selectedUnscrambler != null); } else { myUseUnscrambler.setEnabled(false); } useUnscramblerChanged(); pasteTextFromClipboard(); } public static String getLastUsedLogUrl() { return PropertiesComponent.getInstance().getValue(PROPERTY_LOG_FILE_LAST_URL); } public static UnscrambleSupport getSavedUnscrambler() { final List<UnscrambleSupport> registeredUnscramblers = getRegisteredUnscramblers(); final String savedUnscramblerName = PropertiesComponent.getInstance().getValue(PROPERTY_UNSCRAMBLER_NAME_USED); UnscrambleSupport selectedUnscrambler = null; for (final UnscrambleSupport unscrambleSupport : registeredUnscramblers) { if (Comparing.strEqual(unscrambleSupport.getPresentableName(), savedUnscramblerName)) { selectedUnscrambler = unscrambleSupport; } } return selectedUnscrambler; } public static List<String> getSavedLogFileUrls() { final List<String> res = new ArrayList<String>(); final String savedUrl = PropertiesComponent.getInstance().getValue(PROPERTY_LOG_FILE_HISTORY_URLS); final String[] strings = savedUrl == null ? ArrayUtil.EMPTY_STRING_ARRAY : savedUrl.split(":::"); for (int i = 0; i != strings.length; ++i) { res.add(strings[i]); } return res; } private void pasteTextFromClipboard() { String text = getTextInClipboard(); if (text != null) { final String text1 = text; Runnable runnable = new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { myEditor.getDocument().insertString(0, StringUtil.convertLineSeparators(text1)); } }); } }; CommandProcessor.getInstance().executeCommand(myProject, runnable, "", this); } } public static String getTextInClipboard() { String text = null; try { Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(UnscrambleDialog.class); if (contents != null) { text = (String)contents.getTransferData(DataFlavor.stringFlavor); } } catch (Exception ex) { } return text; } private UnscrambleSupport getSelectedUnscrambler() { if (!myUseUnscrambler.isSelected()) return null; return (UnscrambleSupport)myUnscrambleChooser.getSelectedItem(); } private void createEditor() { EditorFactory editorFactory = EditorFactory.getInstance(); Document document = editorFactory.createDocument(""); myEditor = editorFactory.createEditor(document); EditorSettings settings = myEditor.getSettings(); settings.setFoldingOutlineShown(false); settings.setLineMarkerAreaShown(false); settings.setLineNumbersShown(false); settings.setRightMarginShown(false); EditorPanel editorPanel = new EditorPanel(myEditor); editorPanel.setPreferredSize(new Dimension(600, 400)); myEditorPanel.setLayout(new BorderLayout()); myEditorPanel.add(editorPanel, BorderLayout.CENTER); } protected Action[] createActions(){ return new Action[]{new NormalizeTextAction(), getOKAction(), getCancelAction(), getHelpAction()}; } private void createLogFileChooser() { myLogFile = new TextFieldWithHistory(); JPanel panel = GuiUtils.constructFieldWithBrowseButton(myLogFile, new ActionListener() { public void actionPerformed(ActionEvent e) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(); VirtualFile[] files = FileChooser.chooseFiles(myLogFile, descriptor); if (files.length != 0) { myLogFile.setText(FileUtil.toSystemDependentName(files[files.length-1].getPath())); } } }); myLogFileChooserPanel.setLayout(new BorderLayout()); myLogFileChooserPanel.add(panel, BorderLayout.CENTER); } private void populateRegisteredUnscramblerList() { List<UnscrambleSupport> unscrambleComponents = getRegisteredUnscramblers(); //myUnscrambleChooser.addItem(null); for (final UnscrambleSupport unscrambleSupport : unscrambleComponents) { myUnscrambleChooser.addItem(unscrambleSupport); } myUnscrambleChooser.setRenderer(new DefaultListCellRenderer() { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); UnscrambleSupport unscrambleSupport = (UnscrambleSupport)value; setText(unscrambleSupport == null ? IdeBundle.message("unscramble.no.unscrambler.item") : unscrambleSupport.getPresentableName()); return this; } }); } private static List<UnscrambleSupport> getRegisteredUnscramblers() { List<UnscrambleSupport> unscrambleComponents = new ArrayList<UnscrambleSupport>(); Class[] interfaces = ApplicationManager.getApplication().getComponentInterfaces(); for (final Class<?> anInterface : interfaces) { Object component = ApplicationManager.getApplication().getComponent(anInterface); if (component instanceof UnscrambleSupport) { unscrambleComponents.add((UnscrambleSupport)component); } } return unscrambleComponents; } protected JComponent createCenterPanel() { return myPanel; } public void dispose() { EditorFactory editorFactory = EditorFactory.getInstance(); editorFactory.releaseEditor(myEditor); if (isOK()){ final List list = myLogFile.getHistory(); String res = null; for (Object aList : list) { final String s = (String)aList; if (res == null) { res = s; } else { res = res + ":::" + s; } } PropertiesComponent.getInstance().setValue(PROPERTY_LOG_FILE_HISTORY_URLS, res); UnscrambleSupport selectedUnscrambler = getSelectedUnscrambler(); PropertiesComponent.getInstance().setValue(PROPERTY_UNSCRAMBLER_NAME_USED, selectedUnscrambler == null ? null : selectedUnscrambler.getPresentableName()); PropertiesComponent.getInstance().setValue(PROPERTY_LOG_FILE_LAST_URL, myLogFile.getText()); } super.dispose(); } private final class NormalizeTextAction extends AbstractAction { public NormalizeTextAction(){ putValue(Action.NAME, IdeBundle.message("unscramble.normalize.button")); putValue(DEFAULT_ACTION, Boolean.FALSE); } public void actionPerformed(ActionEvent e){ String text = myEditor.getDocument().getText(); text = normalizeText(text); final String newText = text; CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), newText); } }); } }, "", null); } } static String normalizeText(@NonNls String text) { // move 'at' to the line start text = text.replaceAll("\\nat\\n", "\nat "); text = text.replaceAll("(\\S)[\\s&&[^\\n]]*at ", "$1\n at "); text = text.replaceAll("(\\S)\\nat ", "$1\n at "); // merge (inadvertently) splitted lines (unless next line begins with 'at' or 'Caused by') text = text.replaceAll("\\s*\\n\\s*+([^aC]|(a[^t])|[^Ca]|(C[^a])|(Ca[^u])|(Cau[^s])|(Caus[^e])|(Cause[^d]))", "$1"); // remove empty lines text = text.replaceAll("(\\n\\s*)+\\n", "\n"); return text; } private static final class EditorPanel extends JPanel implements DataProvider{ private final Editor myEditor; public EditorPanel(Editor editor) { super(new BorderLayout()); myEditor = editor; add(myEditor.getComponent()); } public Object getData(String dataId) { if (DataConstants.EDITOR.equals(dataId)) { return myEditor; } return null; } } protected void doOKAction() { if (performUnscramble()) { myLogFile.addCurrentTextToHistory(); close(OK_EXIT_CODE); } } public void doHelpAction() { HelpManager.getInstance().invokeHelp("find.analyzeStackTrace"); } private boolean performUnscramble() { UnscrambleSupport selectedUnscrambler = getSelectedUnscrambler(); return showUnscrambledText(selectedUnscrambler, myLogFile.getText(), myProject, myEditor.getDocument().getText()); } static boolean showUnscrambledText(UnscrambleSupport unscrambleSupport, String logName, Project project, String textToUnscramble) { String unscrambledTrace = unscrambleSupport == null ? textToUnscramble : unscrambleSupport.unscramble(project,textToUnscramble, logName); if (unscrambledTrace == null) return false; final ConsoleView consoleView = addConsole(project); consoleView.print(unscrambledTrace+"\n", ConsoleViewContentType.ERROR_OUTPUT); consoleView.performWhenNoDeferredOutput( new Runnable() { public void run() { consoleView.scrollTo(0); } } ); return true; } private static ConsoleView addConsole(final Project project){ final ConsoleView consoleView = new ConsoleViewImpl(project); final JavaProgramRunner defaultRunner = ExecutionRegistry.getInstance().getDefaultRunner(); final DefaultActionGroup toolbarActions = new DefaultActionGroup(); final RunContentDescriptor descriptor = new RunContentDescriptor(consoleView, null, new MyConsolePanel(consoleView, toolbarActions), IdeBundle.message("unscramble.unscrambled.stacktrace.tab")) { public boolean isContentReuseProhibited() { return true; } }; toolbarActions.add(new CloseAction(defaultRunner, descriptor, project)); ExecutionManager.getInstance(project).getContentManager().showRunContent(defaultRunner, descriptor); return consoleView; } private static final class MyConsolePanel extends JPanel { public MyConsolePanel(ExecutionConsole consoleView, ActionGroup toolbarActions) { super(new BorderLayout()); JPanel toolbarPanel = new JPanel(new BorderLayout()); toolbarPanel.add(ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, toolbarActions,false).getComponent()); add(toolbarPanel, BorderLayout.WEST); add(consoleView.getComponent(), BorderLayout.CENTER); } } protected String getDimensionServiceKey(){ return "#com.intellij.unscramble.UnscrambleDialog"; } public JComponent getPreferredFocusedComponent() { return myEditor.getContentComponent(); } }
/** * @author cdr */ package com.intellij.unscramble; import com.intellij.execution.ExecutionManager; import com.intellij.execution.Executor; import com.intellij.execution.executors.DefaultRunExecutor; import com.intellij.execution.filters.TextConsoleBuilderFactory; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.execution.ui.ExecutionConsole; import com.intellij.execution.ui.RunContentDescriptor; import com.intellij.execution.ui.actions.CloseAction; import com.intellij.ide.IdeBundle; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.EditorSettings; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileChooser.FileChooser; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.*; import com.intellij.util.ArrayUtil; import com.intellij.util.text.CharArrayUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class UnscrambleDialog extends DialogWrapper{ @NonNls private static final String PROPERTY_LOG_FILE_HISTORY_URLS = "UNSCRAMBLE_LOG_FILE_URL"; @NonNls private static final String PROPERTY_LOG_FILE_LAST_URL = "UNSCRAMBLE_LOG_FILE_LAST_URL"; @NonNls private static final String PROPERTY_UNSCRAMBLER_NAME_USED = "UNSCRAMBLER_NAME_USED"; private static final Icon PAUSE_ICON = IconLoader.getIcon("/debugger/threadStates/paused.png"); private static final Icon LOCKED_ICON = IconLoader.getIcon("/debugger/threadStates/locked.png"); private static final Icon RUNNING_ICON = IconLoader.getIcon("/debugger/threadStates/running.png"); private static final Icon SOCKET_ICON = IconLoader.getIcon("/debugger/threadStates/socket.png"); private static final Icon IDLE_ICON = IconLoader.getIcon("/debugger/threadStates/idle.png"); private static final Icon EDT_BUSY_ICON = IconLoader.getIcon("/debugger/threadStates/edtBusy.png"); private static final Icon IO_ICON = IconLoader.getIcon("/debugger/threadStates/io.png"); private final Project myProject; private JPanel myEditorPanel; private JPanel myLogFileChooserPanel; private JComboBox myUnscrambleChooser; private JPanel myPanel; private Editor myEditor; private TextFieldWithHistory myLogFile; private JCheckBox myUseUnscrambler; private JPanel myUnscramblePanel; public UnscrambleDialog(Project project) { super(false); myProject = project; populateRegisteredUnscramblerList(); myUnscrambleChooser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { UnscrambleSupport unscrambleSupport = getSelectedUnscrambler(); GuiUtils.enableChildren(myLogFileChooserPanel, unscrambleSupport != null); } }); myUseUnscrambler.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { useUnscramblerChanged(); } }); createLogFileChooser(); createEditor(); reset(); setTitle(IdeBundle.message("unscramble.dialog.title")); init(); } private void useUnscramblerChanged() { boolean selected = myUseUnscrambler.isSelected(); GuiUtils.enableChildren(myUnscramblePanel, selected, myUseUnscrambler); } private void reset() { final List<String> savedUrls = getSavedLogFileUrls(); myLogFile.setHistorySize(10); myLogFile.setHistory(savedUrls); String lastUrl = getLastUsedLogUrl(); if (lastUrl == null && !savedUrls.isEmpty()) { lastUrl = savedUrls.get(savedUrls.size() - 1); } if (lastUrl != null) { myLogFile.setText(lastUrl); myLogFile.setSelectedItem(lastUrl); } final UnscrambleSupport selectedUnscrambler = getSavedUnscrambler(); final int count = myUnscrambleChooser.getItemCount(); int index = 0; if (selectedUnscrambler != null) { for (int i = 0; i < count; i++) { final UnscrambleSupport unscrambleSupport = (UnscrambleSupport)myUnscrambleChooser.getItemAt(i); if (unscrambleSupport != null && Comparing.strEqual(unscrambleSupport.getPresentableName(), selectedUnscrambler.getPresentableName())) { index = i; break; } } } if (count > 0) { myUseUnscrambler.setEnabled(true); myUnscrambleChooser.setSelectedIndex(index); myUseUnscrambler.setSelected(selectedUnscrambler != null); } else { myUseUnscrambler.setEnabled(false); } useUnscramblerChanged(); pasteTextFromClipboard(); } public static String getLastUsedLogUrl() { return PropertiesComponent.getInstance().getValue(PROPERTY_LOG_FILE_LAST_URL); } @Nullable public static UnscrambleSupport getSavedUnscrambler() { final List<UnscrambleSupport> registeredUnscramblers = getRegisteredUnscramblers(); final String savedUnscramblerName = PropertiesComponent.getInstance().getValue(PROPERTY_UNSCRAMBLER_NAME_USED); UnscrambleSupport selectedUnscrambler = null; for (final UnscrambleSupport unscrambleSupport : registeredUnscramblers) { if (Comparing.strEqual(unscrambleSupport.getPresentableName(), savedUnscramblerName)) { selectedUnscrambler = unscrambleSupport; } } return selectedUnscrambler; } public static List<String> getSavedLogFileUrls() { final List<String> res = new ArrayList<String>(); final String savedUrl = PropertiesComponent.getInstance().getValue(PROPERTY_LOG_FILE_HISTORY_URLS); final String[] strings = savedUrl == null ? ArrayUtil.EMPTY_STRING_ARRAY : savedUrl.split(":::"); for (int i = 0; i != strings.length; ++i) { res.add(strings[i]); } return res; } private void pasteTextFromClipboard() { String text = getTextInClipboard(); if (text != null) { setText(text); } } public final void setText(@NotNull final String text) { Runnable runnable = new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { final Document document = myEditor.getDocument(); document.replaceString(0, document.getTextLength(), StringUtil.convertLineSeparators(text)); } }); } }; CommandProcessor.getInstance().executeCommand(myProject, runnable, "", this); } public static String getTextInClipboard() { String text = null; try { Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(UnscrambleDialog.class); if (contents != null) { text = (String)contents.getTransferData(DataFlavor.stringFlavor); } } catch (Exception ex) { } return text; } @Nullable private UnscrambleSupport getSelectedUnscrambler() { if (!myUseUnscrambler.isSelected()) return null; return (UnscrambleSupport)myUnscrambleChooser.getSelectedItem(); } private void createEditor() { EditorFactory editorFactory = EditorFactory.getInstance(); Document document = editorFactory.createDocument(""); myEditor = editorFactory.createEditor(document); EditorSettings settings = myEditor.getSettings(); settings.setFoldingOutlineShown(false); settings.setLineMarkerAreaShown(false); settings.setLineNumbersShown(false); settings.setRightMarginShown(false); EditorPanel editorPanel = new EditorPanel(myEditor); editorPanel.setPreferredSize(new Dimension(600, 400)); myEditorPanel.setLayout(new BorderLayout()); myEditorPanel.add(editorPanel, BorderLayout.CENTER); } protected Action[] createActions(){ return new Action[]{new NormalizeTextAction(), getOKAction(), getCancelAction(), getHelpAction()}; } private void createLogFileChooser() { myLogFile = new TextFieldWithHistory(); JPanel panel = GuiUtils.constructFieldWithBrowseButton(myLogFile, new ActionListener() { public void actionPerformed(ActionEvent e) { FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(); VirtualFile[] files = FileChooser.chooseFiles(myLogFile, descriptor); if (files.length != 0) { myLogFile.setText(FileUtil.toSystemDependentName(files[files.length-1].getPath())); } } }); myLogFileChooserPanel.setLayout(new BorderLayout()); myLogFileChooserPanel.add(panel, BorderLayout.CENTER); } private void populateRegisteredUnscramblerList() { List<UnscrambleSupport> unscrambleComponents = getRegisteredUnscramblers(); //myUnscrambleChooser.addItem(null); for (final UnscrambleSupport unscrambleSupport : unscrambleComponents) { myUnscrambleChooser.addItem(unscrambleSupport); } myUnscrambleChooser.setRenderer(new DefaultListCellRenderer() { public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); UnscrambleSupport unscrambleSupport = (UnscrambleSupport)value; setText(unscrambleSupport == null ? IdeBundle.message("unscramble.no.unscrambler.item") : unscrambleSupport.getPresentableName()); return this; } }); } private static List<UnscrambleSupport> getRegisteredUnscramblers() { final UnscrambleSupport[] components = Extensions.getExtensions(UnscrambleSupport.EP_NAME); return Arrays.asList(components); } protected JComponent createCenterPanel() { return myPanel; } public void dispose() { EditorFactory editorFactory = EditorFactory.getInstance(); editorFactory.releaseEditor(myEditor); if (isOK()){ final List list = myLogFile.getHistory(); String res = null; for (Object aList : list) { final String s = (String)aList; if (res == null) { res = s; } else { res = res + ":::" + s; } } PropertiesComponent.getInstance().setValue(PROPERTY_LOG_FILE_HISTORY_URLS, res); UnscrambleSupport selectedUnscrambler = getSelectedUnscrambler(); PropertiesComponent.getInstance().setValue(PROPERTY_UNSCRAMBLER_NAME_USED, selectedUnscrambler == null ? null : selectedUnscrambler.getPresentableName()); PropertiesComponent.getInstance().setValue(PROPERTY_LOG_FILE_LAST_URL, myLogFile.getText()); } super.dispose(); } private final class NormalizeTextAction extends AbstractAction { public NormalizeTextAction(){ putValue(Action.NAME, IdeBundle.message("unscramble.normalize.button")); putValue(DEFAULT_ACTION, Boolean.FALSE); } public void actionPerformed(ActionEvent e){ String text = myEditor.getDocument().getText(); text = normalizeText(text); final String newText = text; CommandProcessor.getInstance().executeCommand(myProject, new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { myEditor.getDocument().replaceString(0, myEditor.getDocument().getTextLength(), newText); } }); } }, "", null); } } static String normalizeText(@NonNls String text) { StringBuilder builder = new StringBuilder(text.length()); String[] lines = text.split("\n"); boolean first = true; boolean inAuxInfo = false; for (String line : lines) { //noinspection HardCodedStringLiteral if (!inAuxInfo && (line.startsWith("JNI global references") || line.trim().equals("Heap"))) { builder.append("\n"); inAuxInfo = true; } if (inAuxInfo) { builder.append(line).append("\n"); continue; } if (!first && mustHaveNewLineBefore(line)) { builder.append("\n"); if (line.startsWith("\"")) builder.append("\n"); // Additional linebreak for thread names } first = false; int i = builder.lastIndexOf("\n"); CharSequence lastLine = i == -1 ? builder : builder.subSequence(i + 1, builder.length()); if (lastLine.toString().matches("\\s*at") && !line.matches("\\s+.*")) builder.append(" "); // separate 'at' from file name builder.append(line); } return builder.toString(); } private static boolean mustHaveNewLineBefore(String line) { final int nonws = CharArrayUtil.shiftForward(line, 0, " \t"); if (nonws < line.length()) { line = line.substring(nonws); } if (line.startsWith("at")) return true; // Start of the new stackframe entry if (line.startsWith("Caused")) return true; // Caused by message if (line.startsWith("- locked")) return true; // "Locked a monitor" logging if (line.startsWith("- waiting")) return true; // "Waiting for monitor" logging if (line.startsWith("- parking to wait")) return true; if (line.startsWith("java.lang.Thread.State")) return true; if (line.startsWith("\"")) return true; // Start of the new thread (thread name) return false; } private static final class EditorPanel extends JPanel implements DataProvider{ private final Editor myEditor; public EditorPanel(Editor editor) { super(new BorderLayout()); myEditor = editor; add(myEditor.getComponent()); } public Object getData(String dataId) { if (DataConstants.EDITOR.equals(dataId)) { return myEditor; } return null; } } protected void doOKAction() { if (performUnscramble()) { myLogFile.addCurrentTextToHistory(); close(OK_EXIT_CODE); } } public void doHelpAction() { HelpManager.getInstance().invokeHelp("find.analyzeStackTrace"); } private boolean performUnscramble() { UnscrambleSupport selectedUnscrambler = getSelectedUnscrambler(); return showUnscrambledText(selectedUnscrambler, myLogFile.getText(), myProject, myEditor.getDocument().getText()); } static boolean showUnscrambledText(UnscrambleSupport unscrambleSupport, String logName, Project project, String textToUnscramble) { String unscrambledTrace = unscrambleSupport == null ? textToUnscramble : unscrambleSupport.unscramble(project,textToUnscramble, logName); if (unscrambledTrace == null) return false; List<ThreadState> threadStates = ThreadDumpParser.parse(unscrambledTrace); final ConsoleView consoleView = addConsole(project, threadStates); printStacktrace(consoleView, unscrambledTrace); return true; } private static void printStacktrace(final ConsoleView consoleView, final String unscrambledTrace) { consoleView.clear(); consoleView.print(unscrambledTrace+"\n", ConsoleViewContentType.ERROR_OUTPUT); consoleView.performWhenNoDeferredOutput( new Runnable() { public void run() { consoleView.scrollTo(0); } } ); } private static ConsoleView addConsole(final Project project, final List<ThreadState> threadDump) { final ConsoleView consoleView = TextConsoleBuilderFactory.getInstance().createBuilder(project).getConsole(); final DefaultActionGroup toolbarActions = new DefaultActionGroup(); JComponent consoleComponent = threadDump.size() > 1 ? new ThreadDumpPanel(consoleView, toolbarActions, threadDump) : new MyConsolePanel(consoleView, toolbarActions); final RunContentDescriptor descriptor = new RunContentDescriptor(consoleView, null, consoleComponent, IdeBundle.message("unscramble.unscrambled.stacktrace.tab")) { public boolean isContentReuseProhibited() { return true; } }; final Executor executor = DefaultRunExecutor.getRunExecutorInstance(); toolbarActions.add(new CloseAction(executor, descriptor, project)); for (AnAction action: consoleView.createUpDownStacktraceActions()) { toolbarActions.add(action); } ExecutionManager.getInstance(project).getContentManager().showRunContent(executor, descriptor); return consoleView; } private static final class MyConsolePanel extends JPanel { public MyConsolePanel(ExecutionConsole consoleView, ActionGroup toolbarActions) { super(new BorderLayout()); JPanel toolbarPanel = new JPanel(new BorderLayout()); toolbarPanel.add(ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, toolbarActions,false).getComponent()); add(toolbarPanel, BorderLayout.WEST); add(consoleView.getComponent(), BorderLayout.CENTER); } } private static class ThreadDumpPanel extends JPanel { public ThreadDumpPanel(final ConsoleView consoleView, final ActionGroup toolbarActions, final List<ThreadState> threadDump) { super(new BorderLayout()); JPanel leftPanel = new JPanel(new BorderLayout()); leftPanel.add(ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, toolbarActions,false).getComponent(), BorderLayout.WEST); final JList threadList = new JList(threadDump.toArray(new ThreadState[threadDump.size()])); threadList.setCellRenderer(new ColoredListCellRenderer() { protected void customizeCellRenderer(final JList list, final Object value, final int index, final boolean selected, final boolean hasFocus) { ThreadState threadState = (ThreadState) value; setIcon(getThreadStateIcon(threadState)); if (!selected) { ThreadState selectedThread = (ThreadState)list.getSelectedValue(); if (threadState.isDeadlocked()) { setBackground(LightColors.RED); } else if (selectedThread != null && threadState.isHoldingLock(selectedThread)) { setBackground(Color.YELLOW); } else { setBackground(UIUtil.getListBackground()); } } SimpleTextAttributes attrs = getAttributes(threadState); append(threadState.getName() + " (", attrs); String detail = threadState.getThreadStateDetail(); if (detail == null) { detail = threadState.getState().trim(); } if (detail.length() > 30) { detail = detail.substring(0, 30) + "..."; } append(detail, attrs); append(")", attrs); if (threadState.getExtraState() != null) { append(" [" + threadState.getExtraState() + "]", attrs); } } }); threadList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); threadList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(final ListSelectionEvent e) { int index = threadList.getSelectedIndex(); if (index >= 0) { ThreadState selection = threadDump.get(index); printStacktrace(consoleView, selection.getStackTrace()); } else { printStacktrace(consoleView, ""); } threadList.repaint(); } }); leftPanel.add(new JScrollPane(threadList), BorderLayout.CENTER); add(leftPanel, BorderLayout.WEST); add(consoleView.getComponent(), BorderLayout.CENTER); } private static Icon getThreadStateIcon(final ThreadState threadState) { if (threadState.isSleeping()) { return PAUSE_ICON; } if (threadState.isLocked()) { return LOCKED_ICON; } if (threadState.getOperation() == ThreadOperation.Socket) { return SOCKET_ICON; } if (threadState.getOperation() == ThreadOperation.IO) { return IO_ICON; } if (threadState.isEDT()) { if ("idle".equals(threadState.getThreadStateDetail())) { return IDLE_ICON; } return EDT_BUSY_ICON; } return RUNNING_ICON; } private static SimpleTextAttributes getAttributes(final ThreadState threadState) { if (threadState.isSleeping()) { return SimpleTextAttributes.GRAY_ATTRIBUTES; } if (threadState.isEmptyStackTrace() || ThreadDumpParser.isKnownJdkThread(threadState)) { return new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, Color.GRAY.brighter()); } if (threadState.isEDT()) { return SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES; } return SimpleTextAttributes.REGULAR_ATTRIBUTES; } } protected String getDimensionServiceKey(){ return "#com.intellij.unscramble.UnscrambleDialog"; } public JComponent getPreferredFocusedComponent() { return myEditor.getContentComponent(); } }
import java.security.SecureRandom; import javax.crypto.spec.PBEKeySpec; import javax.crypto.SecretKeyFactory; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.Base64; public class PasswordStorage { @SuppressWarnings("serial") static public class InvalidHashException extends Exception { public InvalidHashException(String message) { super(message); } public InvalidHashException(String message, Throwable source) { super(message, source); } } @SuppressWarnings("serial") static public class CannotPerformOperationException extends Exception { public CannotPerformOperationException(String message) { super(message); } public CannotPerformOperationException(String message, Throwable source) { super(message, source); } } public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; // These constants may be changed without breaking existing hashes. public static final int SALT_BYTE_SIZE = 24; public static final int HASH_BYTE_SIZE = 18; public static final int PBKDF2_ITERATIONS = 64000; // These constants define the encoding and may not be changed. public static final int HASH_SECTIONS = 5; public static final int HASH_ALGORITHM_INDEX = 0; public static final int ITERATION_INDEX = 1; public static final int HASH_SIZE_INDEX = 2; public static final int SALT_INDEX = 3; public static final int PBKDF2_INDEX = 4; public static String createHash(String password) throws CannotPerformOperationException { return createHash(password.toCharArray()); } public static String createHash(char[] password) throws CannotPerformOperationException { // Generate a random salt SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_BYTE_SIZE]; random.nextBytes(salt); // Hash the password byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE); int hashSize = hash.length; // format: algorithm:iterations:hashSize:salt:hash String parts = "sha1:" + PBKDF2_ITERATIONS + ":" + hashSize + ":" + toBase64(salt) + ":" + toBase64(hash); return parts; } public static boolean verifyPassword(String password, String correctHash) throws CannotPerformOperationException, InvalidHashException { return verifyPassword(password.toCharArray(), correctHash); } public static boolean verifyPassword(char[] password, String correctHash) throws CannotPerformOperationException, InvalidHashException { // Decode the hash into its parameters String[] params = correctHash.split(":"); if (params.length != HASH_SECTIONS) { throw new InvalidHashException( "Fields are missing from the password hash." ); } // Currently, Java only supports SHA1. if (!params[HASH_ALGORITHM_INDEX].equals("sha1")) { throw new CannotPerformOperationException( "Unsupported hash type." ); } int iterations = 0; try { iterations = Integer.parseInt(params[ITERATION_INDEX]); } catch (NumberFormatException ex) { throw new InvalidHashException( "Could not parse the iteration count as an integer.", ex ); } if (iterations < 1) { throw new InvalidHashException( "Invalid number of iterations. Must be >= 1." ); } byte[] salt = null; try { salt = fromBase64(params[SALT_INDEX]); } catch (IllegalArgumentException ex) { throw new InvalidHashException( "Base64 decoding of salt failed.", ex ); } byte[] hash = null; try { hash = fromBase64(params[PBKDF2_INDEX]); } catch (IllegalArgumentException ex) { throw new InvalidHashException( "Base64 decoding of pbkdf2 output failed.", ex ); } int storedHashSize = 0; try { storedHashSize = Integer.parseInt(params[HASH_SIZE_INDEX]); } catch (NumberFormatException ex) { throw new InvalidHashException( "Could not parse the hash size as an integer.", ex ); } if (storedHashSize != hash.length) { throw new InvalidHashException( "Hash length doesn't match stored hash length." ); } // Compute the hash of the provided password, using the same salt, // iteration count, and hash length byte[] testHash = pbkdf2(password, salt, iterations, hash.length); // Compare the hashes in constant time. The password is correct if // both hashes match. return slowEquals(hash, testHash); } private static boolean slowEquals(byte[] a, byte[] b) { int diff = a.length ^ b.length; for(int i = 0; i < a.length && i < b.length; i++) diff |= a[i] ^ b[i]; return diff == 0; } private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) throws CannotPerformOperationException { try { PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); return skf.generateSecret(spec).getEncoded(); } catch (NoSuchAlgorithmException ex) { throw new CannotPerformOperationException( "Hash algorithm not supported.", ex ); } catch (InvalidKeySpecException ex) { throw new CannotPerformOperationException( "Invalid key spec.", ex ); } } private static byte[] fromBase64(String hex) throws IllegalArgumentException { return Base64.getDecoder().decode(hex); } private static String toBase64(byte[] array) { return Base64.getEncoder().encodeToString(array); } }
package org.jasig.portal.utils; import org.jasig.portal.PortalException; import org.jasig.portal.utils.SAX2FilterImpl; import org.xml.sax.ContentHandler; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; /** * <p>Replaces all relative URLs with absolute URLs.</p> * @author Ken Weiner, kweiner@interactivebusiness.com * @version $Revision$ */ public abstract class AbsoluteURLFilter extends SAX2FilterImpl { protected String baseUrl = null; /** * A constructor which receives a ContentHandler to which * filtered SAX events are passed * @param handler the ContentHandler to which filtered SAX events are passed */ protected AbsoluteURLFilter(ContentHandler handler) { super(handler); } /** * A factory method that uses a mime type to decide which kind of * AbsoluteURLFilter to instantiate. There are currently two types * of markup supported: XHTML and WML. * @param mimeType the mime type of the markup that this filter will apply to * @param baseUrl the base URL to be prepended to relative URL paths * @param handler the ContentHandler to which to pass along filtered SAX events * @return filter the AbsoluteURLFilter matching the mimeType */ public static final AbsoluteURLFilter newAbsoluteURLFilter(String mimeType, String baseUrl, ContentHandler handler) throws PortalException { AbsoluteURLFilter filter = null; if (mimeType != null) { if (mimeType.equals("text/html")) { filter = new XHTMLURLFilter(handler); } else if (mimeType.equals("text/vnd.wap.wml")) { filter = new WMLURLFilter(handler); } else { throw new PortalException("AbsoluteURLFilter.newAbsoluteURLFilter(): Unable to locate AbsoluteURLFilter for mime type '" + mimeType + "'"); } } else { throw new PortalException("AbsoluteURLFilter.newAbsoluteURLFilter(): Unable to create AbsoluteURLFilter. Mime type is null."); } filter.baseUrl = baseUrl; return filter; } /** * A helper method for derivitive classes to easily fix an attribute * that has a relative URL value * @param elementName the element name containing an attribute of name attName * @param attName the name of the attribute of elementName * @param qName the name of the current element * @param atts the attibutes of the current element * @param attsImpl the attributes implementation to contain the new attribute value */ protected final void fixURL(String elementName, String attName, String qName, Attributes atts, AttributesImpl attsImpl) { if (qName.equalsIgnoreCase(elementName)) { String attValue = atts.getValue(attName); if (attValue != null) { // Assume that if the attribute value exists and doesn't contain a // colon, or if the URL contains a colon and there's a // slash before the first colon, then it is a relative URL // absolute URLs) int i = attValue.indexOf(":"); if ( i==-1 || (i!=-1 && attValue.substring(0, i).indexOf("/")!=-1) ) { if (attValue.startsWith("/")) { // Prepend the scheme and the host to the attribute value (HTTP) i = baseUrl.indexOf(": if (i != -1) attValue = baseUrl.substring(0, baseUrl.indexOf("/", i+3)).concat(attValue); } else if (attValue.trim().equals("")) attValue = baseUrl; else if (attValue.trim().startsWith("?") || attValue.trim().startsWith(" attValue = baseUrl.concat(attValue); else attValue = baseUrl.substring(0, baseUrl.lastIndexOf("/")+1).concat(attValue); if (attValue.indexOf("/../") != -1) attValue = removeUpDirs(attValue); } int index = atts.getIndex(attName); attsImpl.setAttribute(index, atts.getURI(index), atts.getLocalName(index), attName, atts.getType(index), attValue); } } } /** * Removes the '/../' in the URL. Some browsers and web * servers do not handle these URLs correctly. * @param url the absolute URL generated from the fixURL method */ private String removeUpDirs(String url) { String begin; String end; int upDirIndex; int endProtoIndex = url.indexOf(" while ((upDirIndex=url.indexOf("/../")) != -1) { end = url.substring(upDirIndex+4); begin = url.substring(0, upDirIndex); if (begin.indexOf("/", endProtoIndex+2) != -1) begin = url.substring(0, begin.lastIndexOf("/")+1); else begin += "/"; url = begin.concat(end); } return url; } }
package scalac.symtab.classfile; import ch.epfl.lamp.util.Position; import scalac.*; import scalac.util.*; import scalac.symtab.*; import java.io.*; import java.util.*; //todo: don't keep statics module in scope. public class ClassfileParser implements ClassfileConstants { static final int CLASS_ATTR = SOURCEFILE_ATTR | INNERCLASSES_ATTR | SYNTHETIC_ATTR | DEPRECATED_ATTR | META_ATTR | SCALA_ATTR; static final int METH_ATTR = CODE_ATTR | EXCEPTIONS_ATTR | SYNTHETIC_ATTR | DEPRECATED_ATTR | META_ATTR; static final int FIELD_ATTR = CONSTANT_VALUE_ATTR | SYNTHETIC_ATTR | DEPRECATED_ATTR | META_ATTR; protected Global global; protected AbstractFileReader in; protected Symbol c; protected Type ctype; protected Scope locals; protected Scope statics; protected JavaTypeFactory make; protected Signatures sigs; protected ConstantPool pool; protected AttributeParser attrib; protected Definitions defs; public ClassfileParser(Global global, AbstractFileReader in, Symbol c) { this.global = global; this.in = in; this.c = c; this.ctype = c.typeConstructor(); this.make = new JavaTypeCreator(global); this.sigs = new Signatures(global, make); this.pool = new ConstantPool(in, sigs); this.attrib = new AttributeParser(in, pool, this); this.defs = global.definitions; } /** parse the classfile and throw IO exception if there is an * error in the classfile structure */ public void parse() throws IOException { try { if (in.nextInt() != JAVA_MAGIC) throw new IOException("illegal start of class file"); int minorVersion = in.nextChar(); int majorVersion = in.nextChar(); if ((majorVersion < JAVA_MAJOR_VERSION) || ((majorVersion == JAVA_MAJOR_VERSION) && (minorVersion < JAVA_MINOR_VERSION))) throw new IOException("class file has wrong version " + majorVersion + "." + minorVersion + ", should be " + JAVA_MAJOR_VERSION + "." + JAVA_MINOR_VERSION); pool.indexPool(); int flags = in.nextChar(); Name name = readClassName(in.nextChar()); if (c.fullName() != name) throw new IOException("class file '" + c.fullName() + "' contains wrong class " + name); // todo: correct flag transition c.flags = transFlags(flags); if ((c.flags & Modifiers.DEFERRED) != 0) c.flags = c.flags & ~Modifiers.DEFERRED | Modifiers.ABSTRACTCLASS; Type supertpe = readClassType(in.nextChar()); Type[] basetpes = new Type[in.nextChar() + 1]; this.locals = new Scope(); this.statics = new Scope(); // set type of class Type classType = Type.compoundType(basetpes, locals, c); c.setInfo(classType, Symbol.FIRST_ID); // set type of statics Symbol staticsClass = c.module().moduleClass(); if (staticsClass.isModuleClass()) { Type staticsInfo = Type.compoundType(Type.EMPTY_ARRAY, statics, staticsClass); staticsClass.setInfo(staticsInfo, Symbol.FIRST_ID); c.module().setInfo(Type.TypeRef(staticsClass.owner().thisType(), staticsClass, Type.EMPTY_ARRAY)); } basetpes[0] = supertpe; for (int i = 1; i < basetpes.length; i++) basetpes[i] = readClassType(in.nextChar()); int fieldCount = in.nextChar(); for (int i = 0; i < fieldCount; i++) parseField(); int methodCount = in.nextChar(); for (int i = 0; i < methodCount; i++) parseMethod(); Symbol constr = c.primaryConstructor(); if (!constr.isInitialized()) { constr.setInfo( Type.MethodType(Symbol.EMPTY_ARRAY, ctype), Symbol.FIRST_ID); if ((c.flags & Modifiers.INTERFACE) == 0) constr.flags |= Modifiers.PRIVATE; } attrib.readAttributes(c, classType, CLASS_ATTR); //System.out.println("dynamic class: " + c); //System.out.println("statics class: " + staticsClass); //System.out.println("module: " + c.module()); //System.out.println("modules class: " + c.module().type().symbol()); } catch (RuntimeException e) { if (global.debug) e.printStackTrace(); String s = e.getMessage() == null ? "" : " (" +e.getMessage()+ ")"; throw new IOException("bad class file" + s); } } /** convert Java modifiers into Scala flags */ public int transFlags(int flags) { int res = 0; if (((flags & 0x0007) == 0) || ((flags & 0x0002) != 0)) res |= Modifiers.PRIVATE; else if ((flags & 0x0004) != 0) res |= Modifiers.PROTECTED; if ((flags & 0x0400) != 0) res |= Modifiers.DEFERRED; if ((flags & 0x0010) != 0) res |= Modifiers.FINAL; if ((flags & 0x0200) != 0) res |= Modifiers.INTERFACE | Modifiers.TRAIT | Modifiers.ABSTRACTCLASS; return res | Modifiers.JAVA; } /** read a class name */ protected Name readClassName(int i) { return (Name)pool.readPool(i); } /** read a class name and return the corresponding class type */ protected Type readClassType(int i) { if (i == 0) return defs.ANY_TYPE; Type res = defs.getJavaType((Name)pool.readPool(i)); if (res == Type.ErrorType) global.error("unknown class reference " + pool.readPool(i)); return res; } /** read a signature and return it as a type */ protected Type readType(int i) { Name sig = pool.readExternal(i); return sigs.sigToType(Name.names, sig.index, sig.length()); } /** read a field */ protected void parseField() { int flags = in.nextChar(); Name name = (Name)pool.readPool(in.nextChar()); Type type = readType(in.nextChar()); int mods = transFlags(flags); if ((flags & 0x0010) == 0) mods |= Modifiers.MUTABLE; Symbol owner = c; if ((flags & 0x0008) != 0) owner = c.module().moduleClass(); Symbol s = new TermSymbol(Position.NOPOS, name, owner, mods); s.setInfo(type, Symbol.FIRST_ID); attrib.readAttributes(s, type, FIELD_ATTR); ((flags & 0x0008) != 0 ? statics : locals).enterOrOverload(s); } /** read a method */ protected void parseMethod() { int flags = in.nextChar(); Name name = (Name)pool.readPool(in.nextChar()); Type type = readType(in.nextChar()); if (CONSTR_N.equals(name)) { Symbol s = TermSymbol.newConstructor(c, transFlags(flags)); // kick out package visible or // private constructors if (((flags & 0x0002) != 0) || ((flags & 0x0007) == 0)) { attrib.readAttributes(s, type, METH_ATTR); return; } switch (type) { case MethodType(Symbol[] vparams, _): type = Type.MethodType(vparams, ctype); break; default: throw new ApplicationError(); } s.setInfo(type, Symbol.FIRST_ID); attrib.readAttributes(s, type, METH_ATTR); Symbol constr = c.primaryConstructor(); if (constr.isInitialized()) constr = c.addConstructor(); s.copyTo(constr); //System.out.println(c + " " + c.allConstructors() + ":" + c.allConstructors().info());//debug //System.out.println("-- enter " + s); } else { Symbol s = new TermSymbol( Position.NOPOS, name, ((flags & 0x0008) != 0) ? c.module().moduleClass() : c, transFlags(flags)); s.setInfo(type, Symbol.FIRST_ID); attrib.readAttributes(s, type, METH_ATTR); ((flags & 0x0008) != 0 ? statics : locals).enterOrOverload(s); } } }
package setGame; public class Board extends Deck { public Board() { super(0); } public Board(int deckSize) { super(deckSize); } public Board(Card[] cards) { super(cards); } public Set removeRevealedSet() { if (this.size() < 3) { return null; } for (int i = 0; i < this.size() - 2; i++) { for (int k = i + 1; k < this.size() - 1; k++) { for (int j = k + 1; j < this.size(); j++) { Card card1 = this.get(i); Card card2 = this.get(k); Card card3 = this.get(j); Set set = new Set(card1, card2, card3); if (set.isValid()) { this.remove(j); this.remove(k); this.remove(i); return set; } } } } return null; } public boolean hasSetRevealed() { if (this.size() < 3) { return false; } for (int i = 0; i < this.size() - 2; i++) { for (int k = i + 1; k < this.size() - 1; k++) { for (int j = k + 1; j < this.size(); j++) { Card card1 = this.get(i); Card card2 = this.get(k); Card card3 = this.get(j); Set set = new Set(card1, card2, card3); if (set.isValid()) { return true; } } } } return false; } }
package edu.uci.ics.hyracks.control.nc.resources.memory; import java.util.concurrent.atomic.AtomicLong; import edu.uci.ics.hyracks.api.resources.memory.IMemoryManager; public class MemoryManager implements IMemoryManager { private final long maxMemory; private final AtomicLong memory; public MemoryManager(long maxMemory) { this.maxMemory = maxMemory; this.memory = new AtomicLong(maxMemory); } @Override public long getMaximumMemory() { return maxMemory; } @Override public long getAvailableMemory() { return memory.get(); } @Override public boolean allocate(long memory) { // commented as now the deallocation is not implemented yet. // if (this.memory.addAndGet(-memory) < 0) { // this.memory.addAndGet(memory); // return false; return true; } @Override public void deallocate(long memory) { this.memory.addAndGet(memory); } }
package org.phenotips.matchingnotification.storage.internal; import org.phenotips.matchingnotification.match.PatientMatch; import org.phenotips.matchingnotification.storage.MatchStorageManager; import org.xwiki.component.annotation.Component; import java.util.Collections; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import org.apache.commons.lang3.StringUtils; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import com.xpn.xwiki.store.hibernate.HibernateSessionFactory; /** * @version $Id$ */ @Component @Singleton public class DefaultMatchStorageManager implements MatchStorageManager { /** Handles persistence. */ @Inject private HibernateSessionFactory sessionFactory; /** Logging helper object. */ @Inject private Logger logger; @Override public void saveMatches(List<PatientMatch> matches) { Session session = this.sessionFactory.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); try { for (PatientMatch match : matches) { session.save(match); } t.commit(); } catch (HibernateException ex) { this.logger.error("ERROR storing matches: [{}]", ex); if (t != null) { t.rollback(); } throw ex; } finally { session.close(); } } @Override public List<PatientMatch> loadAllMatches() { return this.loadMatchesByCriterion(null); } @Override public List<PatientMatch> loadMatchesByIds(List<Long> matchesIds) { if (matchesIds != null && matchesIds.size() > 0) { Criterion criterion = Restrictions.in("id", matchesIds.toArray()); return this.loadMatchesByCriterion(criterion); } else { return Collections.emptyList(); } } @Override public List<PatientMatch> loadMatchesByReferencePatientId(String patientId) { if (StringUtils.isNotEmpty(patientId)) { Criterion criterion = Restrictions.eq("patientId", patientId); return this.loadMatchesByCriterion(criterion); } else { return Collections.emptyList(); } } @SuppressWarnings("unchecked") private List<PatientMatch> loadMatchesByCriterion(Criterion criterion) { List<PatientMatch> matches = null; Session session = this.sessionFactory.getSessionFactory().openSession(); try { Criteria criteria = session.createCriteria(PatientMatch.class); if (criterion != null) { criteria.add(criterion); } matches = criteria.list(); } catch (HibernateException ex) { this.logger.error("loadMatchesByCriterion. Criterion: {}, ERROR: [{}]", criterion, ex); } finally { session.close(); } return matches; } // TODO remove, for debug. @Override public void clearMatches() { List<PatientMatch> matches = loadAllMatches(); Session session = this.sessionFactory.getSessionFactory().openSession(); Transaction t = session.beginTransaction(); try { session.clear(); for (PatientMatch match : matches) { session.delete(match); } t.commit(); } catch (HibernateException ex) { this.logger.error("ERROR deleting matches", ex); if (t != null) { t.rollback(); } throw ex; } finally { session.close(); } } }
package dr.app.seqgen; import dr.evolution.alignment.Alignment; import dr.evolution.alignment.SimpleAlignment; import dr.evolution.datatype.Nucleotides; import dr.evolution.io.NewickImporter; import dr.evolution.sequence.Sequence; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.DefaultBranchRateModel; import dr.evomodel.sitemodel.GammaSiteModel; import dr.evomodel.sitemodel.SiteModel; import dr.evomodel.substmodel.FrequencyModel; import dr.evomodel.substmodel.HKY; import dr.evomodel.substmodel.SubstitutionEpochModel; import dr.inference.model.Parameter; import dr.math.MathUtils; import dr.xml.*; /** Class for performing random sequence generation for a given site model. * Sequences for the leave nodes in the tree are returned as an alignment. * * @author remco@cs.waikato.ac.nz * */ public class SequenceSimulator { /** nr of samples to generate **/ protected int m_nReplications; /** tree used for generating samples **/ protected Tree m_tree; /** site model used for generating samples **/ protected SiteModel m_siteModel; /** branch rate model used for generating samples **/ protected BranchRateModel m_branchRateModel; /** nr of categories in site model **/ int m_categoryCount; /** nr of states in site model **/ int m_stateCount; /** * an array used to transfer transition probabilities */ protected double[][] m_probabilities; /** * Constructor * @param tree * @param siteModel * @param branchRateModel * @param nReplications: nr of samples to generate */ SequenceSimulator(Tree tree, SiteModel siteModel, BranchRateModel branchRateModel, int nReplications) { m_tree = tree; m_siteModel = siteModel; m_branchRateModel = branchRateModel; m_nReplications = nReplications; m_stateCount = m_siteModel.getFrequencyModel().getDataType().getStateCount(); m_categoryCount = m_siteModel.getCategoryCount(); m_probabilities = new double[m_categoryCount][m_stateCount * m_stateCount]; } // c'tor /** * Convert integer representation of sequence into a Sequence * @param seq integer representation of the sequence * @param node used to determine taxon for sequence * @return Sequence */ Sequence intArray2Sequence(int [] seq, NodeRef node) { String sSeq = ""; for (int i = 0; i < m_nReplications; i++) { String c = m_siteModel.getFrequencyModel().getDataType().getCode(seq[i]); sSeq += c; } return new Sequence(m_tree.getNodeTaxon(node), sSeq); } // intArray2Sequence /** * perform the actual sequence generation * @return alignment containing randomly generated sequences for the nodes in the * leaves of the tree */ public Alignment simulate() { NodeRef root = m_tree.getRoot(); double [] categoryProbs = m_siteModel.getCategoryProportions(); int [] category = new int[m_nReplications]; for (int i = 0; i < m_nReplications; i++) { category[i] = MathUtils.randomChoicePDF(categoryProbs); } FrequencyModel frequencyModel = m_siteModel.getFrequencyModel(); int [] seq = new int[m_nReplications]; for (int i = 0; i < m_nReplications; i++) { seq[i] = MathUtils.randomChoicePDF(frequencyModel.getFrequencies()); } SimpleAlignment alignment = new SimpleAlignment(); alignment.setDataType(m_siteModel.getFrequencyModel().getDataType()); traverse(root, seq, category, alignment); return alignment; } // simulate /** * recursively walk through the tree top down, and add sequence to alignment whenever * a leave node is reached. * @param node reference to the current node, for which we visit all children * @param parentSequence randomly generated sequence of the parent node * @param category array of categories for each of the sites * @param alignment */ void traverse(NodeRef node, int [] parentSequence, int [] category, SimpleAlignment alignment) { for (int iChild = 0; iChild < m_tree.getChildCount(node); iChild++) { NodeRef child = m_tree.getChild(node, iChild); for (int i = 0; i < m_categoryCount; i++) { getTransitionProbabilities(m_tree, child, i, m_probabilities[i]); } int [] seq = new int[m_nReplications]; double [] cProb = new double[m_stateCount]; for (int i = 0; i < m_nReplications; i++) { System.arraycopy(m_probabilities[category[i]], parentSequence[i]*m_stateCount, cProb, 0, m_stateCount); seq[i] = MathUtils.randomChoicePDF(cProb); } if (m_tree.getChildCount(child) == 0) { alignment.addSequence(intArray2Sequence(seq, child)); } traverse(m_tree.getChild(node, iChild), seq, category, alignment); } } // traverse void getTransitionProbabilities(Tree tree, NodeRef node, int rateCategory, double[] probs) { NodeRef parent = tree.getParent(node); final double branchRate = m_branchRateModel.getBranchRate(tree, node); // Get the operational time of the branch final double branchTime = branchRate * (tree.getNodeHeight(parent) - tree.getNodeHeight(node)); if (branchTime < 0.0) { throw new RuntimeException("Negative branch length: " + branchTime); } double branchLength = m_siteModel.getRateForCategory(rateCategory) * branchTime; // TODO Hack until SiteRateModel issue is resolved if (m_siteModel.getSubstitutionModel() instanceof SubstitutionEpochModel) { ((SubstitutionEpochModel)m_siteModel.getSubstitutionModel()).getTransitionProbabilities(tree.getNodeHeight(node), tree.getNodeHeight(parent),branchLength, probs); return; } m_siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probs); } // getTransitionProbabilities /** helper method **/ public static void printUsageAndExit() { System.err.println("Usage: java " + SequenceSimulator.class.getName() + " <nr of instantiations>"); System.err.println("where <nr of instantiations> is the number of instantiations to be replciated"); System.exit(0); } // printUsageAndExit /* standard xml parser stuff follows */ public static final String SEQUENCE_SIMULATOR = "sequenceSimulator"; public static final String SITE_MODEL = SiteModel.SITE_MODEL; public static final String TREE = "tree"; // public static final String BRANCH_RATE_MODEL = "branchRateModel"; public static final String REPLICATIONS = "replications"; public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return SEQUENCE_SIMULATOR; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { int nReplications = xo.getIntegerAttribute(REPLICATIONS); Tree tree = (Tree) xo.getChild(Tree.class); SiteModel siteModel = (SiteModel) xo.getChild(SiteModel.class); BranchRateModel rateModel = (BranchRateModel)xo.getChild(BranchRateModel.class); if (rateModel == null) rateModel = new DefaultBranchRateModel(); SequenceSimulator s = new SequenceSimulator(tree, siteModel, rateModel, nReplications); return s.simulate(); } /** generate simple site model, for testing purposes **/
package edu.mit.transitlab; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import org.postgresql.copy.CopyManager; import org.postgresql.core.BaseConnection; import org.postgresql.util.PSQLException; /** * This program should run in a folder of GTFS files and clean and upload them * to the transitlab server. * * @author rad */ public class GTFSuploader { private static Connection dbConnection; private static String startDate; private static String endDate; public static final String COMMA_DELIM_DBL_QUOTE_PATTERN = ",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))"; /** * @param args the command line arguments */ public static void main(String[] args) { try { openDatabaseConnection(); } catch (SQLException ex) { Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { // Get the start and end date from the feed info file. System.out.print("Opening feed_info.txt..."); openFeedInfo(); System.out.println("done."); } catch (IOException | SQLException ex) { System.out.println("Error."); System.exit(1); } try { System.out.print("Opening stops.txt..."); readStops(); System.out.println("done."); } catch (IOException | SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { System.out.print("Opening stop_times.txt..."); readStopTimes(); System.out.println("done."); } catch (IOException | SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { System.out.print("Opening calendar.txt..."); readCalendar(); System.out.println("done."); } catch (IOException | SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { System.out.print("Opening calendar_dates.txt..."); readCalendar_dates(); System.out.println("done."); } catch (IOException | SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { System.out.print("Opening routes.txt..."); readRoutes(); System.out.println("done."); } catch (IOException | SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { System.out.print("Opening trips.txt..."); readTrips(); System.out.println("done."); } catch (IOException | SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { System.out.print("Opening transfers.txt..."); readTransfers(); System.out.println("done."); } catch (IOException | SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { System.out.print("Opening frequencies.txt..."); readFrequencies(); System.out.println("done."); } catch (IOException | SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { System.out.print("Add primary keys and foreign keys to gtfs tables..."); basicKeys(); System.out.println("done."); } catch (SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { System.out.print("Adding geometry table, nearest stop stop matrix, and bus patterns..."); insertStopGeometry(); insertNearestStopStopMatrix(); insertBusPatterns(); System.out.println("done."); } catch (SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { System.out.print("Add primary keys and foreign keys to processed tables..."); advancedKeys(); System.out.println("done."); } catch (SQLException ex) { System.out.println("Error."); Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } try { closeDatabaseConnection(); } catch (SQLException ex) { Logger.getLogger(GTFSuploader.class.getName()).log(Level.SEVERE, null, ex); } } /** * Opens connection to the database and prepares the INSERT statement. * * @throws SQLException */ private static void openDatabaseConnection() throws SQLException { dbConnection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mbta", "java", "java"); } /** * Closes connection to the database if it is open. * * @throws SQLException */ private static void closeDatabaseConnection() throws SQLException { if (!dbConnection.isClosed()) { dbConnection.close(); } } private static void openFeedInfo() throws IOException, SQLException { BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream("feed_info.txt"))); // Skip first row reader.readLine(); String[] row = reader.readLine().split(","); startDate = row[3].substring(1, row[3].lastIndexOf("\"")); endDate = row[4].substring(1, row[3].lastIndexOf("\"")); String feed_date = row[row.length-1].substring(0, row[row.length-1].lastIndexOf("\"")).trim(); String feed_version = row[row.length-2].substring(1).trim(); reader.close(); if (dbConnection.isClosed()) { openDatabaseConnection(); } try { insertFeedInfo(feed_date, feed_version); } catch (PSQLException e) { System.out.println(e); }; // System.out.println(startDate); // System.out.println(endDate); } private static void insertFeedInfo(String feedDate, String feedVersion)throws SQLException { String insertQuery = "INSERT INTO gtfs.feed(\n" + " uploaded, start_date, end_date, feed_date, version)\n" + " VALUES (now(), "+startDate+", "+endDate+", to_date('"+feedDate+"' , 'MM/DD/YY'),'"+feedVersion+"' );"; PreparedStatement insert = dbConnection.prepareStatement(insertQuery); insert.execute(); } private static void readStops() throws IOException, SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createStopsTable(); } catch (PSQLException e) { System.out.println(e); }; BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream("stops.txt"))); PrintStream textOut = new PrintStream( new BufferedOutputStream( new FileOutputStream("stops_prepared.csv", false))); // Skip first row textOut.println(reader.readLine()); String line; int j = 1; for (; (line = reader.readLine()) != null; j++) { String[] row = line.split(COMMA_DELIM_DBL_QUOTE_PATTERN, -1); // The one row with a number if (row[8].startsWith("\"")) { row[8] = row[8].substring(row[8].indexOf("\"") + 1, row[8].lastIndexOf("\"")); } String output = ""; for (int i = 0; i < row.length; i++) { // Putting empty quotes into null values. if (row[i].isEmpty()) { row[i] = "\"\""; } } // Deal with quotes for numbers if (row[8].lastIndexOf("\"") == 1) { row[8] = ""; } for (int i = 0; i < row.length - 1; i++) { // Putting empty quotes into null values. output += row[i] + ","; } output += row[row.length - 1]; textOut.println(output); } textOut.close(); textOut.flush(); reader.close(); CopyManager manager = new CopyManager((BaseConnection) (dbConnection)); try { manager.copyIn("COPY gtfs.stops_" + startDate + "_" + endDate + " FROM STDIN WITH (FORMAT 'csv', HEADER true)", new FileReader("stops_prepared.csv")); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } // if (dbConnection.isClosed()) { // openDatabaseConnection(); // String insertQuery = "INSERT INTO gtfs.stops_" + startDate + "_" + endDate + "\n" // + "VALUES (?, ?, ?, ?, ?, ?, \n" // PreparedStatement insertStops = dbConnection.prepareStatement(insertQuery); // int j = 1; // for (; (line = reader.readLine()) != null; j++) { // String[] row = line.split(COMMA_DELIM_DBL_QUOTE_PATTERN, -1); // try { // for (int i = 1; i < 9; i++) { // if (row[i - 1].lastIndexOf("\"") == 1) { // insertStops.setNull(i, java.sql.Types.VARCHAR); // } else { // if (row[i - 1].startsWith("\"")) { // insertStops.setString(i, row[i - 1].substring(row[i - 1].indexOf("\"") + 1, row[i - 1].lastIndexOf("\""))); // } else { // insertStops.setNull(i, java.sql.Types.VARCHAR); // if (row[8].startsWith("\"")) { // insertStops.setShort(9, Short.parseShort(row[8].substring(1, row[8].lastIndexOf("\"")))); // } else { // if (row[8].isEmpty()) { // insertStops.setNull(9, java.sql.Types.SMALLINT); // } else { // insertStops.setShort(9, Short.parseShort(row[8])); // if (row[9].lastIndexOf("\"") == 1) { // insertStops.setNull(10, java.sql.Types.VARCHAR); // } else { // if (row[9].startsWith("\"")) { // insertStops.setString(10, row[9].substring(row[9].indexOf("\"") + 1, row[9].lastIndexOf("\""))); // } else { // insertStops.setNull(10, java.sql.Types.VARCHAR); // insertStops.addBatch(); // } catch (Exception e) { // System.out.println("Read error on line " + j + " " + e); // insertStops.executeBatch(); // insertStops.close(); } private static void createStopsTable() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.stops_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.stops\n" + "\n" + "WITH (\n" + " OIDS=FALSE\n" + ");\n" + "ALTER TABLE gtfs.stops_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.stops_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.stops_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.stops_" + startDate + "_" + endDate + ";"; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } /*private static void addDataToInsert(PreparedStatement statement, int idx, String data, int sqlType){ case: }*/ private static void readStopTimes() throws IOException, SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createStopsTimesTable(); } catch (PSQLException e) { System.out.println(e); }; CopyManager manager = new CopyManager((BaseConnection) (dbConnection)); try { String createTempStops = "CREATE TEMP TABLE tempstops \n" + "(\n" + " trip_id character varying(64) NOT NULL,\n" + " arrival_time character varying(8) NOT NULL,\n" + " departure_time character varying(8) NOT NULL,\n" + " stop_id character varying(64) NOT NULL,\n" + " stop_sequence smallint NOT NULL,\n" + " stop_headsign character varying(8),\n" + " pickup_type smallint,\n" + " drop_off_type smallint)WITH (\n" + " OIDS=FALSE\n" + ");"; PreparedStatement createTemp = dbConnection.prepareStatement(createTempStops); createTemp.execute(); manager.copyIn("COPY tempstops FROM STDIN WITH (FORMAT 'csv', HEADER true)", new FileReader("stop_times.txt")); String insertQuery = "INSERT INTO gtfs.stop_times_" + startDate + "_" + endDate + " \n" + "(SELECT trip_id, date '1899-12-31' + arrival_time::interval, date '1899-12-31' + departure_time::interval, stop_id, stop_sequence, \n" + " stop_headsign, pickup_type, drop_off_type FROM tempstops);"; PreparedStatement insertStopTimes = dbConnection.prepareStatement(insertQuery); insertStopTimes.execute(); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } } private static void createStopsTimesTable() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.stop_times_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.stop_times)\n" + "\n" + "WITH (\n" + " OIDS=FALSE\n" + ");\n" + "ALTER TABLE gtfs.stop_times_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.stop_times_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.stop_times_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.stop_times_" + startDate + "_" + endDate + ";";; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } private static void readFrequencies() throws IOException, SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createFrequenciesTable(); } catch (PSQLException e) { System.out.println(e); }; CopyManager manager = new CopyManager((BaseConnection) (dbConnection)); try { String createTempStops = "CREATE TEMP TABLE tempfrequencies \n" + "(\n" + " trip_id character varying(64) NOT NULL,\n" + " start_time character varying(8) NOT NULL,\n" + " end_time character varying(8) NOT NULL,\n" + " headway_secs smallint NOT NULL) WITH\n" + "( OIDS=FALSE\n" + ");"; PreparedStatement createTemp = dbConnection.prepareStatement(createTempStops); createTemp.execute(); manager.copyIn("COPY tempfrequencies FROM STDIN WITH (FORMAT 'csv', HEADER true)", new FileReader("frequencies.txt")); String insertQuery = "INSERT INTO gtfs.frequencies_" + startDate + "_" + endDate + " \n" + "(SELECT trip_id, date '1899-12-31' + start_time::interval, date '1899-12-31' + end_time::interval, headway_secs FROM tempfrequencies);"; PreparedStatement insertStopTimes = dbConnection.prepareStatement(insertQuery); insertStopTimes.execute(); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } } private static void createFrequenciesTable() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.frequencies_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.frequencies)\n" + "\n" + "WITH (\n" + " OIDS=FALSE\n" + ");\n" + "ALTER TABLE gtfs.frequencies_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.frequencies_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.frequencies_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.frequencies_" + startDate + "_" + endDate + ";"; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } private static void readCalendar() throws IOException, SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createCalendarTable(); } catch (PSQLException e) { System.out.println(e); }; BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream("calendar.txt"))); PrintStream textOut = new PrintStream( new BufferedOutputStream( new FileOutputStream("calendar_prepared.csv", false))); // Skip first row textOut.println(reader.readLine()); String line; for (; (line = reader.readLine()) != null;) { String[] row = line.split(COMMA_DELIM_DBL_QUOTE_PATTERN, -1); String output = ""; // Convert 0 & 1 to TRUE & FALSE for the table for (int i = 0; i < row.length - 1; i++) { if (i >= 1 && i <= 7) { row[i] = (row[i].equals("1")) ? "TRUE" : "FALSE"; } output += row[i] + ","; } output += row[row.length - 1]; textOut.println(output); } textOut.close(); textOut.flush(); reader.close(); CopyManager manager = new CopyManager((BaseConnection) (dbConnection)); try { manager.copyIn("COPY gtfs.calendar_" + startDate + "_" + endDate + "(\n" + "\"service_id\",\n" + "\"monday\",\n" + "\"tuesday\",\n" + "\"wednesday\",\n" + "\"thursday\",\n" + "\"friday\",\n" + "\"saturday\",\n" + "\"sunday\",\n" + "\"start_date\",\n" + "\"end_date\") FROM STDIN WITH (FORMAT 'csv', HEADER true)", new FileReader("calendar_prepared.csv")); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } } private static void createCalendarTable() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.calendar_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.calendar)\n" + "\n" + "WITH (\n" + " OIDS=FALSE\n" + ");\n" + "ALTER TABLE gtfs.calendar_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.calendar_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.calendar_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.calendar_" + startDate + "_" + endDate + ";"; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } private static void readCalendar_dates() throws IOException, SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createCalendar_datesTable(); } catch (PSQLException ex) { System.out.println(ex.getServerErrorMessage().getMessage()); }; CopyManager manager = new CopyManager((BaseConnection) (dbConnection)); try { manager.copyIn("COPY gtfs.calendar_dates_" + startDate + "_" + endDate + " FROM STDIN WITH (FORMAT 'csv', HEADER true)", new FileReader("calendar_dates.txt")); } catch (PSQLException ex) { System.out.println(ex.getServerErrorMessage().getMessage()); } } private static void createCalendar_datesTable() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.calendar_dates_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.calendar_dates)\n" + "\n" + "WITH (\n" + " OIDS=FALSE\n" + ");\n" + "ALTER TABLE gtfs.calendar_dates_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.calendar_dates_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.calendar_dates_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.calendar_dates_" + startDate + "_" + endDate + ";"; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } private static void readTrips() throws IOException, SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createTripsTable(); } catch (PSQLException e) { System.out.println(e); }; CopyManager manager = new CopyManager((BaseConnection) (dbConnection)); try { manager.copyIn("COPY gtfs.trips_" + startDate + "_" + endDate + " FROM STDIN WITH (FORMAT 'csv', HEADER true)", new FileReader("trips.txt")); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } } private static void createTripsTable() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.trips_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.trips" + ");\n" + "ALTER TABLE gtfs.trips_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.trips_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.trips_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.trips_" + startDate + "_" + endDate + ";"; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } private static void readTransfers() throws IOException, SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createTransfersTable(); } catch (PSQLException e) { System.out.println(e); }; CopyManager manager = new CopyManager((BaseConnection) (dbConnection)); try { manager.copyIn("COPY gtfs.transfers_" + startDate + "_" + endDate + " FROM STDIN WITH (FORMAT 'csv', HEADER true)", new FileReader("transfers.txt")); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } } private static void createTransfersTable() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.transfers_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.transfers)\n" + "\n" + "WITH (\n" + " OIDS=FALSE\n" + ");\n" + "ALTER TABLE gtfs.transfers_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.transfers_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.transfers_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.transfers_" + startDate + "_" + endDate + ";"; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } private static void readRoutes() throws IOException, SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createRoutesTable(); } catch (PSQLException e) { System.out.println(e); }; CopyManager manager = new CopyManager((BaseConnection) (dbConnection)); try { manager.copyIn("COPY gtfs.routes_" + startDate + "_" + endDate + "(\n" + "route_id,\n" + "agency_id,\n" + "route_short_name,\n" + "route_long_name,\n" + "route_desc,\n" + "route_type,\n" + "route_url,\n" + "route_color,\n" + "route_text_color\n" + ") FROM STDIN WITH (FORMAT 'csv', HEADER true)", new FileReader("routes.txt")); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } } private static void createRoutesTable() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.routes_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.routes)\n" + "\n" + "WITH (\n" + " OIDS=FALSE\n" + ");\n" + "ALTER TABLE gtfs.routes_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.routes_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.routes_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.routes_" + startDate + "_" + endDate + ";"; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } private static void insertStopGeometry() throws SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createStopGeometryTable(); } catch (PSQLException e) { System.out.println(e); }; try { String insertQuery = "INSERT INTO gtfs.stops_geog_" + startDate + "_" + endDate + "\n" + " (SELECT stop_id, parent_station, ST_GeogFromText('SRID=4326;POINT(' || stop_lon || ' ' || stop_lat || ')')\n" + ",ST_GeomFromText('POINT(' || stop_lon || ' ' || stop_lat || ')',4326) " + "FROM gtfs.stops_" + startDate + "_" + endDate + " );" + "ALTER TABLE gtfs.stops_geog_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT geog_" + startDate + "_" + endDate + "_stop_id PRIMARY KEY (stop_id);\n" + " ALTER TABLE gtfs.stops_geog_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT _" + startDate + "_" + endDate + "_stop_id FOREIGN KEY (stop_id)\n" + " REFERENCES gtfs.stops_" + startDate + "_" + endDate + " (stop_id) MATCH SIMPLE\n" + " ON UPDATE NO ACTION ON DELETE NO ACTION\n" + " NOT VALID;\n" + " CREATE INDEX geom_index_" + startDate + "_" + endDate + "\n" + " ON gtfs.stops_geog_" + startDate + "_" + endDate + "\n" + " USING gist\n" + " (geom);"; PreparedStatement insert = dbConnection.prepareStatement(insertQuery); insert.execute(); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } } private static void createStopGeometryTable() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.stops_geog_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.stops_geog)\n" + "\n" + "WITH (\n" + " OIDS=FALSE\n" + ");\n" + "ALTER TABLE gtfs.stops_geog_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.stops_geog_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.stops_geog_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.stops_geog_" + startDate + "_" + endDate + ";"; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } private static void insertNearestStopStopMatrix() throws SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createNearestStopStopMatrixTable(); } catch (PSQLException e) { System.out.println(e); }; String insertQuery = "WITH stops AS(\n" + "SELECT DISTINCT stops.stop_id, geog_latlon\n" + "FROM gtfs.stops_" + startDate + "_" + endDate + " stops \n" + "INNER JOIN gtfs.stop_times_" + startDate + "_" + endDate + " stop_times ON stop_times.stop_id = stops.stop_id\n" + "INNER JOIN gtfs.trips_" + startDate + "_" + endDate + " trips ON trips.trip_id = stop_times.trip_id\n" + "INNER JOIN gtfs.routes_" + startDate + "_" + endDate + " routes ON routes.route_id = trips.route_id\n" + "INNER JOIN gtfs.stops_geog_" + startDate + "_" + endDate + " ON gtfs.stops_geog_" + startDate + "_" + endDate + ".stop_id = stops.stop_id\n" + "WHERE route_type = 3\n" + ")\n" + ", nearest_matrix AS (\n" + "\n" + "SELECT stops_geog.stop_id AS next_o, \n" + " (SELECT nearest.stop_id FROM stops nearest WHERE nearest.stop_id != main.stop_id\n" + " ORDER BY CAST(nearest.geog_latlon AS geometry) <-> CAST(stops_geog.geog_latlon AS geometry)\n" + " LIMIT 1) AS nearest_stop\n" + "FROM stops main\n" + "INNER JOIN gtfs.stops_geog_" + startDate + "_" + endDate + " stops_geog ON stops_geog.stop_id = main.stop_id\n" + ")\n" + "\n" + "INSERT INTO gtfs.stop_stop_matrix_" + startDate + "_" + endDate + "\n" + "(SELECT next_o, nearest_stop, CAST(ST_DISTANCE(stops.geog_latlon, o.geog_latlon) AS INT)as nearest_distance\n" + "FROM nearest_matrix\n" + "INNER JOIN stops ON stops.stop_id = nearest_matrix.next_o\n" + "INNER JOIN gtfs.stops_geog_" + startDate + "_" + endDate + " o ON o.stop_id = next_o);"; try { PreparedStatement insert = dbConnection.prepareStatement(insertQuery); insert.execute(); } catch (PSQLException ex) { System.out.println(); System.out.println("Error with: insertNearestStopStopMatrix()"); System.out.println(ex); ex.printStackTrace(); } } private static void createNearestStopStopMatrixTable() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.stop_stop_matrix_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.stop_stop_matrix)\n" + "\n" + "WITH (\n" + " OIDS=FALSE\n" + ");\n" + "ALTER TABLE gtfs.stop_stop_matrix_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.stop_stop_matrix_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.stop_stop_matrix_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.stop_stop_matrix_" + startDate + "_" + endDate + ";"; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } private static void insertBusPatterns() throws SQLException { if (dbConnection.isClosed()) { openDatabaseConnection(); } try { createBus_patterns_Table(); } catch (PSQLException e) { System.out.println(e); }; String insertQuery = "WITH bus_patterns AS(\n" + "SELECT trips.trip_id, stop_id, stop_sequence\n" + " , (lead(CASE WHEN stop_times.stop_id is not null THEN stop_times.stop_id ELSE '0' END) \n" + " OVER (PARTITION BY stop_times.trip_id ORDER BY stop_sequence)) AS next_stop\n" + "FROM gtfs.stop_times_" + startDate + "_" + endDate + " stop_times\n" + "INNER JOIN gtfs.trips_" + startDate + "_" + endDate + " trips\n" + " ON stop_times.trip_id = trips.trip_id\n" + "INNER JOIN gtfs.routes_" + startDate + "_" + endDate + " routes\n" + " ON trips.route_id = routes.route_id \n" + " AND route_short_name !='Shuttle'AND route_type = 3\n" + "\n" + ")\n" + "INSERT INTO gtfs.bus_patterns_" + startDate + "_" + endDate + "\n" + "SELECT CAST(bus_patterns.trip_id AS integer), CAST (bus_patterns.stop_id AS integer)\n" + " , stop_sequence\n" + "/*Use MBTA's distances_between_stops table first, else use postGIS calculated values\n" + " Could improve by using actual shape files*/\n" + " , CAST(COALESCE((SUM(CASE WHEN use_map = 1 THEN distance_between_map\n" + " WHEN distance_between_survey is not null THEN distance_between_survey \n" + " ELSE 0 END) OVER (PARTITION BY bus_patterns.trip_id ORDER BY stop_sequence RANGE UNBOUNDED PRECEDING) \n" + " - (CASE WHEN use_map = 1 THEN distance_between_map\n" + " WHEN use_map = 0 THEN distance_between_survey \n" + " ELSE 0 END))/3.28084 ,\n" + " ST_Distance(ST_TRANSFORM((SELECT geom FROM gtfs.stops_geog_" + startDate + "_" + endDate + " WHERE gtfs.stops_geog_" + startDate + "_" + endDate + ".stop_id = bus_patterns.stop_id),26986)\n" + " , ST_TRANSFORM((SELECT geom FROM gtfs.stops_geog_" + startDate + "_" + endDate + " WHERE gtfs.stops_geog_" + startDate + "_" + endDate + ".stop_id = next_stop),26986)))AS integer)\n" + " \n" + "FROM bus_patterns\n" + " LEFT OUTER JOIN distances_between_stops \n" + " ON distances_between_stops.stop_id_start = bus_patterns.stop_id\n" + " AND next_stop = distances_between_stops.stop_id_end;"; try { PreparedStatement insert = dbConnection.prepareStatement(insertQuery); insert.execute(); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } } private static void createBus_patterns_Table() throws SQLException { String createStopsQuery = "CREATE TABLE IF NOT EXISTS gtfs.bus_patterns_" + startDate + "_" + endDate + "\n" + "(\n" + "LIKE gtfs.bus_patterns)\n" + "\n" + "WITH (\n" + " OIDS=FALSE\n" + ");\n" + "ALTER TABLE gtfs.bus_patterns_" + startDate + "_" + endDate + "\n" + " OWNER TO java;\n" + "GRANT ALL ON TABLE gtfs.bus_patterns_" + startDate + "_" + endDate + " TO radumas;\n" + "GRANT SELECT, REFERENCES ON TABLE gtfs.bus_patterns_" + startDate + "_" + endDate + " TO mbta_researchers;" + "TRUNCATE TABLE gtfs.bus_patterns_" + startDate + "_" + endDate + ";"; PreparedStatement createStops = dbConnection.prepareStatement(createStopsQuery); createStops.execute(); } private static void basicKeys() throws SQLException { String constraintsQuery = "ALTER TABLE gtfs.calendar_" + startDate + "_" + endDate + "\n" + "ADD CONSTRAINT service_id_" + startDate + "_" + endDate + "_key PRIMARY KEY (service_id);\n" + "ALTER TABLE gtfs.calendar_dates_" + startDate + "_" + endDate + "\n" + "ADD CONSTRAINT calendar_service_id_" + startDate + "_" + endDate + "_key PRIMARY KEY (service_id, service_date);\n" + "ALTER TABLE gtfs.frequencies_" + startDate + "_" + endDate + "\n" + "ADD CONSTRAINT frequencies_" + startDate + "_" + endDate + "_trip_id PRIMARY KEY (trip_id);\n" + "ALTER TABLE gtfs.routes_" + startDate + "_" + endDate + "\n" + "ADD CONSTRAINT _" + startDate + "_" + endDate + "_route_id PRIMARY KEY (route_id);\n" + "ALTER TABLE gtfs.stop_times_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT _" + startDate + "_" + endDate + "_trip_id_sequence PRIMARY KEY (trip_id, stop_sequence);\n" + " ALTER TABLE gtfs.stops_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT _" + startDate + "_" + endDate + "_stop_id PRIMARY KEY (stop_id);\n" + " ALTER TABLE gtfs.transfers_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT _" + startDate + "_" + endDate + "_transfer_stop_id PRIMARY KEY (from_stop_id, to_stop_id);\n" + " ALTER TABLE gtfs.trips_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT _" + startDate + "_" + endDate + "_trip_id PRIMARY KEY (trip_id);\n" + " ALTER TABLE gtfs.transfers_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT _" + startDate + "_" + endDate + "_from_stop_id FOREIGN KEY (from_stop_id)\n" + " REFERENCES gtfs.stops_" + startDate + "_" + endDate + " (stop_id) MATCH SIMPLE\n" + " ON UPDATE NO ACTION ON DELETE NO ACTION;\n" + " ALTER TABLE gtfs.stop_times_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT _" + startDate + "_" + endDate + "_stop_id FOREIGN KEY (stop_id)\n" + " REFERENCES gtfs.stops_" + startDate + "_" + endDate + " (stop_id) MATCH SIMPLE\n" + " ON UPDATE NO ACTION ON DELETE NO ACTION;\n" + " ALTER TABLE gtfs.stop_times_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT _" + startDate + "_" + endDate + "_trip_id FOREIGN KEY (trip_id)\n" + " REFERENCES gtfs.trips_" + startDate + "_" + endDate + " (trip_id) MATCH SIMPLE\n" + " ON UPDATE NO ACTION ON DELETE NO ACTION;\n" + " ALTER TABLE gtfs.transfers_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT _" + startDate + "_" + endDate + "_to_stop_id FOREIGN KEY (to_stop_id)\n" + " REFERENCES gtfs.stops_" + startDate + "_" + endDate + " (stop_id) MATCH SIMPLE\n" + " ON UPDATE NO ACTION ON DELETE NO ACTION;\n" + "ALTER TABLE gtfs.frequencies_" + startDate + "_" + endDate + "\n" + "ADD CONSTRAINT _" + startDate + "_" + endDate + "_trip_id FOREIGN KEY (trip_id)\n" + " REFERENCES gtfs.trips_" + startDate + "_" + endDate + " (trip_id) MATCH SIMPLE\n" + " ON UPDATE NO ACTION ON DELETE NO ACTION;\n" + " ALTER TABLE gtfs.trips_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT _" + startDate + "_" + endDate + "_route_id FOREIGN KEY (route_id)\n" + " REFERENCES gtfs.routes_" + startDate + "_" + endDate + " (route_id) MATCH SIMPLE\n" + " ON UPDATE NO ACTION ON DELETE NO ACTION;"; try { PreparedStatement constraints = dbConnection.prepareStatement(constraintsQuery); constraints.execute(); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } } private static void advancedKeys() throws SQLException { String constraintsQuery = "ALTER TABLE gtfs.bus_patterns_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT bus_patterns_" + startDate + "_" + endDate + "_pk PRIMARY KEY (trip_id, stop_sequence);" + "\n ALTER TABLE gtfs.bus_patterns_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT bus_patterns_" + startDate + "_" + endDate + "_stop FOREIGN KEY (stop_id)\n" + " REFERENCES gtfs.stops_" + startDate + "_" + endDate + " (stop_id) MATCH SIMPLE\n" + " ON UPDATE NO ACTION ON DELETE NO ACTION;" + "\n ALTER TABLE gtfs.bus_patterns_" + startDate + "_" + endDate + "\n" + " ADD CONSTRAINT bus_patterns_" + startDate + "_" + endDate + "_trip FOREIGN KEY (trip_id)\n" + " REFERENCES gtfs.trips_" + startDate + "_" + endDate + " (trip_id) MATCH SIMPLE\n" + " ON UPDATE NO ACTION ON DELETE NO ACTION;\n" + " ALTER TABLE gtfs.stop_stop_matrix_" + startDate + "_" + endDate + "\n" + "ADD CONSTRAINT matrix_" + startDate + "_" + endDate + "_stop_id PRIMARY KEY (from_stop_id);\n"; try { PreparedStatement constraints = dbConnection.prepareStatement(constraintsQuery); constraints.execute(); } catch (PSQLException ex) { System.out.println(ex); System.out.println(ex.getServerErrorMessage().getMessage()); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.stuy.commands; import edu.wpi.first.wpilibj.command.CommandGroup; /** * * @author admin */ public class AutonSetting1 extends CommandGroup { /* For inches to fender */ private static final int DIST_FENDER_TO_KEY = 110; private static final double BUMPER_EDGE_TO_WHEEL_CENTER = 9.5; private static final int BOT_LENGTH_WITH_BUMPERS = 44; public static final double INCHES_TO_FENDER = DIST_FENDER_TO_KEY - (BOT_LENGTH_WITH_BUMPERS - BUMPER_EDGE_TO_WHEEL_CENTER); /* For inches to bridge from fender */ public static final double INCHES_TO_BRIDGE = 5.0; public AutonSetting1() { addSequential(new AutonDriveToFender(INCHES_TO_FENDER)); // TODO: Call ConveyAutomatic for a set time interval OR ConveySemiauto for two balls addSequential(new ShooterShoot(2.0)); // TODO: Get tusks running concurrently with backing up, have them retract after backuptobridge is done addParallel(new TusksExtend()); addSequential(new AutonBackUpToBridge(INCHES_TO_BRIDGE)); addSequential(new TusksRetract()); } }
package fr.jayasoft.ivy; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; import javax.swing.event.EventListenerList; import org.xml.sax.SAXException; import fr.jayasoft.ivy.IvyNode.EvictionData; import fr.jayasoft.ivy.conflict.LatestConflictManager; import fr.jayasoft.ivy.conflict.NoConflictManager; import fr.jayasoft.ivy.conflict.StrictConflictManager; import fr.jayasoft.ivy.event.IvyEvent; import fr.jayasoft.ivy.event.IvyListener; import fr.jayasoft.ivy.event.PrepareDownloadEvent; import fr.jayasoft.ivy.filter.Filter; import fr.jayasoft.ivy.filter.FilterHelper; import fr.jayasoft.ivy.latest.LatestLexicographicStrategy; import fr.jayasoft.ivy.latest.LatestRevisionStrategy; import fr.jayasoft.ivy.latest.LatestTimeStrategy; import fr.jayasoft.ivy.report.ArtifactDownloadReport; import fr.jayasoft.ivy.report.ConfigurationResolveReport; import fr.jayasoft.ivy.report.DownloadReport; import fr.jayasoft.ivy.report.DownloadStatus; import fr.jayasoft.ivy.report.LogReportOutputter; import fr.jayasoft.ivy.report.ReportOutputter; import fr.jayasoft.ivy.report.ResolveReport; import fr.jayasoft.ivy.report.XmlReportOutputter; import fr.jayasoft.ivy.repository.TransferEvent; import fr.jayasoft.ivy.repository.TransferListener; import fr.jayasoft.ivy.resolver.CacheResolver; import fr.jayasoft.ivy.resolver.ChainResolver; import fr.jayasoft.ivy.resolver.DualResolver; import fr.jayasoft.ivy.resolver.ModuleEntry; import fr.jayasoft.ivy.resolver.OrganisationEntry; import fr.jayasoft.ivy.resolver.RevisionEntry; import fr.jayasoft.ivy.url.URLHandlerRegistry; import fr.jayasoft.ivy.util.FileUtil; import fr.jayasoft.ivy.util.IvyPatternHelper; import fr.jayasoft.ivy.util.Message; import fr.jayasoft.ivy.xml.XmlIvyConfigurationParser; import fr.jayasoft.ivy.xml.XmlModuleDescriptorParser; import fr.jayasoft.ivy.xml.XmlModuleDescriptorUpdater; import fr.jayasoft.ivy.xml.XmlReportParser; /** * Ivy is a free java based dependency manager. * * This class is the main class of Ivy, which offers mainly dependency resolution. * * Here is one typical usage: * Ivy ivy = new Ivy(); * ivy.configure(new URL("ivyconf.xml")); * ivy.resolve(new URL("ivy.xml"), null, new String[] {"*"}, null, null, true); * * @author x.hanin * */ public class Ivy implements TransferListener { public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss"); private static final String DEFAULT_CACHE_ARTIFACT_PATTERN = "[organisation]/[module]/[type]s/[artifact]-[revision].[ext]"; private static final String DEFAULT_CACHE_IVY_PATTERN = "[organisation]/[module]/ivy-[revision].xml"; private static final String DEFAULT_CACHE_RESOLVED_IVY_PATTERN = "resolved-[organisation]-[module]-[revision].xml"; private static final String DEFAULT_CACHE_RESOLVED_IVY_PROPERTIES_PATTERN = "resolved-[organisation]-[module]-[revision].properties"; private Map _typeDefs = new HashMap(); private Map _resolversMap = new HashMap(); private DependencyResolver _defaultResolver; private DependencyResolver _dictatorResolver = null; private String _defaultResolverName; private File _defaultCache; private boolean _checkUpToDate = true; private Map _moduleConfigurations = new LinkedHashMap(); // Map (ModuleId -> String resolverName) private Map _conflictsManager = new HashMap(); // Map (String conflictManagerName -> ConflictManager) private Map _latestStrategies = new HashMap(); // Map (String latestStrategyName -> LatestStrategy) private Map _variables = new HashMap(); private ReportOutputter[] _reportOutputters = new ReportOutputter[] {new LogReportOutputter(), new XmlReportOutputter()}; private String _cacheIvyPattern = DEFAULT_CACHE_IVY_PATTERN; private String _cacheResolvedIvyPattern = DEFAULT_CACHE_RESOLVED_IVY_PATTERN; private String _cacheResolvedIvyPropertiesPattern = DEFAULT_CACHE_RESOLVED_IVY_PROPERTIES_PATTERN; private String _cacheArtifactPattern = DEFAULT_CACHE_ARTIFACT_PATTERN; private boolean _validate = true; private LatestStrategy _defaultLatestStrategy = null; private ConflictManager _defaultConflictManager = null; private List _listingIgnore = new ArrayList(); private boolean _repositoriesConfigured; private boolean _useRemoteConfig = false; private File _defaultUserDir; public Ivy() { setVariable("ivy.default.conf.dir", Ivy.class.getResource("conf").toExternalForm(), true); String ivyTypeDefs = System.getProperty("ivy.typedef.files"); if (ivyTypeDefs != null) { String[] files = ivyTypeDefs.split("\\,"); for (int i = 0; i < files.length; i++) { try { typeDefs(new FileInputStream(new File(files[i].trim()))); } catch (FileNotFoundException e) { Message.warn("typedefs file not found: "+files[i].trim()); } catch (IOException e) { Message.warn("problem with typedef file: "+files[i].trim()+": "+e.getMessage()); } } } else { try { typeDefs(Ivy.class.getResourceAsStream("typedef.properties")); } catch (IOException e) { Message.warn("impossible to load default type defs"); } } LatestLexicographicStrategy latestLexicographicStrategy = new LatestLexicographicStrategy(); LatestRevisionStrategy latestRevisionStrategy = new LatestRevisionStrategy(); LatestTimeStrategy latestTimeStrategy = new LatestTimeStrategy(); addLatestStrategy("latest-revision", latestRevisionStrategy); addLatestStrategy("latest-lexico", latestLexicographicStrategy); addLatestStrategy("latest-time", latestTimeStrategy); addConflictManager("latest-revision", new LatestConflictManager("latest-revision", latestRevisionStrategy)); addConflictManager("latest-time", new LatestConflictManager("latest-time", latestTimeStrategy)); addConflictManager("all", new NoConflictManager()); addConflictManager("strict", new StrictConflictManager()); _listingIgnore.add(".cvsignore"); _listingIgnore.add("CVS"); _listingIgnore.add(".svn"); addTransferListener(new TransferListener() { public void transferProgress(TransferEvent evt) { switch (evt.getEventType()) { case TransferEvent.TRANSFER_PROGRESS: Message.progress(); break; case TransferEvent.TRANSFER_COMPLETED: Message.endProgress(" ("+(evt.getTotalLength() / 1024)+"kB)"); break; default: break; } } }); } /** * Call this method to ask ivy to configure some variables using either a remote or a local properties file */ public void configureRepositories(boolean remote) { if (!_repositoriesConfigured) { Properties props = new Properties(); boolean configured = false; if (_useRemoteConfig && remote) { try { URL url = new URL("http: Message.verbose("configuring repositories with "+url); props.load(URLHandlerRegistry.getDefault().openStream(url)); configured = true; } catch (Exception ex) { Message.verbose("unable to use remote repository configuration: "+ex.getMessage()); props = new Properties(); } } if (!configured) { try { props.load(Ivy.class.getResourceAsStream("repository.properties")); } catch (IOException e) { Message.error("unable to use internal repository configuration: "+e.getMessage()); } } addAllVariables(props, false); _repositoriesConfigured = true; } } public void typeDefs(InputStream stream) throws IOException { try { Properties p = new Properties(); p.load(stream); typeDefs(p); } finally { stream.close(); } } public void typeDefs(Properties p) { for (Iterator iter = p.keySet().iterator(); iter.hasNext();) { String name = (String) iter.next(); try { typeDef(name, Class.forName(p.getProperty(name))); } catch (ClassNotFoundException e) { Message.warn("impossible to define resolver "+name+": class not found: "+p.getProperty(name)); } } } // CONFIGURATION public void configure(File configurationFile) throws ParseException, IOException { Message.info(":: configuring :: file = "+configurationFile); long start = System.currentTimeMillis(); setConfigurationVariables(configurationFile); try { new XmlIvyConfigurationParser(this).parse(configurationFile.toURL()); } catch (MalformedURLException e) { IllegalArgumentException iae = new IllegalArgumentException("given file cannot be transformed to url: "+configurationFile); iae.initCause(e); throw iae; } setVariable("ivy.default.ivy.user.dir", getDefaultIvyUserDir().getAbsolutePath(), false); Message.verbose("configuration done ("+(System.currentTimeMillis()-start)+"ms)"); dumpConfig(); } public void configure(URL configurationURL) throws ParseException, IOException { Message.info(":: configuring :: url = "+configurationURL); long start = System.currentTimeMillis(); setConfigurationVariables(configurationURL); new XmlIvyConfigurationParser(this).parse(configurationURL); setVariable("ivy.default.ivy.user.dir", getDefaultIvyUserDir().getAbsolutePath(), false); Message.verbose("configuration done ("+(System.currentTimeMillis()-start)+"ms)"); dumpConfig(); } public void configureDefault() throws ParseException, IOException { configure(getDefaultConfigurationURL()); } public void setConfigurationVariables(File configurationFile) { try { setVariable("ivy.conf.dir", new File(configurationFile.getAbsolutePath()).getParent()); setVariable("ivy.conf.file", configurationFile.getAbsolutePath()); setVariable("ivy.conf.url", configurationFile.toURL().toExternalForm()); } catch (MalformedURLException e) { IllegalArgumentException iae = new IllegalArgumentException("given file cannot be transformed to url: "+configurationFile); iae.initCause(e); throw iae; } } public void setConfigurationVariables(URL configurationURL) { String confURL = configurationURL.toExternalForm(); setVariable("ivy.conf.url", confURL); int slashIndex = confURL.lastIndexOf('/'); if (slashIndex != -1) { setVariable("ivy.conf.dir", confURL.substring(0, slashIndex)); } else { Message.warn("configuration url does not contain any slash (/): ivy.conf.dir variable not set"); } } private void dumpConfig() { Message.verbose("\tdefault cache: "+getDefaultCache()); Message.verbose("\tdefault resolver: "+getDefaultResolver()); Message.debug("\tdefault latest strategy: "+getDefaultLatestStrategy()); Message.debug("\tdefault conflict manager: "+getDefaultConflictManager()); Message.debug("\tvalidate: "+doValidate()); Message.debug("\tcheck up2date: "+isCheckUpToDate()); Message.debug("\tcache ivy pattern: "+getCacheIvyPattern()); Message.debug("\tcache artifact pattern: "+getCacheArtifactPattern()); Message.verbose("\t-- "+_resolversMap.size()+" resolvers:"); for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) { DependencyResolver resolver = (DependencyResolver)iter.next(); resolver.dumpConfig(); } if (!_moduleConfigurations.isEmpty()) { Message.debug("\tmodule configurations:"); for (Iterator iter = _moduleConfigurations.keySet().iterator(); iter.hasNext();) { ModuleId mid = (ModuleId)iter.next(); String res = (String)_moduleConfigurations.get(mid); Message.debug("\t\t"+mid+" -> "+res); } } } public void loadProperties(URL url) throws IOException { loadProperties(url, true); } public void loadProperties(URL url, boolean overwrite) throws IOException { Properties properties = new Properties(); properties.load(url.openStream()); addAllVariables(properties, overwrite); } public void loadProperties(File file) throws IOException { loadProperties(file, true); } public void loadProperties(File file, boolean overwrite) throws IOException { Properties properties = new Properties(); properties.load(new FileInputStream(file)); addAllVariables(properties, overwrite); } public void setVariable(String varName, String value) { setVariable(varName, value, true); } public void setVariable(String varName, String value, boolean overwrite) { if (overwrite || !_variables.containsKey(varName)) { Message.debug("setting '"+varName+"' to '"+value+"'"); _variables.put(varName, substitute(value)); } else { Message.debug("'"+varName+"' already set: discarding '"+value+"'"); } } public void addAllVariables(Map variables) { addAllVariables(variables, true); } public void addAllVariables(Map variables, boolean overwrite) { for (Iterator iter = variables.keySet().iterator(); iter.hasNext();) { String key = (String)iter.next(); String val = (String)variables.get(key); setVariable(key, val, overwrite); } } /** * Substitute variables in the given string by their value found in the current * set of variables * * @param str the string in which substitution should be made * @return the string where all current ivy variables have been substituted by their value */ public String substitute(String str) { return IvyPatternHelper.substituteVariables(str, getVariables()); } /** * Returns the variables loaded in configuration file. Those variables * may better be seen as ant properties * * @return */ public Map getVariables() { return _variables; } public void typeDef(String name, Class clazz) { _typeDefs.put(name, clazz); } public Map getTypeDefs() { return _typeDefs; } public Class getTypeDef(String name) { return (Class)_typeDefs.get(name); } // methods which match ivy conf method signature specs public void addConfigured(DependencyResolver resolver) { addResolver(resolver); } public void addResolver(DependencyResolver resolver) { if (resolver == null) { throw new NullPointerException("null resolver"); } if (resolver instanceof IvyAware) { ((IvyAware)resolver).setIvy(this); } _resolversMap.put(resolver.getName(), resolver); if (resolver instanceof ChainResolver) { List subresolvers = ((ChainResolver)resolver).getResolvers(); for (Iterator iter = subresolvers.iterator(); iter.hasNext();) { DependencyResolver dr = (DependencyResolver)iter.next(); addResolver(dr); } } else if (resolver instanceof DualResolver) { DependencyResolver ivyResolver = ((DualResolver)resolver).getIvyResolver(); if (ivyResolver != null) { addResolver(ivyResolver); } DependencyResolver artifactResolver = ((DualResolver)resolver).getArtifactResolver(); if (artifactResolver != null) { addResolver(artifactResolver); } } } public void setDefaultCache(File cacheDirectory) { _defaultCache = cacheDirectory; } public void setDefaultResolver(String resolverName) { checkResolverName(resolverName); _defaultResolverName = resolverName; } private void checkResolverName(String resolverName) { if (!_resolversMap.containsKey(resolverName)) { throw new IllegalArgumentException("no resolver found called "+resolverName+": check your configuration"); } } /** * regular expressions as explained in Pattern class may be used in ModuleId * organisation and name * * @param moduleId * @param resolverName */ public void addModuleConfiguration(ModuleId moduleId, String resolverName) { checkResolverName(resolverName); _moduleConfigurations.put(moduleId, resolverName); } public File getDefaultIvyUserDir() { if (_defaultUserDir==null) { _defaultUserDir = new File(System.getProperty("user.home"), ".ivy"); Message.verbose("no default ivy user dir defined: set to "+_defaultUserDir); } return _defaultUserDir; } public File getDefaultCache() { if (_defaultCache==null) { _defaultCache = new File(getDefaultIvyUserDir(), "cache"); Message.verbose("no default cache defined: set to "+_defaultCache); } return _defaultCache; } public DependencyResolver getResolver(ModuleId moduleId) { if (_dictatorResolver != null) { return _dictatorResolver; } String resolverName = getResolverName(moduleId); return getResolver(resolverName); } public DependencyResolver getResolver(String resolverName) { if (_dictatorResolver != null) { return _dictatorResolver; } DependencyResolver resolver = (DependencyResolver)_resolversMap.get(resolverName); if (resolver == null) { Message.error("unknown resolver "+resolverName); } return resolver; } public DependencyResolver getDefaultResolver() { if (_dictatorResolver != null) { return _dictatorResolver; } if (_defaultResolver == null) { _defaultResolver = (DependencyResolver)_resolversMap.get(_defaultResolverName); } return _defaultResolver; } public String getResolverName(ModuleId moduleId) { String name = (String)_moduleConfigurations.get(moduleId); if (name != null) { return name; } for (Iterator iter = _moduleConfigurations.keySet().iterator(); iter.hasNext();) { ModuleId mid = (ModuleId)iter.next(); if (Pattern.compile(mid.getOrganisation()).matcher(moduleId.getOrganisation()).matches() && Pattern.compile(mid.getName()).matcher(moduleId.getName()).matches()) { return (String)_moduleConfigurations.get(mid); } } return _defaultResolverName; } public void addConfigured(ConflictManager cm) { addConflictManager(cm.getName(), cm); } public ConflictManager getConflictManager(String name) { if ("default".equals(name)) { return getDefaultConflictManager(); } return (ConflictManager)_conflictsManager.get(name); } public void addConflictManager(String name, ConflictManager cm) { if (cm instanceof IvyAware) { ((IvyAware)cm).setIvy(this); } _conflictsManager.put(name, cm); } public void addConfigured(LatestStrategy latest) { addLatestStrategy(latest.getName(), latest); } public LatestStrategy getLatestStrategy(String name) { if ("default".equals(name)) { return getDefaultLatestStrategy(); } return (LatestStrategy)_latestStrategies.get(name); } public void addLatestStrategy(String name, LatestStrategy latest) { if (latest instanceof IvyAware) { ((IvyAware)latest).setIvy(this); } _latestStrategies.put(name, latest); } // CHECK /** * Checks the given ivy file using current configuration to see if all dependencies * are available, with good confs. If a resolver name is given, it also checks that the declared * publications are available in the corresponding resolver. * Note that the check is not performed recursively, i.e. if a dependency has itself dependencies * badly described or not available, this check will not discover it. */ public boolean check(URL ivyFile, String resolvername) { try { boolean result = true; // parse ivy file ModuleDescriptor md = XmlModuleDescriptorParser.parseDescriptor(this, ivyFile, doValidate()); // check publications if possible if (resolvername != null) { DependencyResolver resolver = getResolver(resolvername); String[] confs = md.getConfigurationsNames(); Set artifacts = new HashSet(); for (int i = 0; i < confs.length; i++) { artifacts.addAll(Arrays.asList(md.getArtifacts(confs[i]))); } for (Iterator iter = artifacts.iterator(); iter.hasNext();) { Artifact art = (Artifact)iter.next(); if (!resolver.exists(art)) { Message.info("declared publication not found: "+art); result = false; } } } // check dependencies DependencyDescriptor[] dds = md.getDependencies(); ResolveData data = new ResolveData(this, getDefaultCache(), new Date(), null, true); for (int i = 0; i < dds.length; i++) { // check master confs String[] masterConfs = dds[i].getModuleConfigurations(); for (int j = 0; j < masterConfs.length; j++) { if (!"*".equals(masterConfs[j].trim()) && md.getConfiguration(masterConfs[j]) == null) { Message.info("dependency required in non existing conf for "+ivyFile+" \n\tin "+dds[i].getDependencyRevisionId()+": "+masterConfs[j]); result = false; } } // resolve DependencyResolver resolver = getResolver(dds[i].getDependencyId()); ResolvedModuleRevision rmr = resolver.getDependency(dds[i], data); if (rmr == null) { Message.info("dependency not found in "+ivyFile+":\n\t"+dds[i]); result = false; } else { String[] depConfs = dds[i].getDependencyConfigurations(md.getConfigurationsNames()); for (int j = 0; j < depConfs.length; j++) { if (!Arrays.asList(rmr.getDescriptor().getConfigurationsNames()).contains(depConfs[j])) { Message.info("dependency configuration is missing for "+ivyFile+"\n\tin "+dds[i].getDependencyRevisionId()+": "+depConfs[j]); result = false; } Artifact[] arts = rmr.getDescriptor().getArtifacts(depConfs[j]); for (int k = 0; k < arts.length; k++) { if (!resolver.exists(arts[k])) { Message.info("dependency artifact is missing for "+ivyFile+"\n\t in "+dds[i].getDependencyRevisionId()+": "+arts[k]); result = false; } } } } } return result; } catch (ParseException e) { Message.info("parse problem on "+ivyFile+": "+e.getMessage()); return false; } catch (IOException e) { Message.info("io problem on "+ivyFile+": "+e.getMessage()); return false; } catch (Exception e) { Message.info("problem on "+ivyFile+": "+e.getMessage()); return false; } } // RESOLVE /** * * @param ivySource the url to the descriptor of the module for which dependencies should be resolved * @param revision the revision of the module for which dependencies should be resolved. * This revision is considered as the resolved revision of the module, unless it is null. * If it is null, then a default revision is given if necessary (no revision found in ivy file) * @param confs the configurations for which dependencies should be resolved * @param cache the directory where to place resolved dependencies * @param date the date for which the dependencies should be resolved. All obtained artifacts * should have a publication date which is before or equal to the given date * @throws ParseException * @throws IOException * @throws NullPointerException if any parameter is null except cache or date */ public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, Date date, boolean validate) throws ParseException, IOException { return resolve(ivySource, revision, confs, cache, date, validate, false); } public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, Date date, boolean validate, boolean useCacheOnly) throws ParseException, IOException { return resolve(ivySource, revision, confs, cache, date, validate, useCacheOnly, FilterHelper.NO_FILTER); } public ResolveReport resolve(URL ivySource, String revision, String[] confs, File cache, Date date, boolean validate, boolean useCacheOnly, Filter artifactFilter) throws ParseException, IOException { DependencyResolver oldDictator = getDictatorResolver(); if (useCacheOnly) { setDictatorResolver(new CacheResolver(this)); } try { ModuleDescriptor md = XmlModuleDescriptorParser.parseDescriptor(this, ivySource, validate); if (cache==null) { // ensure that a cache exists cache = getDefaultCache(); } if (revision == null && md.getResolvedModuleRevisionId().getRevision() == null) { revision = "working@"+getLocalHostName(); } if (revision != null) { md.setResolvedModuleRevisionId(new ModuleRevisionId(md.getModuleRevisionId().getModuleId(), revision)); } if (confs.length == 1 && confs[0].equals("*")) { confs = md.getConfigurationsNames(); } long start = System.currentTimeMillis(); Message.info(":: resolving dependencies :: "+md.getResolvedModuleRevisionId()); Message.info("\tconfs: "+Arrays.asList(confs)); Message.verbose("\tvalidate = "+validate); ResolveReport report = new ResolveReport(md); // resolve dependencies IvyNode[] dependencies = getDependencies(md, confs, cache, date, report, validate); Message.verbose(":: downloading artifacts ::"); // collect list of artifacts Collection artifacts = new ArrayList(); for (int i = 0; i < dependencies.length; i++) { //download artifacts required in all asked configurations if (!dependencies[i].isCompletelyEvicted() && !dependencies[i].hasProblem()) { artifacts.addAll(Arrays.asList(dependencies[i].getSelectedArtifacts(artifactFilter))); } } fireIvyEvent(new PrepareDownloadEvent((Artifact[])artifacts.toArray(new Artifact[artifacts.size()]))); Map resolvedRevisions = new HashMap(); // Map (ModuleId dependency -> String revision) Map dependenciesStatus = new HashMap(); // Map (ModuleId dependency -> String status) for (int i = 0; i < dependencies.length; i++) { //download artifacts required in all asked configurations if (!dependencies[i].isCompletelyEvicted() && !dependencies[i].hasProblem()) { DependencyResolver resolver = dependencies[i].getModuleRevision().getResolver(); Artifact[] selectedArtifacts = dependencies[i].getSelectedArtifacts(artifactFilter); DownloadReport dReport = resolver.download(selectedArtifacts, this, cache); ArtifactDownloadReport[] adrs = dReport.getArtifactsReports(); for (int j = 0; j < adrs.length; j++) { if (adrs[j].getDownloadStatus() == DownloadStatus.FAILED) { Message.warn("\t[NOT FOUND ] "+adrs[j].getArtifact()); resolver.reportFailure(adrs[j].getArtifact()); } } // update concerned reports String[] dconfs = dependencies[i].getRootModuleConfigurations(); for (int j = 0; j < dconfs.length; j++) { // the report itself is responsible to take into account only // artifacts required in its corresponding configuration // (as described by the Dependency object) if (dependencies[i].isEvicted(dconfs[j])) { report.getConfigurationReport(dconfs[j]).addDependency(dependencies[i]); } else { report.getConfigurationReport(dconfs[j]).addDependency(dependencies[i], dReport); } } // update resolved dependencies map for resolved ivy file producing resolvedRevisions.put(dependencies[i].getModuleId(), dependencies[i].getResolvedId().getRevision()); dependenciesStatus.put(dependencies[i].getModuleId(), dependencies[i].getDescriptor().getStatus()); } else if (dependencies[i].isCompletelyEvicted()) { // dependencies has been evicted: it has not been added to the report yet String[] dconfs = dependencies[i].getRootModuleConfigurations(); for (int j = 0; j < dconfs.length; j++) { report.getConfigurationReport(dconfs[j]).addDependency(dependencies[i]); } } } // produce resolved ivy file and ivy properties in cache File ivyFileInCache = getResolvedIvyFileInCache(cache, md.getResolvedModuleRevisionId()); try { XmlModuleDescriptorUpdater.update( ivySource, ivyFileInCache, Collections.EMPTY_MAP, null, md.getResolvedModuleRevisionId().getRevision(), null); } catch (SAXException e) { ParseException ex = new ParseException(e.getMessage(), 0); ex.initCause(e); throw ex; } File ivyPropertiesInCache = getResolvedIvyPropertiesInCache(cache, md.getResolvedModuleRevisionId()); Properties props = new Properties(); for (Iterator iter = resolvedRevisions.keySet().iterator(); iter.hasNext();) { ModuleId mid = (ModuleId)iter.next(); String rev = (String)resolvedRevisions.get(mid); String status = (String)dependenciesStatus.get(mid); props.put(mid.encodeToString(), rev+" "+status); } props.store(new FileOutputStream(ivyPropertiesInCache), md.getResolvedModuleRevisionId()+ " resolved revisions"); Message.verbose("\tresolved ivy file produced in "+ivyFileInCache); Message.info(":: resolution report ::"); // output report report.output(getReportOutputters(), cache); Message.verbose("\tresolve done ("+(System.currentTimeMillis()-start)+"ms)"); Message.sumupProblems(); return report; } finally { setDictatorResolver(oldDictator); } } /** * Download an artifact to the cache. * Not used internally, useful especially for IDE plugins * needing to download artifact one by one (for source or javadoc artifact, * for instance). * * Downloaded artifact file can be accessed using getArchiveFileInCache method. * * It is possible to track the progression of the download using classical ivy * progress monitoring feature (see addTransferListener). * * @param artifact the artifact to download * @param cache the cache to use. If null, will use default cache * @return a report concerning the download */ public ArtifactDownloadReport download(Artifact artifact, File cache) { if (cache == null) { cache = getDefaultCache(); } DependencyResolver resolver = getResolver(artifact.getModuleRevisionId().getModuleId()); DownloadReport r = resolver.download(new Artifact[] {artifact}, this, cache); return r.getArtifactReport(artifact); } public ReportOutputter[] getReportOutputters() { return _reportOutputters; } /** * Resolve the dependencies of a module without downloading corresponding artifacts. * The module to resolve is given by its ivy file URL. This method requires * appropriate configuration of the ivy instance, especially resolvers. * * @param ivySource url of the ivy file to use for dependency resolving * @param confs an array of configuration names to resolve - must not be null nor empty * @param cache the cache to use - default cache is used if null * @param date the date to which resolution must be done - may be null * @return an array of the resolved dependencies * @throws ParseException if a parsing problem occured in the ivy file * @throws IOException if an IO problem was raised during ivy file parsing */ public IvyNode[] getDependencies(URL ivySource, String[] confs, File cache, Date date, boolean validate) throws ParseException, IOException { return getDependencies(XmlModuleDescriptorParser.parseDescriptor(this, ivySource, validate), confs, cache, date, null, validate); } /** * Resolve the dependencies of a module without downloading corresponding artifacts. * The module to resolve is given by its module descriptor.This method requires * appropriate configuration of the ivy instance, especially resolvers. * * @param md the descriptor of the module for which we want to get dependencies - must not be null * @param confs an array of configuration names to resolve - must not be null nor empty * @param cache the cache to use - default cache is used if null * @param date the date to which resolution must be done - may be null * @param report a resolve report to fill during resolution - may be null * @return an array of the resolved Dependencies */ public IvyNode[] getDependencies(ModuleDescriptor md, String[] confs, File cache, Date date, ResolveReport report, boolean validate) { if (md == null) { throw new NullPointerException("module descriptor must not be null"); } if (cache==null) { // ensure that a cache exists cache = getDefaultCache(); } if (confs.length == 1 && confs[0].equals("*")) { confs = md.getConfigurationsNames(); } Map dependenciesMap = new HashMap(); Date reportDate = new Date(); for (int i = 0; i < confs.length; i++) { Configuration configuration = md.getConfiguration(confs[i]); if (configuration == null) { Message.error("asked configuration not found in "+md.getModuleRevisionId()+": "+confs[i]); } else { ConfigurationResolveReport confReport = null; if (report != null) { confReport = report.getConfigurationReport(confs[i]); if (confReport == null) { confReport = new ConfigurationResolveReport(this, md, confs[i], reportDate, cache); report.addReport(confs[i], confReport); } } ResolveData data = new ResolveData(this, cache, date, confReport, validate, dependenciesMap); IvyNode node = new IvyNode(data, md, confs[i], true); node.setRootModuleConf(confs[i]); fetchDependencies(node, confs[i]); } } // prune and reverse sort fectched dependencies Collection dependencies = new HashSet(dependenciesMap.size()); // use a Set to avoids duplicates for (Iterator iter = dependenciesMap.values().iterator(); iter.hasNext();) { IvyNode dep = (IvyNode) iter.next(); if (dep != null) { dependencies.add(dep); } } List sortedDependencies = sortNodes(dependencies); Collections.reverse(sortedDependencies); // handle transitive eviction now: // if a module has been evicted then all its dependencies required // only by it should be evicted too. Since nodes are now sorted from the more dependent to // the less one, we can traverse the list and check only the direct parent and not all // the ancestors for (ListIterator iter = sortedDependencies.listIterator(); iter.hasNext();) { IvyNode node = (IvyNode)iter.next(); if (!node.isCompletelyEvicted()) { for (int i = 0; i < confs.length; i++) { IvyNode.Caller[] callers = node.getCallers(confs[i]); boolean allEvicted = callers.length > 0; for (int j = 0; j < callers.length; j++) { if (callers[j].getModuleRevisionId().equals(md.getModuleRevisionId())) { // the caller is the root module itself, it can't be evicted allEvicted = false; break; } else { IvyNode callerNode = (IvyNode)dependenciesMap.get(callers[j].getModuleRevisionId()); if (callerNode != null && !callerNode.isEvicted(confs[i])) { allEvicted = false; break; } } } if (allEvicted) { Message.verbose("all callers are evicted for "+node+": evicting too"); node.markEvicted(confs[i], null, null, null); } } } } return (IvyNode[])sortedDependencies.toArray(new IvyNode[sortedDependencies.size()]); } private void fetchDependencies(IvyNode node, String conf) { resolveConflict(node, node.getParent()); if (node.loadData(conf)) { node = node.getRealNode(); // if data loading discarded the node, get the real one resolveConflict(node, node.getParent()); if (!node.isEvicted(node.getRootModuleConf())) { if ("*".equals(conf)) { String[] confs = node.getDescriptor().getConfigurationsNames(); for (int i = 0; i < confs.length; i++) { doFetchDependencies(node, confs[i]); } } else { doFetchDependencies(node, conf); } } } if (node.isEvicted(node.getRootModuleConf())) { // update selected nodes with confs asked in evicted one IvyNode.EvictionData ed = node.getEvictedData(node.getRootModuleConf()); for (Iterator iter = ed.getSelected().iterator(); iter.hasNext();) { IvyNode selected = (IvyNode)iter.next(); fetchDependencies(selected, conf); } } } private void doFetchDependencies(IvyNode node, String conf) { Configuration c = node.getConfiguration(conf); // we handle the case where the asked configuration extends others: // we have to first fetch the extended configurations String[] extendedConfs = c.getExtends(); if (extendedConfs.length > 0) { node.updateConfsToFetch(Arrays.asList(extendedConfs)); } for (int i = 0; i < extendedConfs.length; i++) { fetchDependencies(node, extendedConfs[i]); } if (node.getDependencyDescriptor() == null || node.getDependencyDescriptor().isTransitive()) { Collection dependencies = node.getDependencies(conf, true); for (Iterator iter = dependencies.iterator(); iter.hasNext();) { IvyNode dep = (IvyNode)iter.next(); if (dep.isCircular()) { Message.warn("circular dependency found ! "+node.getId()+" depends on "+dep.getId()+" which is already on the same branch of dependency"); continue; } String[] confs = dep.getRequiredConfigurations(node, conf); for (int i = 0; i < confs.length; i++) { fetchDependencies(dep, confs[i]); } // if there are still confs to fetch (usually because they have // been updated when evicting another module), we fetch them now confs = dep.getConfsToFetch(); for (int i = 0; i < confs.length; i++) { fetchDependencies(dep, confs[i]); } } } } private void resolveConflict(IvyNode node, IvyNode parent) { resolveConflict(node, parent, Collections.EMPTY_SET); } private void resolveConflict(IvyNode node, IvyNode parent, Collection toevict) { if (parent == null || node == parent) { return; } if (parent.getResolvedRevisions(node.getModuleId(), node.getRootModuleConf()).contains(node.getResolvedId())) { // resolve conflict has already be done with node with the same id // => job already done, we just have to check if the node wasn't previously evicted in root ancestor EvictionData evictionData = node.getEvictionDataInRoot(node.getRootModuleConf(), parent); if (evictionData != null) { // node has been previously evicted in an ancestor: we mark it as evicted and ensure selected are selected if (evictionData.getSelected() != null) { for (Iterator iter = evictionData.getSelected().iterator(); iter.hasNext();) { IvyNode selected = (IvyNode)iter.next(); if (selected.isEvicted(node.getRootModuleConf())) { selected.markSelected(node.getRootModuleConf()); Message.debug("selecting "+selected+" in "+parent+" due to eviction of "+node); } } } node.markEvicted(evictionData); Message.debug("evicting "+node+" by "+evictionData); } return; } Collection conflicts = new HashSet(); Collection resolvedNodes = new HashSet(parent.getResolvedNodes(node.getModuleId(), node.getRootModuleConf())); if (resolvedNodes.removeAll(toevict)) { // recompute resolved from all sub nodes Collection deps = parent.getDependencies(parent.getRequiredConfigurations()); for (Iterator iter = deps.iterator(); iter.hasNext();) { IvyNode dep = (IvyNode)iter.next(); conflicts.addAll(dep.getResolvedNodes(node.getModuleId(), node.getRootModuleConf())); } } else { conflicts.add(node); conflicts.addAll(resolvedNodes); } Collection resolved = parent.getConflictManager(node.getModuleId()).resolveConflicts(parent, conflicts); if (resolved.contains(node)) { // node has been selected for the current parent // we update its eviction... but it can still be evicted by parent ! node.markSelected(node.getRootModuleConf()); Message.debug("selecting "+node+" in "+parent); // handle previously selected nodes that are now evicted by this new node toevict = resolvedNodes; toevict.removeAll(resolved); for (Iterator iter = toevict.iterator(); iter.hasNext();) { IvyNode te = (IvyNode)iter.next(); te.markEvicted(node.getRootModuleConf(), parent, parent.getConflictManager(node.getModuleId()), resolved); Message.debug("evicting "+te+" by "+te.getEvictedData(node.getRootModuleConf())); } // it's very important to update resolved BEFORE recompute parent call // to allow it to recompute its resolved collection with correct data // if necessary parent.setResolvedNodes(node.getModuleId(), node.getRootModuleConf(), resolved); resolveConflict(node, parent.getParent(), toevict); } else { // node has been evicted for the current parent // first we mark the selected nodes as selected if it isn't already the case for (Iterator iter = resolved.iterator(); iter.hasNext();) { IvyNode selected = (IvyNode)iter.next(); if (selected.isEvicted(node.getRootModuleConf())) { selected.markSelected(node.getRootModuleConf()); Message.debug("selecting "+selected+" in "+parent); } } // it's time to update parent resolved with found resolved... // if they have not been recomputed, it does not change anything parent.setResolvedNodes(node.getModuleId(), node.getRootModuleConf(), resolved); node.markEvicted(node.getRootModuleConf(), parent, parent.getConflictManager(node.getModuleId()), resolved); Message.debug("evicting "+node+" by "+node.getEvictedData(node.getRootModuleConf())); } } public ResolvedModuleRevision findModuleInCache(ModuleRevisionId mrid, File cache, boolean validate) { // first, check if it is in cache if (mrid.isExactRevision()) { File ivyFile = getIvyFileInCache(cache, mrid); if (ivyFile.exists()) { // found in cache ! try { ModuleDescriptor depMD = XmlModuleDescriptorParser.parseDescriptor(this, ivyFile.toURL(), validate); DependencyResolver resolver = (DependencyResolver)_resolversMap.get(depMD.getResolverName()); if (resolver == null) { Message.debug("\tresolver not found: "+depMD.getResolverName()+" => trying to use default one for "+mrid); resolver = getDefaultResolver(); } if (resolver != null) { Message.debug("\tfound ivy file in cache for "+mrid+": "+ivyFile); return new DefaultModuleRevision(resolver, depMD, false, false); } else { Message.debug("\tresolver not found: "+depMD.getResolverName()+" => cannot use cached ivy file for "+mrid); } } catch (Exception e) { // will try with resolver Message.debug("\tproblem while parsing cached ivy file for: "+mrid+": "+e.getMessage()); } } else { Message.debug("\tno ivy file in cache for "+mrid+": tried "+ivyFile); } } return null; } // RETRIEVE public void retrieve(ModuleId moduleId, String[] confs, final File cache, String destFilePattern) { Message.info(":: retrieving :: "+moduleId); Message.info("\tconfs: "+Arrays.asList(confs)); long start = System.currentTimeMillis(); destFilePattern = IvyPatternHelper.substituteVariables(destFilePattern, getVariables()); try { // find what we must retrieve where final Map artifactsToCopy = new HashMap(); // Artifact source -> Set (String copyDestAbsolutePath) final Map conflictsMap = new HashMap(); // String copyDestAbsolutePath -> Set (Artifact source) final Map conflictsConfMap = new HashMap(); // String copyDestAbsolutePath -> Set (String conf) XmlReportParser parser = new XmlReportParser(); for (int i = 0; i < confs.length; i++) { final String conf = confs[i]; Artifact[] artifacts = parser.getArtifacts(moduleId, conf, cache); for (int j = 0; j < artifacts.length; j++) { Artifact artifact = artifacts[j]; String destFileName = IvyPatternHelper.substitute(destFilePattern, artifact.getModuleRevisionId().getOrganisation(), artifact.getModuleRevisionId().getName(), artifact.getModuleRevisionId().getRevision(), artifact.getName(), artifact.getType(), artifact.getExt(), conf); Set dest = (Set)artifactsToCopy.get(artifact); if (dest == null) { dest = new HashSet(); artifactsToCopy.put(artifact, dest); } String copyDest = new File(destFileName).getAbsolutePath(); dest.add(copyDest); Set conflicts = (Set)conflictsMap.get(copyDest); Set conflictsConf = (Set)conflictsConfMap.get(copyDest); if (conflicts == null) { conflicts = new HashSet(); conflictsMap.put(copyDest, conflicts); } if (conflictsConf == null) { conflictsConf = new HashSet(); conflictsConfMap.put(copyDest, conflictsConf); } conflicts.add(artifact); conflictsConf.add(conf); } } // resolve conflicts if any for (Iterator iter = conflictsMap.keySet().iterator(); iter.hasNext();) { String copyDest = (String)iter.next(); Set artifacts = (Set)conflictsMap.get(copyDest); Set conflictsConfs = (Set)conflictsConfMap.get(copyDest); if (artifacts.size() > 1) { List artifactsList = new ArrayList(artifacts); // conflicts battle is resolved by a sort using a conflict resolving policy comparator // which consider as greater a winning artifact Collections.sort(artifactsList, getConflictResolvingPolicy()); // after the sort, the winning artifact is the greatest one, i.e. the last one Message.info("\tconflict on "+copyDest+" in "+conflictsConfs+": "+((Artifact)artifactsList.get(artifactsList.size() -1)).getModuleRevisionId().getRevision()+" won"); // we now iterate over the list beginning with the artifact preceding the winner, // and going backward to the least artifact for (int i=artifactsList.size() - 2; i >=0; i Artifact looser = (Artifact)artifactsList.get(i); Message.verbose("\t\tremoving conflict looser artifact: "+looser); // for each loser, we remove the pair (loser - copyDest) in the artifactsToCopy map Set dest = (Set)artifactsToCopy.get(looser); dest.remove(copyDest); if (dest.isEmpty()) { artifactsToCopy.remove(looser); } } } } // do retrieve int targetsCopied = 0; int targetsUpToDate = 0; for (Iterator iter = artifactsToCopy.keySet().iterator(); iter.hasNext();) { Artifact artifact = (Artifact)iter.next(); File archive = getArchiveFileInCache(cache, artifact); Set dest = (Set)artifactsToCopy.get(artifact); Message.verbose("\tretrieving "+archive); for (Iterator it2 = dest.iterator(); it2.hasNext();) { File destFile = new File((String)it2.next()); if (!_checkUpToDate || !upToDate(archive, destFile)) { Message.verbose("\t\tto "+destFile); FileUtil.copy(archive, destFile, null); targetsCopied++; } else { Message.verbose("\t\tto "+destFile+" [NOT REQUIRED]"); targetsUpToDate++; } } } Message.info("\t"+targetsCopied+" artifacts copied, "+targetsUpToDate+" already retrieved"); Message.verbose("\tretrieve done ("+(System.currentTimeMillis()-start)+"ms)"); } catch (Exception ex) { IllegalStateException ise = new IllegalStateException("problem during retrieve of "+moduleId); ise.initCause(ex); throw ise; } } private boolean upToDate(File source, File target) { if (!target.exists()) { return false; } return source.lastModified() == target.lastModified(); } /** * The returned comparator should consider greater the artifact which * gains the conflict battle. * This is used only during retrieve... prefer resolve conflict manager * to resolve conflicts. * @return */ private Comparator getConflictResolvingPolicy() { return new Comparator() { // younger conflict resolving policy public int compare(Object o1, Object o2) { Artifact a1 = (Artifact)o1; Artifact a2 = (Artifact)o2; if (a1.getPublicationDate().after(a2.getPublicationDate())) { // a1 is after a2 <=> a1 is younger than a2 <=> a1 wins the conflict battle return +1; } else if (a1.getPublicationDate().before(a2.getPublicationDate())) { // a1 is before a2 <=> a2 is younger than a1 <=> a2 wins the conflict battle return -1; } else { return 0; } } }; } // PUBLISH public void deliver(ModuleRevisionId mrid, String revision, File cache, String destIvyPattern, String status, Date pubdate, PublishingDependencyRevisionResolver pdrResolver, boolean validate ) throws IOException, ParseException { deliver(mrid, revision, cache, destIvyPattern, status, pubdate, pdrResolver, validate, true); } public void deliver(ModuleRevisionId mrid, String revision, File cache, String destIvyPattern, String status, Date pubdate, PublishingDependencyRevisionResolver pdrResolver, boolean validate, boolean resolveDynamicRevisions) throws IOException, ParseException { Message.info(":: delivering :: "+mrid+" :: "+revision+" :: "+status+" :: "+pubdate); Message.verbose("\tvalidate = "+validate); long start = System.currentTimeMillis(); destIvyPattern = substitute(destIvyPattern); // 1) find the resolved module descriptor in cache File ivyFile = getResolvedIvyFileInCache(cache, mrid); if (!ivyFile.exists()) { throw new IllegalStateException("ivy file not found in cache for "+mrid+": please resolve dependencies before publishing ("+ivyFile+")"); } ModuleDescriptor md = null; URL ivyFileURL = null; try { ivyFileURL = ivyFile.toURL(); md = XmlModuleDescriptorParser.parseDescriptor(this, ivyFileURL, validate); md.setResolvedModuleRevisionId(new ModuleRevisionId(mrid.getModuleId(), revision)); md.setResolvedPublicationDate(pubdate); } catch (MalformedURLException e) { throw new RuntimeException("malformed url obtained for file "+ivyFile); } catch (ParseException e) { throw new IllegalStateException("bad ivy file in cache for "+mrid+": please clean and resolve again"); } // 2) parse resolvedRevisions From properties file Map resolvedRevisions = new HashMap(); // Map (ModuleId -> String revision) Map dependenciesStatus = new HashMap(); // Map (ModuleId -> String status) File ivyProperties = getResolvedIvyPropertiesInCache(cache, mrid); if (!ivyProperties.exists()) { throw new IllegalStateException("ivy properties not found in cache for "+mrid+": please resolve dependencies before publishing ("+ivyFile+")"); } Properties props = new Properties(); props.load(new FileInputStream(ivyProperties)); for (Iterator iter = props.keySet().iterator(); iter.hasNext();) { String mid = (String)iter.next(); String[] parts = props.getProperty(mid).split(" "); if (resolveDynamicRevisions) { resolvedRevisions.put(ModuleId.decode(mid), parts[0]); } String depStatus = props.getProperty(mid); dependenciesStatus.put(ModuleId.decode(mid), parts[1]); } // 3) use pdrResolver to resolve dependencies info Map resolvedDependencies = new HashMap(); // Map (ModuleId -> String revision) DependencyDescriptor[] dependencies = md.getDependencies(); for (int i = 0; i < dependencies.length; i++) { String rev = (String)resolvedRevisions.get(dependencies[i].getDependencyId()); if (rev == null) { rev = dependencies[i].getDependencyRevisionId().getRevision(); } String depStatus = (String)dependenciesStatus.get(dependencies[i].getDependencyId()); resolvedDependencies.put(dependencies[i].getDependencyId(), pdrResolver.resolve(md, status, new ModuleRevisionId(dependencies[i].getDependencyId(), rev), depStatus)); } // 4) copy the source resolved ivy to the destination specified, // updating status, revision and dependency revisions obtained by // PublishingDependencyRevisionResolver String publishedIvy = IvyPatternHelper.substitute(destIvyPattern, md.getResolvedModuleRevisionId()); Message.info("\tdelivering ivy file to "+publishedIvy); try { XmlModuleDescriptorUpdater.update(this, ivyFileURL, new File(publishedIvy), resolvedDependencies, status, revision, pubdate, null, true); } catch (SAXException ex) { throw new IllegalStateException("bad ivy file in cache for "+mrid+": please clean and resolve again"); } Message.verbose("\tdeliver done ("+(System.currentTimeMillis()-start)+"ms)"); } /** * * @param pubrevision * @param resolverName the name of a resolver to use for publication * @param srcArtifactPattern a pattern to find artifacts to publish with the given resolver * @param srcIvyPattern a pattern to find ivy file to publish, null if ivy file should not be published * @return a collection of missing artifacts (those that are not published) * @throws ParseException */ public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, String srcArtifactPattern, String resolverName, String srcIvyPattern, boolean validate) throws IOException { return publish(mrid, pubrevision, cache, srcArtifactPattern, resolverName, srcIvyPattern, validate, false); } /** * * @param pubrevision * @param resolverName the name of a resolver to use for publication * @param srcArtifactPattern a pattern to find artifacts to publish with the given resolver * @param srcIvyPattern a pattern to find ivy file to publish, null if ivy file should not be published * @return a collection of missing artifacts (those that are not published) * @throws ParseException */ public Collection publish(ModuleRevisionId mrid, String pubrevision, File cache, String srcArtifactPattern, String resolverName, String srcIvyPattern, boolean validate, boolean overwrite) throws IOException { Message.info(":: publishing :: "+mrid); Message.verbose("\tvalidate = "+validate); long start = System.currentTimeMillis(); srcArtifactPattern = substitute(srcArtifactPattern); srcIvyPattern = substitute(srcIvyPattern); // 1) find the resolved module descriptor in cache File ivyFile = getResolvedIvyFileInCache(cache, mrid); if (!ivyFile.exists()) { throw new IllegalStateException("ivy file not found in cache for "+mrid+": please resolve dependencies before publishing ("+ivyFile+")"); } DependencyResolver resolver = getResolver(resolverName); if (resolver == null) { throw new IllegalArgumentException("unknown resolver "+resolverName); } ModuleDescriptor md = null; URL ivyFileURL = null; try { ivyFileURL = ivyFile.toURL(); md = XmlModuleDescriptorParser.parseDescriptor(this, ivyFileURL, false); md.setResolvedModuleRevisionId(new ModuleRevisionId(mrid.getModuleId(), pubrevision)); } catch (MalformedURLException e) { throw new RuntimeException("malformed url obtained for file "+ivyFile); } catch (ParseException e) { throw new IllegalStateException("bad ivy file in cache for "+mrid+": please clean cache and resolve again"); } // collect all declared artifacts of this module Collection missing = new ArrayList(); Set artifactsSet = new HashSet(); String[] confs = md.getConfigurationsNames(); for (int i = 0; i < confs.length; i++) { Artifact[] artifacts = md.getArtifacts(confs[i]); for (int j = 0; j < artifacts.length; j++) { artifactsSet.add(artifacts[j]); } } // for each declared published artifact in this descriptor, do: for (Iterator iter = artifactsSet.iterator(); iter.hasNext();) { Artifact artifact = (Artifact) iter.next(); // 1) copy the artifact using src pattern and resolver if (!publish(artifact, srcArtifactPattern, resolver, overwrite)) { missing.add(artifact); } } if (srcIvyPattern != null) { Artifact artifact = new MDArtifact(md, "ivy", "ivy", "xml"); if (!publish(artifact, srcIvyPattern, resolver, overwrite)) { missing.add(artifact); } } Message.verbose("\tpublish done ("+(System.currentTimeMillis()-start)+"ms)"); return missing; } private boolean publish(Artifact artifact, String srcArtifactPattern, DependencyResolver resolver, boolean overwrite) throws IOException { File src = new File(IvyPatternHelper.substitute(srcArtifactPattern, artifact)); if (src.exists()) { resolver.publish(artifact, src, overwrite); return true; } else { Message.info("missing artifact "+artifact+": "+src+" file does not exist"); return false; } } // SORT public static List sortNodes(Collection nodes) { return ModuleDescriptorSorter.sortNodes(nodes); } /** * Sorts the given ModuleDescriptors from the less dependent to the more dependent. * This sort ensures that a ModuleDescriptor is always found in the list before all * ModuleDescriptors depending directly on it. * @param moduleDescriptors a Collection of ModuleDescriptor to sort * @return a List of sorted ModuleDescriptors */ public static List sortModuleDescriptors(Collection moduleDescriptors) { return ModuleDescriptorSorter.sortModuleDescriptors(moduleDescriptors); } // CACHE public File getResolvedIvyFileInCache(File cache, ModuleRevisionId mrid) { return new File(cache, IvyPatternHelper.substitute(_cacheResolvedIvyPattern, mrid.getOrganisation(), mrid.getName(), mrid.getRevision(), "ivy", "ivy", "xml")); } public File getResolvedIvyPropertiesInCache(File cache, ModuleRevisionId mrid) { return new File(cache, IvyPatternHelper.substitute(_cacheResolvedIvyPropertiesPattern, mrid.getOrganisation(), mrid.getName(), mrid.getRevision(), "ivy", "ivy", "xml")); } public File getIvyFileInCache(File cache, ModuleRevisionId mrid) { return new File(cache, IvyPatternHelper.substitute(_cacheIvyPattern, mrid.getOrganisation(), mrid.getName(), mrid.getRevision(), "ivy", "ivy", "xml")); } public File getArchiveFileInCache(File cache, Artifact artifact) { return new File(cache, getArchivePathInCache(artifact)); } public File getArchiveFileInCache(File cache, String organisation, String module, String revision, String artifact, String type, String ext) { return new File(cache, getArchivePathInCache(organisation, module, revision, artifact, type, ext)); } public String getArchivePathInCache(Artifact artifact) { return getArchivePathInCache( artifact.getModuleRevisionId().getOrganisation(), artifact.getModuleRevisionId().getName(), artifact.getModuleRevisionId().getRevision(), artifact.getName(), artifact.getType(), artifact.getExt()); } public String getArchivePathInCache(String organisation, String module, String revision, String artifact, String type, String ext) { return IvyPatternHelper.substitute(_cacheArtifactPattern, organisation, module, revision, artifact, type, ext); } public static String getLocalHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "localhost"; } } public OrganisationEntry[] listOrganisationEntries() { List entries = new ArrayList(); for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) { DependencyResolver resolver = (DependencyResolver)iter.next(); entries.addAll(Arrays.asList(resolver.listOrganisations())); } return (OrganisationEntry[])entries.toArray(new OrganisationEntry[entries.size()]); } public String[] listOrganisations() { Collection orgs = new HashSet(); for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) { DependencyResolver resolver = (DependencyResolver)iter.next(); OrganisationEntry[] entries = resolver.listOrganisations(); if (entries != null) { for (int i = 0; i < entries.length; i++) { if (entries[i] != null) { orgs.add(entries[i].getOrganisation()); } } } } return (String[])orgs.toArray(new String[orgs.size()]); } public ModuleEntry[] listModuleEntries(OrganisationEntry org) { List entries = new ArrayList(); for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) { DependencyResolver resolver = (DependencyResolver)iter.next(); entries.addAll(Arrays.asList(resolver.listModules(org))); } return (ModuleEntry[])entries.toArray(new ModuleEntry[entries.size()]); } public String[] listModules(String org) { List mods = new ArrayList(); for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) { DependencyResolver resolver = (DependencyResolver)iter.next(); ModuleEntry[] entries = resolver.listModules(new OrganisationEntry(resolver, org)); if (entries != null) { for (int i = 0; i < entries.length; i++) { if (entries[i] != null) { mods.add(entries[i].getModule()); } } } } return (String[])mods.toArray(new String[mods.size()]); } public RevisionEntry[] listRevisionEntries(ModuleEntry module) { List entries = new ArrayList(); for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) { DependencyResolver resolver = (DependencyResolver)iter.next(); entries.addAll(Arrays.asList(resolver.listRevisions(module))); } return (RevisionEntry[])entries.toArray(new RevisionEntry[entries.size()]); } public String[] listRevisions(String org, String module) { List revs = new ArrayList(); for (Iterator iter = _resolversMap.values().iterator(); iter.hasNext();) { DependencyResolver resolver = (DependencyResolver)iter.next(); RevisionEntry[] entries = resolver.listRevisions(new ModuleEntry(new OrganisationEntry(resolver, org), module)); if (entries != null) { for (int i = 0; i < entries.length; i++) { if (entries[i] != null) { revs.add(entries[i].getRevision()); } } } } return (String[])revs.toArray(new String[revs.size()]); } /** * Returns true if the name should be ignored in listing * @param name * @return */ public boolean listingIgnore(String name) { return _listingIgnore.contains(name); } /** * Filters the names list by removing all names that should be ignored * as defined by the listing ignore list * @param names */ public void filterIgnore(Collection names) { names.removeAll(_listingIgnore); } public boolean isCheckUpToDate() { return _checkUpToDate; } public void setCheckUpToDate(boolean checkUpToDate) { _checkUpToDate = checkUpToDate; } public String getCacheArtifactPattern() { return _cacheArtifactPattern; } public void setCacheArtifactPattern(String cacheArtifactPattern) { _cacheArtifactPattern = cacheArtifactPattern; } public String getCacheIvyPattern() { return _cacheIvyPattern; } public void setCacheIvyPattern(String cacheIvyPattern) { _cacheIvyPattern = cacheIvyPattern; } public boolean doValidate() { return _validate; } public void setValidate(boolean validate) { _validate = validate; } public String getVariable(String name) { String val = (String)_variables.get(name); return val==null?val:substitute(val); } public ConflictManager getDefaultConflictManager() { if (_defaultConflictManager == null) { _defaultConflictManager = new LatestConflictManager(getDefaultLatestStrategy()); } return _defaultConflictManager; } public void setDefaultConflictManager(ConflictManager defaultConflictManager) { _defaultConflictManager = defaultConflictManager; } public LatestStrategy getDefaultLatestStrategy() { if (_defaultLatestStrategy == null) { _defaultLatestStrategy = new LatestRevisionStrategy(); } return _defaultLatestStrategy; } public void setDefaultLatestStrategy(LatestStrategy defaultLatestStrategy) { _defaultLatestStrategy = defaultLatestStrategy; } private EventListenerList _listeners = new EventListenerList(); public void addTransferListener(TransferListener listener) { _listeners.add(TransferListener.class, listener); } public void removeTransferListener(TransferListener listener) { _listeners.remove(TransferListener.class, listener); } public boolean hasTransferListener(TransferListener listener) { return Arrays.asList(_listeners.getListeners(TransferListener.class)).contains(listener); } protected void fireTransferEvent(TransferEvent evt) { Object[] listeners = _listeners.getListenerList(); for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==TransferListener.class) { ((TransferListener)listeners[i+1]).transferProgress(evt); } } } public void addIvyListener(IvyListener listener) { _listeners.add(IvyListener.class, listener); } public void removeIvyListener(IvyListener listener) { _listeners.remove(IvyListener.class, listener); } public boolean hasIvyListener(IvyListener listener) { return Arrays.asList(_listeners.getListeners(IvyListener.class)).contains(listener); } public void fireIvyEvent(IvyEvent evt) { Object[] listeners = _listeners.getListenerList(); for (int i = listeners.length-2; i>=0; i-=2) { if (listeners[i]==IvyListener.class) { ((IvyListener)listeners[i+1]).progress(evt); } } } public void transferProgress(TransferEvent evt) { fireTransferEvent(evt); fireIvyEvent(evt); } public boolean isUseRemoteConfig() { return _useRemoteConfig; } public void setUseRemoteConfig(boolean useRemoteConfig) { _useRemoteConfig = useRemoteConfig; } public DependencyResolver getDictatorResolver() { return _dictatorResolver; } public void setDictatorResolver(DependencyResolver dictatorResolver) { _dictatorResolver = dictatorResolver; } /** * WARNING: Replace all current ivy variables by the given Map. * Should be used only when restoring variables. * * Thr given Map is not copied, but stored by reference. * @param variables */ public void setVariables(Map variables) { if (variables == null) { throw new NullPointerException("variables shouldn't be null"); } _variables = variables; } public static URL getDefaultConfigurationURL() { return Ivy.class.getResource("conf/ivyconf.xml"); } }
package boa.types; /** * A type variable for use with functions that return types dependent on their argument types. * * @author rdyer */ public class BoaTypeVar extends BoaScalar { private String name; public BoaTypeVar (String name) { this.name = name; } public String getName() { return name; } /** {@inheritDoc} */ @Override public boolean accepts(BoaType that) { return true; } /** {@inheritDoc} */ @Override public String toString() { return "TypeVar " + name; } }
/* description: The linkdb output by nutch contain the url and the urls \ that direct to the first url in every single line.Then we \ need to convert it to the url and the urls that the url direct \ to in every single line. input: linkdb_data Text. output: linkdb_data2 Text. Mapper: <null, urls> --> <srcUrl, targetUrl> Reducer: <srcUrl, Iterator<targetUrl>> --> <null, srcUrl+targetUrls> */ package SearchPackage; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableComparator; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Partitioner; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.MapFileOutputFormat; public class OutLinks { public static class OutLinksMapper extends Mapper <LongWritable, Text, Text, Text> { public void map (LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String urls[] = line.split(" "); int urlSize = urls.length; for(int i = 1; i < urlSize; i++) { context.write(new Text(urls[i]), new Text(urls[0])); } } } public static class OutLinksReducer extends Reducer <Text, Text, Text, NullWritable > { public void reduce (Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { StringBuffer OutLinkStr = new StringBuffer(key.toString()); for(Text value : values) { OutLinkStr.append(" ").append(value.toString()); } context.write(new Text(OutLinkStr.toString()), NullWritable.get()); } } public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: OutLinks <input path> <output path>"); System.exit(-1); } Job job = new Job(); job.setJarByClass(OutLinks.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setMapperClass(OutLinksMapper.class); job.setReducerClass(OutLinksReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Text.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(NullWritable.class); job.waitForCompletion(true); } }
package Database; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import Cars.Car; import Freeways.Freeway; public class ExecuteCommands { public static void main(String[] args) { try { ExecuteCommands demo = new ExecuteCommands(); } catch (NumberFormatException e) { e.printStackTrace(); } } public static void addFreeway(int freewayID, int numCars, int averageSpeed) { Connection connection = null; try { connection = CreateConnection.getConnection(); Statement insertStatement = connection.createStatement(); insertStatement.executeUpdate("INSERT INTO FinalProject.Freeways " + "VALUES("+freewayID+", "+numCars+", "+averageSpeed+")"); } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public static void updateFreeway(int freewayID, int numCars, int averageSpeed) { Connection connection = null; try { connection = CreateConnection.getConnection(); Statement insertStatement = connection.createStatement(); insertStatement.executeUpdate("UPDATE FinalProject.Freeways " + "SET numCars='"+numCars+"', averageSpeed='"+averageSpeed+"' " + "WHERE Name='"+freewayID+"';"); } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public static Freeway getFreewayInfo(int freewayID) { ResultSet rs = null; Connection connection = null; java.sql.Statement statement = null; Freeway freeway = null; String query = "SELECT * FROM FinalProject.Freeways WHERE carID=" + freewayID; try { connection = CreateConnection.getConnection(); statement = connection.createStatement(); rs = statement.executeQuery(query); if (rs.next()) { // employee = new Employee(); // employee.setEmpId(rs.getInt("emp_id")); // employee.setEmpName(rs.getString("emp_name")); // employee.setDob(rs.getDate("dob")); // employee.setSalary(rs.getDouble("salary")); // employee.setDeptId((rs.getInt("dept_id"))); } } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return freeway; } }
import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.text.SimpleDateFormat; import java.util.Iterator; import java.util.List; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.LogarithmicAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CombinedDomainXYPlot; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.Marker; import org.jfree.chart.plot.ValueMarker; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.time.FixedMillisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.ui.Layer; import org.jfree.ui.RectangleAnchor; import org.jfree.ui.TextAnchor; import org.jfree.util.ShapeUtilities; public class Plotting { public static CombinedDomainXYPlot createPlot() { final CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis("Domain")); plot.setGap(10.0); final DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss")); return plot; } public static XYPlot plotPQData(CombinedDomainXYPlot parent, String title, TimeSeriesCollection calculated, TimeSeriesCollection fitted) { final JFreeChart chart = ChartFactory.createTimeSeriesChart(title, // String "Time", // String timeAxisLabel title, // String valueAxisLabel, calculated, // XYDataset dataset, true, // include legend false, // tooltips false); // urls XYPlot xyPlot = (XYPlot) chart.getPlot(); xyPlot.setDomainCrosshairVisible(true); xyPlot.setRangeCrosshairVisible(true); final DateAxis axis = (DateAxis) xyPlot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss")); // final NumberAxis axis2 = new NumberAxis(title + "Speed"); // xyPlot.setRangeAxis(1, axis2); // xyPlot.setDataset(1, speedColl); // xyPlot.mapDatasetToRangeAxis(1, 1); XYLineAndShapeRenderer lineRenderer1 = new XYLineAndShapeRenderer(true, true); xyPlot.setRenderer(lineRenderer1); parent.add(xyPlot); return xyPlot; } public static void plotSingleVesselData( CombinedDomainXYPlot parent, String title, Track ownshipTrack, List<LegOfData> ownshipLegs, Color transColor, Color color, List<Long> valueMarkers, final Long endTime) { TimeSeriesCollection dataset1 = new TimeSeriesCollection(); TimeSeriesCollection dataset2 = new TimeSeriesCollection(); TimeSeries data1 = new TimeSeries(title + "Course", FixedMillisecond.class); TimeSeries data2 = new TimeSeries(title + "Speed", FixedMillisecond.class); double[] courses = ownshipTrack.getCourses(); double[] speeds = ownshipTrack.getSpeeds(); long[] times = ownshipTrack.getDates(); // obtain the data for the points for (int i = 0; i < times.length; i++) { long thisTime = times[i]; if(endTime == null || thisTime <= endTime) { data1.add(new FixedMillisecond(thisTime), courses[i]); data2.add(new FixedMillisecond(thisTime), speeds[i]); } } dataset1.addSeries(data1); dataset2.addSeries(data2); final JFreeChart chart = ChartFactory.createTimeSeriesChart(title, // String "Time", // String timeAxisLabel title + "Course", // String valueAxisLabel, dataset1, // XYDataset dataset, true, // include legend true, // tooltips false); // urls XYPlot xyPlot = (XYPlot) chart.getPlot(); xyPlot.setDomainCrosshairVisible(true); xyPlot.setRangeCrosshairVisible(true); final DateAxis axis = (DateAxis) xyPlot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss")); final NumberAxis axis2 = new NumberAxis(title + "Speed"); xyPlot.setRangeAxis(1, axis2); xyPlot.setDataset(1, dataset2); xyPlot.mapDatasetToRangeAxis(1, 1); XYLineAndShapeRenderer lineRenderer1 = new XYLineAndShapeRenderer(true, true); lineRenderer1.setSeriesPaint(0, color); lineRenderer1.setSeriesShape(0, ShapeUtilities.createUpTriangle(2f)); XYLineAndShapeRenderer lineRenderer2 = new XYLineAndShapeRenderer(true, true); lineRenderer2.setSeriesPaint(0, color); lineRenderer2.setSeriesShape(0, ShapeUtilities.createDownTriangle(2f)); // ok, and store them xyPlot.setRenderer(0, lineRenderer1); xyPlot.setRenderer(1, lineRenderer2); // let's try the shading if (ownshipLegs != null) { Iterator<LegOfData> iter = ownshipLegs.iterator(); while (iter.hasNext()) { LegOfData leg = (LegOfData) iter.next(); final Marker bst = new IntervalMarker(leg.getStart(), leg.getEnd(), transColor, new BasicStroke(2.0f), null, null, 1.0f); bst.setLabel(leg.getName()); bst.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT); bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10)); bst.setLabelTextAnchor(TextAnchor.BASELINE_RIGHT); xyPlot.addDomainMarker(bst, Layer.BACKGROUND); } } // let's try the shading if (valueMarkers != null) { plotMarkers(xyPlot, valueMarkers); } parent.add(xyPlot); } public static void plotCombinedVesselData( CombinedDomainXYPlot parent, Track ownshipTrack, List<LegOfData> ownshipLegs, Color ownshipCol, Track tgtTrack, List<LegOfData> tgtLegs, Color tgtCol, List<Long> turnEstimates, final Long endTime) { TimeSeriesCollection courseColl = new TimeSeriesCollection(); TimeSeriesCollection speedColl = new TimeSeriesCollection(); TimeSeries oCourse = new TimeSeries("O/S Course", FixedMillisecond.class); TimeSeries oSpeed = new TimeSeries("O/S Speed", FixedMillisecond.class); TimeSeries tCourse = new TimeSeries("Tgt Course", FixedMillisecond.class); TimeSeries tSpeed = new TimeSeries("Tgt Speed", FixedMillisecond.class); double[] oCourses = ownshipTrack.getCourses(); double[] oSpeeds = ownshipTrack.getSpeeds(); long[] oTimes = ownshipTrack.getDates(); double[] tCourses = tgtTrack.getCourses(); double[] tSpeeds = tgtTrack.getSpeeds(); // obtain the data for the points for (int i = 0; i < oTimes.length; i++) { long thisTime = oTimes[i]; if(endTime == null || thisTime <= endTime) { oCourse.add(new FixedMillisecond(thisTime), oCourses[i]); oSpeed.add(new FixedMillisecond(thisTime), oSpeeds[i]); tCourse.add(new FixedMillisecond(thisTime), tCourses[i]); tSpeed.add(new FixedMillisecond(thisTime), tSpeeds[i]); } } courseColl.addSeries(oCourse); speedColl.addSeries(oSpeed); courseColl.addSeries(tCourse); speedColl.addSeries(tSpeed); final JFreeChart chart = ChartFactory.createTimeSeriesChart(null, // String "Time", // String timeAxisLabel "Course", // String valueAxisLabel, courseColl, // XYDataset dataset, true, // include legend true, // tooltips false); // urls XYPlot xyPlot = (XYPlot) chart.getPlot(); xyPlot.setDomainCrosshairVisible(true); xyPlot.setRangeCrosshairVisible(true); final DateAxis axis = (DateAxis) xyPlot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss")); final NumberAxis axis2 = new NumberAxis("Speed"); xyPlot.setRangeAxis(1, axis2); xyPlot.setDataset(1, speedColl); xyPlot.mapDatasetToRangeAxis(1, 1); XYLineAndShapeRenderer lineRenderer1 = new XYLineAndShapeRenderer(true, true); lineRenderer1.setSeriesPaint(0, Color.blue); lineRenderer1.setSeriesPaint(1, Color.red); lineRenderer1.setSeriesShape(0, ShapeUtilities.createUpTriangle(2f)); lineRenderer1.setSeriesShape(1, ShapeUtilities.createDownTriangle(2f)); XYLineAndShapeRenderer lineRenderer2 = new XYLineAndShapeRenderer(true, true); lineRenderer2.setSeriesPaint(0, Color.blue); lineRenderer2.setSeriesPaint(1, Color.red); lineRenderer2.setSeriesShape(0, ShapeUtilities.createDownTriangle(2f)); lineRenderer2.setSeriesShape(1, ShapeUtilities.createUpTriangle(2f)); // ok, and store them xyPlot.setRenderer(0, lineRenderer1); xyPlot.setRenderer(1, lineRenderer2); // let's try the shading if (ownshipLegs != null) { Iterator<LegOfData> iter = ownshipLegs.iterator(); while (iter.hasNext()) { LegOfData leg = (LegOfData) iter.next(); final Marker bst = new IntervalMarker(leg.getStart(), leg.getEnd(), ownshipCol, new BasicStroke(2.0f), null, null, 1.0f); bst.setLabel(leg.getName()); bst.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT); bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10)); bst.setLabelTextAnchor(TextAnchor.BASELINE_RIGHT); xyPlot.addDomainMarker(bst, Layer.BACKGROUND); } } if (tgtLegs != null) { Iterator<LegOfData> iter = tgtLegs.iterator(); while (iter.hasNext()) { LegOfData leg = (LegOfData) iter.next(); final Marker bst = new IntervalMarker(leg.getStart(), leg.getEnd(), tgtCol, new BasicStroke(2.0f), null, null, 1.0f); bst.setLabel(leg.getName()); bst.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT); bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10)); bst.setLabelTextAnchor(TextAnchor.BASELINE_RIGHT); xyPlot.addDomainMarker(bst, Layer.BACKGROUND); } } // let's try the shading if (turnEstimates != null) { plotMarkers(xyPlot, turnEstimates); } parent.add(xyPlot); } public static void addLegResults( CombinedDomainXYPlot parent, TimeSeriesCollection errorValues, List<Long> valueMarkers) { final JFreeChart chart = ChartFactory.createTimeSeriesChart( "Leg Results", // String // title, "Time", // String timeAxisLabel "Errpr", // String valueAxisLabel, errorValues, // XYDataset dataset, true, // include legend true, // tooltips false); // urls XYPlot xyPlot = (XYPlot) chart.getPlot(); xyPlot.setDomainCrosshairVisible(true); xyPlot.setRangeCrosshairVisible(true); final DateAxis axis = (DateAxis) xyPlot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss")); final NumberAxis rangeAxis = new LogarithmicAxis("Log(error)"); xyPlot.setRangeAxis(rangeAxis); XYLineAndShapeRenderer lineRenderer1 = new XYLineAndShapeRenderer(true, true); xyPlot.setRenderer(0, lineRenderer1); // let's try the shading if (valueMarkers != null) { plotMarkers(xyPlot, valueMarkers); } xyPlot.getRenderer().setSeriesVisibleInLegend(true); parent.add(xyPlot); } /** Plot a series of vertical markers * @param xyPlot * @param valueMarkers */ private static void plotMarkers(XYPlot xyPlot, List<Long> valueMarkers) { Iterator<Long> iter = valueMarkers.iterator(); while (iter.hasNext()) { Long leg = (Long) iter.next(); final Marker bst = new ValueMarker(leg, Color.gray, new BasicStroke(3.0f), null, null, 1.0f); bst.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT); bst.setLabelFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 10)); bst.setLabelTextAnchor(TextAnchor.BASELINE_RIGHT); xyPlot.addDomainMarker(bst, Layer.BACKGROUND); } } public static void plotSensorData(CombinedDomainXYPlot parent, long[] times, double[] bearings, TimeSeries rmsScores) { TimeSeriesCollection scores = new TimeSeriesCollection(); scores.addSeries(rmsScores); TimeSeriesCollection dataset = new TimeSeriesCollection(); TimeSeries bSeries = new TimeSeries("Bearings", FixedMillisecond.class); dataset.addSeries(bSeries); for (int i = 0; i < bearings.length; i++) { bSeries.add(new FixedMillisecond(times[i]), bearings[i]); } final JFreeChart chart = ChartFactory.createTimeSeriesChart( "Leg Results", // String // title, "Time", // String timeAxisLabel "Bearing", // String valueAxisLabel, dataset, // XYDataset dataset, true, // include legend true, // tooltips false); // urls XYPlot xyPlot = (XYPlot) chart.getPlot(); xyPlot.setDomainCrosshairVisible(true); xyPlot.setRangeCrosshairVisible(true); final DateAxis axis = (DateAxis) xyPlot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss")); // final NumberAxis rangeAxis = new LogarithmicAxis("Log(error)"); // xyPlot.setRangeAxis(rangeAxis); final NumberAxis axis2 = new LogarithmicAxis("RMS Error"); xyPlot.setRangeAxis(1, axis2); xyPlot.setDataset(1, scores); xyPlot.mapDatasetToRangeAxis(1, 1); XYLineAndShapeRenderer lineRenderer2 = new XYLineAndShapeRenderer(true, false); xyPlot.setRenderer(1, lineRenderer2); xyPlot.getRenderer().setSeriesVisibleInLegend(false); // final NumberAxis rangeAxis = new LogarithmicAxis("Log(error)"); // xyPlot.setRangeAxis(rangeAxis); XYLineAndShapeRenderer lineRenderer1 = new XYLineAndShapeRenderer(true, true); xyPlot.setRenderer(0, lineRenderer1); xyPlot.getRenderer().setSeriesVisibleInLegend(true); parent.add(xyPlot); } }
package sudoku; import common.Pair; import common.Universe; import common.time.TimeBuilder; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import sudoku.parse.Parser; import sudoku.parse.SadmanParser; import sudoku.parse.TxtParser; /** * <p>Represents a sudoku target as a bipartite graph of {@link Claim truth-claims} such as "Cell * 1,7 has value 3." and {@link Rule groupings of claims} of which one claim per grouping is true * and the rest in the same group are false.</p> <p>The Claims are internally stored as * {@link SpaceMap a three-dimensional array} where the dimensions are the x and y coordinates that * a cell may have in the target and a z coordinate which is the values available to the cells.</p> * <p>A Puzzle features a sort of memory of history in the form of a time tree, built upon by * calling {@link #timeBuilder() timeBuilder()}} and using {@link TimeBuilder its methods}. * Automatic Rule-collapse uses this time-tree, and all Techniques used in solving the target should * do so, too.</p> * @author fiveham * @author fiveham * */ public class Puzzle extends SudokuNetwork{ /** * <p>The index for the x-dimension.</p> */ public static final int X_DIM = 0; /** * <p>The index for the y-dimension.</p> */ public static final int Y_DIM = 1; /** * <p>The index for the z-dimension.</p> */ public static final int Z_DIM = 2; /** * <p>A three-dimensional array of this Puzzle's Claims.</p> */ private SpaceMap claims; /** * <p>A list of all the valid dimension-independent values for coordinates in this Puzzle.</p> */ private List<IndexValue> indices; /** * <p>A list of lists which contain dimension-associated valid coordinate values for this * Puzzle.</p> */ private List<List<IndexInstance>> dimensions; private final Universe<Fact> factUniverse; private final Universe<Claim> claimUniverse; /** * <p>Constructs a Puzzle using the text in the specified file {@code f}.</p> * @param f the file containing the target in text form at the start of the file * @throws FileNotFoundException if {@code f} cannot be found or read */ public Puzzle(File f, String charset) throws FileNotFoundException{ this(chooseParser(f,charset)); } public Puzzle(Parser parser){ super(parser.mag()); this.indices = genIndices(sideLength, this); this.dimensions = genDimensions(indices, this); this.claims = new SpaceMap(this); this.nodes.addAll(genRuleNodes(this, sideLength, claims)); this.nodes.ensureCapacity(nodes.size()+sideLength*sideLength*sideLength); StreamSupport.stream(claims.spliterator(), false).forEach(nodes::add); for(Claim c : parseText(parser.values())){ Init specificValue = new Init(this, c); nodes.add(specificValue); } this.claimUniverse = new Universe<>(claimStream()); this.factUniverse = new Universe<>(factStream()); } private static Parser chooseParser(File f, String charset) throws FileNotFoundException{ String extension = f.getName(); extension = extension.substring(extension.lastIndexOf(".")); switch(extension){ case ".txt": return new TxtParser(f, charset); case ".sdk": return new SadmanParser(f, charset); default: throw new IllegalArgumentException("Illegal file extension "+extension+" only .txt and .sdk allowed."); } } /** * <p>Generates the Rules for {@code p}.</p> * @param p a sudoku puzzle * @param sideLength the side-length of {@code p} * @param claims {@code p}'s SpaceMap of Claims * @return a list of the Rules for {@code p} */ private List<Rule> genRuleNodes(Puzzle p, int sideLength, SpaceMap claims){ List<Rule> rules = new ArrayList<>( RuleType.values().length * (int) Math.pow(p.sideLength, DIMENSION_COUNT)); for(RuleType type : RuleType.values()){ for(IndexInstance dimA : type.dimA(p)){ for(IndexInstance dimB : type.dimB(p)){ Rule newerRule = new Rule( p, type, type.dimInsideRule(p).stream() .map((dimC) -> claims.get(dimA, dimB, dimC)) .collect(Collectors.toList()), dimA, dimB); rules.add(newerRule); } } } return rules; } /** * <p>Generates the lists of dimension-associated valid coordinate values for {@code p}.</p> * @param indices a pre-computed list of the valid coordinate values for {@code p} * @param p the Puzzle for which these dimensions are being generated * @see #dimensions * @return a list of the lists of dimension-associated valid coordinate values for {@code p} */ private static List<List<IndexInstance>> genDimensions(List<IndexValue> indices, Puzzle p){ List<List<IndexInstance>> dimensions = new ArrayList<>(DimensionType.values().length); for(DimensionType type : DimensionType.values()){ List<IndexInstance> indexInstancesForType = new ArrayList<>(indices.size()); for(IndexValue i : indices){ indexInstancesForType.add( new IndexInstance(type, i) ); } dimensions.add(indexInstancesForType); } return dimensions; } private static List<IndexValue> genIndices(int sideLength, Puzzle p){ List<IndexValue> indices = new ArrayList<>(sideLength); for(int i = 0; i < sideLength; ++i){ indices.add(new IndexValue(p, i)); } return Collections.unmodifiableList(indices); } /** * <p>Returns this target's SpaceMap of claims.</p> * @return this target's SpaceMap of claims */ public SpaceMap claims(){ return claims; } public Claim claim(int x, int y, int z){ return claims.get(x, y, z); } public Universe<Fact> factUniverse(){ return factUniverse; } public Universe<Claim> claimUniverse(){ return claimUniverse; } /** * <p>Returns a list (sorted) of all the {@link #IndexValue index values} that exist for this * Puzzle.</p> * @return a list (sorted) of all the {@link #IndexValue index values} that exist for this * Puzzle. */ List<IndexValue> indexValues(){ return indices; } List<IndexInstance> indexInstances(DimensionType dim){ return dimensions.get(dim.ordinal()); } private IndexValue indexFromInt(int i){ try{ return indices.get(i); } catch(IndexOutOfBoundsException e){ throw new IllegalArgumentException(e); } } /** * <p>Returns the in-memory IndexValue corresponding to the specified human-readable integer * value.</p> <p>This is used to convert the 1-based human-readable integers in a target's * source file into the 0-based in-memory IndexValues used by Puzzle to specify values of * spatial coordinates.</p> * @param i a 1-based human-readable integer from a target's source text file * @return a 0-based IndexValue corresponding to the 1-based integer {@code i}. */ private IndexValue indexFromHumanReadableInt(int i){ return indexFromInt(i-1); } /** * <p>A convenience method that returns the outputs of {@link #decodeX(IndexInstance...) decodeX}, * {@link #decodeY(IndexInstance...) decodeY}, and {@link #decodeZ(IndexInstance...) decodeZ}, as * an ordered triple in the form of an array.</p> * @param points dimensional indices passed on to decodeX, decodeY, and decodeZ * @return an ordered triple of the outputs of decodeX, decodeY, and decodeZ given the same * parameter this method received */ public IndexValue[] decodeXYZ(IndexInstance... points){ return new IndexValue[]{ decodeX(points), decodeY(points), decodeZ(points) }; } /** * <p>Returns the IndexValue for this Puzzle {@link #indexFromInt(int) corresponding} to the sum * of the x-components of the specified {@code points}.</p> * @param points IndexInstances from this puzzle * @returns the IndexValue for this Puzzle {@link #indexFromInt(int) corresponding} to the sum * of the x-components of the specified {@code points} */ IndexValue decodeX(IndexInstance... dims){ return decodeDim(IndexInstance::contributionX, dims); } /** * <p>Returns the IndexValue for this Puzzle {@link #indexFromInt(int) corresponding} to the sum * of the y-components of the specified {@code points}.</p> * @param points IndexInstances from this puzzle * @returns the IndexValue for this Puzzle {@link #indexFromInt(int) corresponding} to the sum * of the y-components of the specified {@code points} */ IndexValue decodeY(IndexInstance... dims){ return decodeDim(IndexInstance::contributionY, dims); } /** * <p>Returns the IndexValue for this Puzzle {@link #indexFromInt(int) corresponding} to the sum * of the z-components of the specified {@code points}.</p> * @param points IndexInstances from this puzzle * @returns the IndexValue for this Puzzle {@link #indexFromInt(int) corresponding} to the sum * of the z-components of the specified {@code points} */ IndexValue decodeZ(IndexInstance... points){ return decodeDim(IndexInstance::contributionZ, points); } /** * <p>The number of physical spatial dimensions ({@value}) pertinent to this model of a sudoku * target.</p> */ public static final int DIMENSION_COUNT = 3; /** * <p>Decodes the specified dimensional component of the specified {@code dims} and returns the * {@link #indexFromInt(int) corresponding IndexValue}.</p> * <p>Performs the actual work for {@link #decodeX()}, {@link #decodeY}, and {@link #decodeZ}.</p> * @param dimComponent a function used to specify which dimension's component (x, y, or z) will * be summed * @param points dimensional indices * @return the IndexValue {@link #indexFromInt(int) corresponding} to the combined specified * dimensional contributions of the specified dimensional indices */ private IndexValue decodeDim( Function<IndexInstance, Integer> dimComponent, IndexInstance[] points){ int score = 0; for(IndexInstance dim : points){ score += dimComponent.apply(dim); } return indexFromInt(score); } /** * <p>Returns a string representing the target, with each cell represented by its solved value * if known or by a space if the cell's value is unknown.</p> * @return a string representing the target, with each cell represented by its solved value if * known or by a space if the cell's value is unknown */ @Override public String toString(){ StringBuilder result = new StringBuilder(); class InterNumber implements Supplier<String>{ private int useCount = 0; @Override public String get(){ StringBuilder result = new StringBuilder(" "); if(++useCount % sideLength() == 0){ result.append(System.lineSeparator()); } return result.toString(); } } Supplier<String> betweenNumbers = new InterNumber(); nodeStream() .filter(Rule.class::isInstance) .map(Rule.class::cast) .filter(RuleType.CELL::isTypeOf) .sorted((cell1, cell2) -> { int snake1 = cell1.dimB().intValue() + cell1.dimA().intValue() * sideLength(); int snake2 = cell2.dimB().intValue() + cell2.dimA().intValue() * sideLength(); return Integer.compare(snake1, snake2); }) .forEach((cell) -> result.append(cell.isSolved() ? cell.iterator().next().getZ() : BLANK_CELL) .append(betweenNumbers.get())); return result.toString(); } /** * <p>Returns the x-coordinate of the low-X edge of the specified box. The index of a box * follows a snaking pattern from the upper left with box 0, moving rightward and increasing, * then wrapping around to the next line of boxes below as needed until the lower right is * reached.</p> * @param boxIndex the index of the box whose lower-x-coordinate edge's x-coordinate is * returned. * @return the x-coordinate of the low-X edge of the box in the {@code boxIndex}-th box of a * Puzzle whose {@link Sudoku#magnitude() magnitude} is {@code mag} */ private static int boxLowX(IndexValue boxIndex, int mag){ return mag * snakeInSquareX(boxIndex, mag); } /** * <p>Returns the y-coordinate of the low-Y edge of the specified box. The index of a box * follows a snaking pattern from the upper left with box 0, moving rightward and increasing, * then wrapping around to the next line of boxes below as needed until the lower right is * reached.</p> * @param boxIndex the index of the box whose lower-y-coordinate edge's y-coordinate is * returned. * @return the y-coordinate of the low-Y edge of the box in the {@code boxIndex}-th box of a * Puzzle whose {@link Sudoku#magnitude() magnitude} is {@code mag} */ private static int boxLowY(IndexValue boxIndex, int mag){ return mag * snakeInSquareY(boxIndex, mag); } /** * <p>Returns a list of those Claims from {@link #claims the SpaceMap} that are true, given the * content of the source file for this target. * @param values a list of the integer values of the cells of this target as read from this * target's source text. {@value #BLANK_CELL} indicates an empty cell.</p> * @return a list of those Claims from {@link #claims the SpaceMap} that are true, given the * content of the source file for this target */ private List<Claim> parseText(List<Integer> values){ List<Claim> knownTrueClaims = new ArrayList<>(); int pointer = 0; for(IndexValue y : indices){ for(IndexValue x : indices){ int value; try{ value = values.get(pointer++); } catch(IndexOutOfBoundsException e){ throw new IllegalArgumentException("Fewer than "+ sideLength*sideLength +" tokens in source text", e); } if(value != BLANK_CELL){ knownTrueClaims.add( claims.get(x,y, indexFromHumanReadableInt(value)) ); } } } return knownTrueClaims; } /** * <p>The value ({@value #BLANK_CELL}) used internally to refer to a blank cell or to the value * in a blank cell.</p> */ public static final int BLANK_CELL = 0; /** * <p>Entries in this enum describe properties of the four types of regions in a sudoku target: * <ul><li>box</li><li>row</li><li>column</li><li>cell</li></ul></p> <p>The first two dimensions * of a RegionSpecies are held constant for any one Rule (in regards to the Rule's initial set * of Claims) with that RegionSpecies as its type, while the RegionSpecies's third dimension is * fully explored within the aforementioned Rule.</p> * @author fiveham * @author fiveham * */ public static enum RuleType{ /** * <p>For a box, the first dimension is {@link Puzzle.DimensionType#SYMBOL z}, the second * dimension is {@link Puzzle.DimensionType#BOX box-index}, and the third dimension is * {@link Puzzle.DimensionType#CELL_ID_IN_BOX cell-index}.</p> */ BOX (DimensionType.SYMBOL, DimensionType.BOX, DimensionType.CELL_ID_IN_BOX, (rt,p) -> "The "+p.getA().val.humanReadableIntValue()+" in "+rt+" "+p.getB().val.humanReadableIntValue()), /** * <p>For a row, the first dimension is {@link Puzzle.DimensionType#SYMBOL z}, the second * dimension is {@link Puzzle.DimensionType#Y y}, and the third dimension is * {@link Puzzle.DimensionType#X x}.</p> */ ROW (DimensionType.SYMBOL, DimensionType.Y, DimensionType.X, (rt,p) -> "The "+p.getA().val.humanReadableIntValue()+" in "+rt+" "+p.getB().val.humanReadableIntValue()), /** * <p>For a box, the first dimension is {@link Puzzle.DimensionType#SYMBOL z}, the second * dimension is {@link Puzzle.DimensionType#X x}, and the third dimension is * {@link Puzzle.DimensionType#Y y}.</p> */ COLUMN (DimensionType.SYMBOL, DimensionType.X, DimensionType.Y, (rt,p) -> "The "+p.getA().val.humanReadableIntValue()+" in "+rt+" "+p.getB().val.humanReadableIntValue()), /** * <p>For a cell, the first dimension is {@link Puzzle.DimensionType#Y y}, the second * dimension is {@link Puzzle.DimensionType#X x}, and the third dimension is * {@link Puzzle.DimensionType#SYMBOL z}.</p> */ CELL (DimensionType.Y, DimensionType.X, DimensionType.SYMBOL, (rt,p) -> "The value in "+rt+" "+p.getB().val.humanReadableIntValue()+","+p.getA().val.humanReadableIntValue()); private final DimensionType dimAType; private final DimensionType dimBType; private final DimensionType dimCType; private final BiFunction<RuleType,Pair<IndexInstance,IndexInstance>,String> description; private RuleType(DimensionType dimAType, DimensionType dimBType, DimensionType dimCType, BiFunction<RuleType,Pair<IndexInstance,IndexInstance>,String> description){ this.dimAType = dimAType; this.dimBType = dimBType; this.dimCType = dimCType; this.description = description; } /** * <p>Returns a description of a Rule of this type having the specified {@code dimA} and * {@code dimB}.</p> * @param dimA the first dimension of the Rule being described * @param dimB the second dimension of the Rule being described * @return a description of a Rule of this type having the specified {@code dimA} and * {@code dimB} */ public String descriptionFor(IndexInstance dimA, IndexInstance dimB){ return description.apply(this, new Pair<>(dimA,dimB)); } public boolean isTypeOf(Rule r){ return r.getType()==this; } /** * <p>Returns a list of all the dimension-value pairs for the first dimension of a region of * this species in the specified Puzzle.</p> * @param p the Puzzle to which the returned IndexInstances belong * @return a list of all the dimension-value pairs for the first dimension of a region of * this species in the specified Puzzle */ public List<IndexInstance> dimA(Puzzle p){ return p.indexInstances(dimAType); } /** * <p>Returns a list of all the dimension-value pairs for the second dimension of a region * of this species in the specified Puzzle.</p> * @param p the Puzzle to which the returned IndexInstances belong * @return a list of all the dimension-value pairs for the second dimension of a region of * this species in the specified Puzzle */ public List<IndexInstance> dimB(Puzzle p){ return p.indexInstances(dimBType); } /** * <p>Returns a list of all the dimension-value pairs for the third dimension of a region of * this species in the specified Puzzle.</p> * @param p the Puzzle to which the returned IndexInstances belong * @return a list of all the dimension-value pairs for the third dimension of a region of * this species in the specified Puzzle */ public List<IndexInstance> dimInsideRule(Puzzle p){ return p.indexInstances(dimCType); } } /** * <p>A wrapper for IndexValue that internally specifies to which * {@link Puzzle.DimensionType dimension} (of which five are available) the wrapped IndexValue * pertains.</p> * @author fiveham * @author fiveham * */ public static class IndexInstance{ private DimensionType type; private IndexValue val; /** * <p>Constructs an IndexInstance belonging to the {@code target}, pertaining to the * specified dimension {@code type} and having the value {@code val}.</p> * @param target the Puzzle to which this IndexInstance belongs * @param type the dimension along which this IndedInstance lies * @param val the value of this IndexInstance's position along its dimension */ public IndexInstance(DimensionType type, IndexValue val){ this.type = type; this.val = val; } @Override public boolean equals(Object o){ if(o instanceof IndexInstance){ IndexInstance d = (IndexInstance) o; return d.type.equals(type) && d.val.equals(val); } return false; } public int intValue(){ return val.intValue(); } /** * <p>The {@link Puzzle.DimensionType dimension type} of this IndexInstance.</p> * @return {@link Puzzle.DimensionType dimension type} of this IndexInstance */ public DimensionType getType(){ return type; } /** * <p>The x-component of the wrapped IndexValue given that it specifies a position along * this IndexInstance's wrapped {@link #getType() dimension}.</p> * @return the x-component of the wrapped IndexValue given that it pertains to the wrapped * dimension */ public int contributionX(){ return type.contribX.apply(val, val.puzzle.magnitude); } /** * <p>The y-component of the wrapped IndexValue given that it specifies a position along * this IndexInstance's wrapped {@link #getType() dimension}.</p> * @return the y-component of the wrapped IndexValue given that it pertains to the wrapped * dimension */ public int contributionY(){ return type.contribY.apply(val, val.puzzle.magnitude); } /** * <p>The z-component of the wrapped IndexValue given that it specifies a position along * this IndexInstance's wrapped {@link #getType() dimension}.</p> * @return the z-component of the wrapped IndexValue given that it pertains to the wrapped * dimension */ public int contributionZ(){ return type.contribZ.apply(val, val.puzzle.magnitude); } } /** * <p>A dimensional component contribution function that provides a contribution of zero * regardless of its inputs.</p> */ private static final BiFunction<IndexValue,Integer,Integer> ZERO = (indx,mag) -> 0; /** * <p>A dimensional component contribution function that produces all the the input dimension * value as output.</p> */ private static final BiFunction<IndexValue,Integer,Integer> INT_VALUE = (indx,mag) -> indx.intValue(); private static int snakeInSquareX(IndexValue index, int magnitude){ return index.intValue() % magnitude; } private static int snakeInSquareY(IndexValue index, int magnitude){ return index.intValue() / magnitude; } /** * <p>This enum specifies the properties of the five claim-coordinating dimensions available in * this model of a sudoku target.</p> * @author fiveham * @author fiveham * */ public static enum DimensionType{ /** * <p>The conventional x dimension. An IndexInstance in this dimension contributes all of * its value to the x dimension and contributes zero to y and z.</p> */ X (INT_VALUE, ZERO, ZERO), /** * <p>The conventional y dimension. An IndexInstance in this dimension contributes all of * its value to the y dimension and contributes zero to x and z.</p> */ Y (ZERO, INT_VALUE, ZERO), /** * <p>The conventional z dimension. An IndexInstance in this dimension contributes all of * its value to the z dimension and contributes zero to x and y.</p> */ SYMBOL (ZERO, ZERO, INT_VALUE), /** * <p>The dimension for box-index within the target. This dimension snakes through the * target from the upper left corner (low x,y), increases to the right (higher x), then * jumps back to the next row once it reaches maximum x, continuing in this fashion until it * reaches the lower right corner (high x,y).</p> */ BOX (Puzzle::boxLowX, Puzzle::boxLowY, ZERO), /** * <p>The dimension for cell-index within a box. This dimension snakes through a box-sized * area from the upper left corner (low x,y), increases to the right (higher x), then jumps * back to the next row once it reaches maximum x within the box, continuing in this fashion * until it reaches the lower right corner (high x,y) of the box.</p> */ CELL_ID_IN_BOX (Puzzle::snakeInSquareX, Puzzle::snakeInSquareY, ZERO); private final BiFunction<IndexValue,Integer,Integer> contribX; private final BiFunction<IndexValue,Integer,Integer> contribY; private final BiFunction<IndexValue,Integer,Integer> contribZ; private DimensionType(BiFunction<IndexValue,Integer,Integer> contribX, BiFunction<IndexValue,Integer,Integer> contribY, BiFunction<IndexValue,Integer,Integer> contribZ){ this.contribX = contribX; this.contribY = contribY; this.contribZ = contribZ; } } /** * <p>A wrapper for an integer value valid for use as a coordinate in this Puzzle along any of * its Claim-coordinating dimensions.</p> <p>The number of index values a given Puzzle has is * equal to the side-length of the target and thus may vary. In order to allow a Puzzle to take * on an arbitrary size depending solely on the Puzzle's source text, its allowable index values * must be determined at runtime instead of being hard-coded in an enum as has previously been * the case. The use of an enum is preferable over the use of raw primitive data types such as * {@code int} because {@code int} and other applicable types can vary over a wider range than a * Puzzle ever needs and thus need to be range-checked. Another reason to avoid the use of * primitive data types for the purposes that IndexValue fulfills is that both an enum and a * runtime-generated list of non-enum values allow less verbose iteration, not having to * explicitly range-check an int against the target's sidelength for instance.</p> * @author fiveham * @author fiveham * */ public static class IndexValue{ /** * <p>The Puzzle to which this IndexValue belongs.</p> */ private final Puzzle puzzle; /** * <p>The wrapped int value.</p> */ private final int v; /** * <p>Constructs an IndexValue belonging to {@code target} and wrapping {@code v}.</p> * @param target the Puzzle to which this IndexValue belongs * @param v the int value wrapped by this IndexValue */ private IndexValue(Puzzle puzzle, int v){ this.puzzle = puzzle; this.v = v; } /** * <p>The wrapped int value.</p> * @return the wrapped int value */ public int intValue(){ return v; } /** * <p>The target that owns and created this IndexValue. This IndexValue is only valid in * this Puzzle.</p> * @return the Puzzle that owns and created this IndedValue */ public Puzzle getPuzzle(){ return puzzle; } /** * <p>Returns this IndexValue's wrapped int value plus 1, translating the internal 0-based * values to the conventional 1-based values used in written sudoku puzzles.</p> * @return the wrapped integer plus 1 */ public int humanReadableIntValue(){ return v+1; } /** * <p>Returns the human-readable representation of the wrapped integer value.</p> * @return a string representation of the wrapped int value plus 1 */ public String humanReadableSymbol(){ return Integer.toString(humanReadableIntValue(), puzzle.sideLength+1); } @Override public String toString(){ return Integer.toString(humanReadableIntValue()); } @Override public boolean equals(Object o){ if(o instanceof IndexValue){ IndexValue iv = (IndexValue) o; return puzzle == iv.puzzle && v == iv.v; } return false; } } }
package example; // -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ import java.awt.*; import javax.swing.*; import javax.swing.plaf.basic.BasicTabbedPaneUI; public final class MainPanel extends JPanel { public static final Color SELECTED_BG = new Color(255, 150, 0); public static final Color UNSELECTED_BG = new Color(255, 50, 0); private MainPanel() { super(new BorderLayout()); UIManager.put("TabbedPane.tabInsets", new Insets(5, 10, 5, 10)); // UIManager.put("TabbedPane.selectedTabPadInsets", new Insets(2, 3, 2, 2)); UIManager.put("TabbedPane.contentBorderInsets", new Insets(5, 5, 5, 5)); UIManager.put("TabbedPane.tabAreaInsets", new Insets(0, 0, 0, 0)); UIManager.put("TabbedPane.selectedLabelShift", 0); UIManager.put("TabbedPane.labelShift", 0); // UIManager.put("TabbedPane.foreground", Color.WHITE); // UIManager.put("TabbedPane.selectedForeground", Color.WHITE); // UIManager.put("TabbedPane.unselectedBackground", UNSELECTED_BG); // UIManager.put("TabbedPane.tabAreaBackground", UNSELECTED_BG); JTabbedPane tabs = new JTabbedPane() { @Override public void updateUI() { super.updateUI(); setUI(new BasicTabbedPaneUI() { @Override protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) { // Do not paint anything } @Override protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { // Do not paint anything } @Override protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) { g.setColor(isSelected ? SELECTED_BG : UNSELECTED_BG); g.fillRect(x, y, w, h); } @Override protected void paintContentBorderTopEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { g.setColor(SELECTED_BG); g.fillRect(x, y, w, h); } @Override protected void paintContentBorderRightEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { g.setColor(SELECTED_BG); g.fillRect(x, y, w, h); } @Override protected void paintContentBorderBottomEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { g.setColor(SELECTED_BG); g.fillRect(x, y, w, h); } @Override protected void paintContentBorderLeftEdge(Graphics g, int tabPlacement, int selectedIndex, int x, int y, int w, int h) { g.setColor(SELECTED_BG); g.fillRect(x, y, w, h); } }); setOpaque(true); setForeground(Color.WHITE); setBackground(UNSELECTED_BG); setTabPlacement(SwingConstants.LEFT); setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); } }; tabs.addTab("A", new ImageIcon(getClass().getResource("wi0009-32.png")), new JScrollPane(new JTree())); tabs.addTab("B", new ImageIcon(getClass().getResource("wi0054-32.png")), new JScrollPane(new JTextArea())); tabs.addTab("C", new ImageIcon(getClass().getResource("wi0062-32.png")), new JScrollPane(new JTree())); tabs.addTab("D", new ImageIcon(getClass().getResource("wi0063-32.png")), new JScrollPane(new JTextArea())); add(tabs); setPreferredSize(new Dimension(320, 240)); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGui(); } }); } public static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package flowreader.utils; import flowreader.FlowReader; import flowreader.model.Document; import flowreader.model.Page; import flowreader.model.WordCloud; import flowreader.view.MainView; import flowreader.view.PageView; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Properties; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.ButtonBuilder; import javafx.scene.control.LabelBuilder; import javafx.scene.control.ProgressIndicator; import javafx.scene.effect.BoxBlur; import javafx.scene.layout.HBoxBuilder; import javafx.scene.paint.Color; import javafx.scene.text.Text; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; /** * * @author D-Day */ public class TextFileReader extends Task { private File file; private HashMap<String, Integer> commonWords; private Document doc; private MainView mv; private ProgressIndicator pi; public TextFileReader(MainView mv, ProgressIndicator pi) { this.commonWords = new HashMap<String, Integer>(); this.getCommonWords(); this.mv = mv; this.pi = pi; } public void startFileChooser(Stage primaryStage) { //start file chooser File f = new File(System.getProperty("user.dir")); FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Please choose a text file to read"); fileChooser.setInitialDirectory(f); //Set extension filter FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt"); fileChooser.getExtensionFilters().add(extFilter); //Show save file dialog file = fileChooser.showOpenDialog(primaryStage); } /** * @param bounds the boundaries of the page used to know how much text * contains a page * @return a list of pages that contains the text of each page and the words * occurrences * @throws IOException */ public Document readFile(double width, double height) throws IOException { System.out.println("Debut readfile"); ArrayList<Page> pages = new ArrayList<Page>(); // The list of all the pages ArrayList<WordCloud> wordClouds = new ArrayList(); ArrayList<ArrayList<WordCloud>> wordCloudLevels = new ArrayList<ArrayList<WordCloud>>(); // Text Wrapper double boundWidth = width; // Width of the page double boundHeight = height; // Height of the page double spaceWidth = new Text(" ").getBoundsInLocal().getWidth(); // Width of a space double lineHeight = new Text("").getBoundsInLocal().getHeight(); // Height of a line double spaceLeft = width; // Width of the page Text tempPage = new Text(""); String pageText = ""; HashMap<String, Integer> wordsOccurrences = new HashMap<String, Integer>(); LineNumberReader lnr = new LineNumberReader(new java.io.FileReader(file)); lnr.skip(Long.MAX_VALUE); int numberOfLines = lnr.getLineNumber(); //System.out.println(numberOfLines); LineNumberReader r = new LineNumberReader(new java.io.FileReader(file)); try{ String paragraph, word; int nbligne = 0; while ((paragraph = r.readLine()) != null) { nbligne++; this.updateProgress(nbligne, numberOfLines+1); //System.out.println(nbligne); Scanner sc = new Scanner(paragraph); try{ while (sc.hasNext()) { // while there is words in the line word = sc.next(); /*if(this.trimPunctuation(word).equals("apple")){ System.out.println(word+" "+this.trimPunctuation(word)); }*/ double wordWidth = new Text(word).getBoundsInLocal().getWidth(); double textWithNewLine = tempPage.getBoundsInLocal().getHeight() + lineHeight; if (textWithNewLine > boundHeight) { Page page = new Page(pageText); WordCloud wordCloud = new WordCloud(wordsOccurrences); //System.out.println(""+page.toString()); pages.add(page); wordClouds.add(wordCloud); pageText = ""; //System.out.println("Apple: "+wordsOccurrences.get("apple")); wordsOccurrences = new HashMap<String, Integer>(); } if (wordWidth + spaceWidth > spaceLeft) { if (!(textWithNewLine > boundHeight)) { pageText += "\n"; } spaceLeft = boundWidth - wordWidth; } else { spaceLeft = spaceLeft - (wordWidth + spaceWidth); } pageText += word + " "; word = this.trimPunctuation(word); if (!this.commonWords.containsKey(word)) { if (wordsOccurrences.get(word) != null) { wordsOccurrences.put(word, wordsOccurrences.get(word) + 1); } else { wordsOccurrences.put(word, 1); } } tempPage.setText(pageText); } if (!((tempPage.getBoundsInLocal().getHeight() + lineHeight) > boundHeight)) { pageText += "\n"; tempPage.setText(pageText); spaceLeft = boundWidth; } } finally{ if(sc!=null){ sc.close(); } } } //System.out.println("Apple: "+wordsOccurrences.get("apple")); Page page = new Page(pageText); WordCloud wordCloud = new WordCloud(wordsOccurrences); //System.out.println(""+page.toString()); pages.add(page); wordClouds.add(wordCloud); } finally{ if(r!=null){ r.close(); } } //wordCloudLevels.add(wordClouds);// add the first level ArrayList<ArrayList<WordCloud>> temp_list = makeCloudLevels(wordClouds); for (ArrayList<WordCloud> temp_element : temp_list) { wordCloudLevels.add(temp_element); } //System.out.println("number of levels:" + wordCloudLevels.size()); Document document = new Document(pages, wordCloudLevels); System.out.println("fin readfile"); return document; } private ArrayList<ArrayList<WordCloud>> makeCloudLevels(ArrayList<WordCloud> clouds) { ArrayList<ArrayList<WordCloud>> localLevels = new ArrayList<ArrayList<WordCloud>>(); ArrayList<ArrayList<WordCloud>> otherLevels = new ArrayList<ArrayList<WordCloud>>(); //updateProgress(1, 10); localLevels.add(clouds); ArrayList<WordCloud> currentLevel = new ArrayList<WordCloud>(); WordCloud cloudB = null; boolean haveB = false; int listCount = 0; int lastIndex = clouds.size() - 1; // there is only one word cloud on the previous level if (lastIndex == 0) { //localLevels.add(clouds); return localLevels; } // Get through the previous level of cloud to create the current level for (WordCloud cloud : clouds) { if (haveB && (cloudB != null)) { WordCloud newCloud = new WordCloud(cloud, cloudB); // if odd number of cloud merge of three clouds if (clouds.indexOf(cloud) + 1 == lastIndex) { WordCloud triCloud = new WordCloud(newCloud, clouds.get(lastIndex)); currentLevel.add(triCloud); } else { // else add the new cloud to the level currentLevel.add(newCloud); } haveB = false; } else { cloudB = cloud; haveB = true; } } otherLevels = makeCloudLevels(currentLevel); for (ArrayList<WordCloud> cloudList : otherLevels) { // add otherLevels to localLevels localLevels.add(cloudList); } return localLevels; } private void getCommonWords() { StringBuilder stringBuffer = new StringBuilder(); BufferedReader bufferedReader = null; try { InputStream f; f = TextFileReader.class.getResourceAsStream("CommonEnglishWords.txt"); //File f = new File("CommonEnglishWords.txt"); //System.out.println("xx"+f.getAbsolutePath()); bufferedReader = new BufferedReader(new InputStreamReader(f)); String temp_text; while ((temp_text = bufferedReader.readLine()) != null) { //System.out.println(temp_text); this.commonWords.put(temp_text, 1); } } catch (FileNotFoundException ex) { System.out.println("Couldn't find the file!"); } catch (IOException ex) { System.out.println("no idea!.. some IOException"); }finally { try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException ex) { System.out.println("couldn't close the file!"); } } } //removes punctuation from any words found private String trimPunctuation(String word) { String w = word.toLowerCase().replaceAll("\\W", ""); return w; } @Override protected Document call() throws Exception { Document docu = readFile(PageView.textBoundWidth, PageView.textBoundHeight); return docu; } }
package galileo.dataset.feature; import java.io.IOException; import galileo.serialization.ByteSerializable; import galileo.serialization.SerializationException; import galileo.serialization.SerializationInputStream; import galileo.serialization.SerializationOutputStream; import galileo.serialization.Serializer; /** * Contains Feature information -- arbitrary data dimensions for storage and * indexing. * * @author malensek */ public class Feature implements Comparable<Feature>, ByteSerializable { protected String name; protected FeatureData<? extends Comparable<?>> data; /** * Constructs a nameless, null Feature (no data). */ public Feature() { this(""); } /** * Constructs a null Feature (no data). */ public Feature(String name) { setName(name); this.data = new NullFeatureData(); } /** * Constructs an integer Feature. */ public Feature(String name, int value) { setName(name); this.data = new IntegerFeatureData(value); } /** * Constructs a nameless integer Feature. */ public Feature(int value) { this("", value); } /** * Constructs a long Feature. */ public Feature(String name, long value) { setName(name); this.data = new LongFeatureData(value); } /** * Constructs a nameless long Feature. */ public Feature(long value) { this("", value); } /** * Constructs a floating point Feature. */ public Feature(String name, float value) { setName(name); this.data = new FloatFeatureData(value); } /** * Constructs a nameless floating point Feature. */ public Feature(float value) { this("", value); } /** * Constructs a double-precision floating point Feature. */ public Feature(String name, double value) { setName(name); this.data = new DoubleFeatureData(value); } /** * Constructs a nameless double-precision floating point Feature. */ public Feature(double value) { this("", value); } /** * Constructs an interval Feature with bounds specified as int values. */ public Feature(String name, int value1, int value2) { setName(name); this.data = new IntegerIntervalFeatureData(value1, value2); } /** * Constructs a nameless interval Feature with bounds specified as int * values. */ public Feature(int value1, int value2) { this("", value1, value2); } /** * Constructs an interval Feature with bounds specified as long values. */ public Feature(String name, long value1, long value2) { setName(name); this.data = new LongIntervalFeatureData(value1, value2); } /** * Constructs an interval Feature with bounds specified as long values. */ public Feature(long value1, long value2) { this("", value1, value2); } /** * Constructs an interval Feature with bounds specified as floating point * values. */ public Feature(String name, float value1, float value2) { setName(name); this.data = new FloatIntervalFeatureData(value1, value2); } /** * Constructs a nameless interval Feature with bounds specified as floating * point values. */ public Feature(float value1, float value2) { this("", value1, value2); } /** * Constructs an interval Feature with bounds specified as double-precision * floating point values. */ public Feature(String name, double value1, double value2) { setName(name); this.data = new DoubleIntervalFeatureData(value1, value2); } /** * Constructs a nameless interval Feature with bounds specified as * double-precision floating point values. */ public Feature(double value1, double value2) { this("", value1, value2); } /** * Constructs a String Feature. */ public Feature(String name, String value) { setName(name); this.data = new StringFeatureData(value); } /** * Constructs a nameless Feature that contains raw binary information * (byte array). */ public Feature(byte[] bytes) { this("", bytes); } /** * Constructs a Feature that contains raw binary information (byte array). */ public Feature(String name, byte[] bytes) { setName(name); this.data = new BinaryFeatureData(bytes); } /** * Creates a shallow copy of a Feature. */ public Feature(Feature feature) { this(feature.name, feature); } /** * Creates a shallow copy of a Feature with the provided name. */ public Feature(String name, Feature feature) { setName(name); this.data = feature.data; } /** * Converts a native Object to a nameless Feature. Useful if the Object * type is not known in advance. * * @param o Object to convert to a Feature */ public static Feature fromNativeType(Object o) { return fromNativeType("", o); } /** * Converts a native Object to a Feature if the Object type is not known in * advance. This is done by determining if the provided object is an * instance of a valid Feature type, and then casting the Object to the * type. In general, this method should only be used in special cases where * an item's type is not known already. * * @param name Name of the resulting Feature * @param o Object to convert to a Feature */ public static Feature fromNativeType(String name, Object o) { FeatureType type = FeatureType.fromPrimitiveType(o); if (type == null) { throw new IllegalArgumentException("Cannot construct a Feature " + "from this type."); } switch (type) { case INT: return new Feature(name, (int) o); case LONG: return new Feature(name, (long) o); case FLOAT: return new Feature(name, (float) o); case DOUBLE: return new Feature(name, (double) o); case STRING: return new Feature(name, (String) o); default: throw new IllegalArgumentException("Could not instantiate " + "FeatureData"); } } public String getName() { return name; } private void setName(String name) { this.name = name; } public FeatureType getType() { return data.getType(); } public int getInt() { return data.toInt(); } public long getLong() { return data.toLong(); } public float getFloat() { return data.toFloat(); } public double getDouble() { return data.toDouble(); } /** * Returns the current Feature data as a String value. This method is * different from the toString() method, which provides a String * representation of the Feature class rather than just its data. * * @return String representation of this Feature's data. */ public String getString() { return data.toString(); } public boolean greater(Feature f) { return this.compareTo(f) > 0; } public boolean less(Feature f) { return this.compareTo(f) < 0; } @Override public int hashCode() { final int prime = 773; int result = 1; result = prime * result + ((data == null) ? 0 : data.hashCode()); result = prime * result + ((name == null) ? 0 : name.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; } Feature other = (Feature) obj; if (this.name.equals(other.name) && this.data.equals(other.data)) { return true; } return false; } @Override public int compareTo(Feature otherFeature) { return this.data.compareTo(otherFeature.data); } public String dataToString() { return "" + data; } @Override public String toString() { if (name.equals("")) { if (data.getType() == FeatureType.NULL) { return "[null]"; } else { return "(unnamed feature)=" + data; } } return name + "=" + data; } @Deserialize public Feature(SerializationInputStream in) throws IOException, SerializationException { name = new String(in.readString()); FeatureType type = FeatureType.fromInt(in.readInt()); data = Serializer.deserializeFromStream(type.toClass(), in); } @Override public void serialize(SerializationOutputStream out) throws IOException { out.writeString(name); out.writeInt(data.getType().toInt()); out.writeSerializable(data); } }
package gov.nih.nci.camod.util; import java.util.*; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Static helper class for sending e-mail. Propeteries are defined in "mail.properties" * * @author georgeda * */ public class MailUtil { static private final Log log = LogFactory.getLog(MailUtil.class); static private ResourceBundle macroBundle = null; private MailUtil() { } /** * @param inRecipients - the list of people to send e-mail to * @param inSubject - the subject of the e-mail * @param inMessage - the message to send * @param inFrom - who the message is from * */ static public void sendMail(String inRecipients[], String inSubject, String inMessage, String inFrom) throws MessagingException { log.trace("Entering sendMail"); try { // Convert the bundle to a properties file. Is there a better way to do this? ResourceBundle theBundle = ResourceBundle.getBundle("mail"); Properties theProperties = new Properties(); Enumeration theKeys = theBundle.getKeys(); while (theKeys.hasMoreElements()) { String theKey = (String) theKeys.nextElement(); theProperties.put(theKey, theBundle.getObject(theKey)); } boolean theDebugFlag = false; if (theProperties.getProperty("mail.debug") != null) { try { theDebugFlag = Boolean.getBoolean(theProperties.getProperty("mail.debug")); } catch (Exception e) { log.warn("Unable to set e-mail debug flag", e); } } // create some properties and get the default Session Session theSession = Session.getDefaultInstance(theProperties, null); theSession.setDebug(theDebugFlag); // create a message Message theEmailMessage = new MimeMessage(theSession); // set the from and to address InternetAddress theAddressFrom = new InternetAddress(inFrom); theEmailMessage.setFrom(theAddressFrom); InternetAddress[] theAddressTo = new InternetAddress[inRecipients.length]; for (int i = 0; i < inRecipients.length; i++) { theAddressTo[i] = new InternetAddress(inRecipients[i]); } theEmailMessage.setRecipients(Message.RecipientType.TO, theAddressTo); // Setting the Subject and Content Type theEmailMessage.setSubject(inSubject); theEmailMessage.setContent(inMessage, "text/plain"); log.debug("Sending email to: " + inRecipients); log.debug("email subject: " + inSubject); Transport.send(theEmailMessage); } catch (Exception e) { log.error("Unable to send e-mail", e); } log.trace("Exiting sendMail"); } /** * @param inRecipients - the list of people to send e-mail to * @param inSubject - the subject of the e-mail * @param inMessage - String to be used as an additional custom note within the body of content * @param inFrom - who the message is from * @param messageStds - an array of Strings to be used as keys to create the message to send * */ static public void sendMail(String inRecipients[], String inSubject, String inMessage, String inFrom, String[] messageStds) throws MessagingException { log.trace("Entering sendMail(String, String, String, String[])"); try { // Convert the bundle to a properties file. Is there a better way to do this? ResourceBundle theBundle = ResourceBundle.getBundle("mail"); Properties theProperties = new Properties(); Enumeration theKeys = theBundle.getKeys(); while (theKeys.hasMoreElements()) { String theKey = (String) theKeys.nextElement(); theProperties.put(theKey, theBundle.getObject(theKey)); } boolean theDebugFlag = false; if (theProperties.getProperty("mail.debug") != null) { try { theDebugFlag = Boolean.getBoolean(theProperties.getProperty("mail.debug")); } catch (Exception e) { log.warn("Unable to set e-mail debug flag", e); } } // create some properties and get the default Session Session theSession = Session.getDefaultInstance(theProperties, null); theSession.setDebug(theDebugFlag); // create a message Message theEmailMessage = new MimeMessage(theSession); // set the from and to address InternetAddress theAddressFrom = new InternetAddress(inFrom); theEmailMessage.setFrom(theAddressFrom); InternetAddress[] theAddressTo = new InternetAddress[inRecipients.length]; for (int i = 0; i < inRecipients.length; i++) { theAddressTo[i] = new InternetAddress(inRecipients[i]); } theEmailMessage.setRecipients(Message.RecipientType.TO, theAddressTo); // Setting the Subject and Content Type theEmailMessage.setSubject(inSubject); if (null == inMessage || "".equals(inMessage)) { theEmailMessage.setContent(constructMessageFromMacros(messageStds), "text/plain"); } else { theEmailMessage.setContent(constructMessageFromMacros(messageStds) + "\n\n" + inMessage , "text/plain"); } log.debug("Sending email to: " + inRecipients); log.debug("email subject: " + inSubject); Transport.send(theEmailMessage); } catch (Exception e) { log.error("Unable to send e-mail", e); } log.trace("Exiting sendMail(String, String, String, String[])"); } /** * Private method to construct the message body from an array of keys * * @param macros is the list of keys for expansion * @return String with macros expanded to use as the body of an e-mail message */ private static String constructMessageFromMacros(String[] macros) { StringBuffer sb = new StringBuffer(); try { if (null==macroBundle) loadMacroBundle(); } catch (MissingResourceException e) { log.error("Unable to load Macro ResourceBundle from within constructMessageFromMacros(macros)", e); return "A problem was encountered in generating automated e-mail. Please contact System Administrator"; } for (int i = 0; i < macros.length; i++) { sb.append(macroBundle.getString(macros[i])).append("\n"); } return sb.toString(); } /** * Private method to load the ResourceBundle where keys are mapped to e-mail strings. The * implementation here, rather than as part of the member property declaration, makes * it easier to figure out what is going right or wrong (e.g., missing properties file) * with log entries. */ private static void loadMacroBundle() { log.trace("loading Macro ResourceBundle"); macroBundle = ResourceBundle.getBundle("mailmacros"); log.trace("done loading Macro ResourceBundle"); } static public void main(String[] inArgs) { String[] theRecipients = new String[1]; theRecipients[0] = new String("georgeda@mail.nih.gov"); String[] theMessageKeys = {"defaultbody","alternative1","alternative2"}; try { sendMail(theRecipients, "Testing", "Hello there!", "georgeda@mail.nih.gov"); sendMail(theRecipients, "Testing 2", "Additional custom note goes here.", "georgeda@mail.nih.gov", theMessageKeys); } catch (Exception e) { System.out.println("Caught exception" + e); e.printStackTrace(); } } }
import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Testable { /** * Simple test annotation, to indicate that a method is a test method. */ @Retention(RetentionPolicy.RUNTIME) public @interface Test {} public class TestItFailure extends RuntimeException { public TestItFailure() {} public TestItFailure(String message) { super(message); } } public void assertThat(boolean expr) throws TestItFailure { if (!expr) { throw new TestItFailure(); } } public void assertEqual(Object a, Object b) throws TestItFailure { if (!a.equals(b)) { throw new TestItFailure(String.format( "%s != %s", a.toString(), b.toString())); } } public void fail() { assertThat(false); } /** * Default `runTests` method; `verbose` defaults to false. * See below. */ public void runTests() { runTests(false); } /** * * @param verbose: if true, print stack traces of errors to stderr; * otherwise, just show "pass" or "fail" for each test. */ public void runTests(boolean verbose) { try { int failures = doRunTests(verbose); if (failures > 0) { // If there are any failures, we should return // with a proper exit code indicating the failure. System.exit(1); } } catch (Exception e) { // Something unexpected happened. e.printStackTrace(); System.exit(1); } } /** * Override in subclasses to specify custom setup commands for each test * method. */ public void setUp() {} private int doRunTests(boolean verbose) throws IllegalAccessException, IllegalArgumentException { int testCount = 0; int passCount = 0; int failCount = 0; for (Method meth: this.getClass().getDeclaredMethods()) { // Check for `ATest` annotations, in order to find test methods. Annotation[] annots = meth.getAnnotationsByType(Testable.Test.class); if (annots.length > 0) { testCount++; boolean pass = true; try { this.setUp(); meth.invoke(this); } catch (InvocationTargetException ex) { if (verbose) { System.err.println("Error in method: " + meth.getName()); ex.getTargetException().printStackTrace(); } pass = false; } if (pass) { passCount++; } else { failCount++; } System.out.printf("%s: %s\n", meth.getName(), pass ? "pass": "fail"); } } System.out.printf( "%d/%d tests ran successfully (failed: %d)\n", passCount, testCount, failCount); return failCount; } }
package afc.ant.modular; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * <p>An entity that serves as a prototype of a {@link Module}. Each module is identified * by its {@link #getPath() path} relative to the root directory of this environment. * In addition, each module has metadata associated with it. This metadata consists of * {@link #getDependencies() dependencies} and {@link #getAttributes() attributes}.</p> * * <p>The module dependencies is a set of modules which this module depends upon. * Typically the dependee modules should be processed before this module can be * processed. A {@code ModuleInfo} holds references to its dependee modules by their paths.</p> * * <p>The module attributes are named pieces of data of free format. Attribute names * are case-sensitive. The {@code null} name is not allowed. An attribute value can be * any object or {@code null}.</p> * * <p>A typical workflow of module metadata processing is the following. A {@link ModuleLoader} * creates {@code ModuleInfo} instances that hold information about modules. These * {@code ModuleInfo}s are then converted into {@code Module}s by {@link ModuleRegistry}. * The dependency paths defined in the {@code ModuleInfo} are converted into {@code Module} * instances and the attributes are copied with no transformation.</p> * * <p>{@code ModuleInfo} is not thread-safe. Its instances are expected to be processed * by a single thread.</p> * * @author D&#378;mitry La&#365;&#269;uk */ public final class ModuleInfo { private final String path; private final HashSet<String> dependencies = new HashSet<String>(); private final Set<String> dependenciesView = Collections.unmodifiableSet(dependencies); private final HashMap<String, Object> attributes = new HashMap<String, Object>(); private final Map<String, Object> attributesView = Collections.unmodifiableMap(attributes); /** * <p>Creates a {@code ModuleInfo} with a given path. The normalised path is assigned. * The {@code ModuleInfo} instance created has neither dependencies nor attributes.</p> * * @param path the module path. It must not be {@code null}. * * @throws NullPointerException if <em>path</em> is {@code null}. */ public ModuleInfo(final String path) { if (path == null) { throw new NullPointerException("path"); } this.path = normalisePath(path); } /** * <p>Returns the path of this {@code ModuleInfo}. It is a path relative to the root directory * of the environment that is associated with this {@code ModuleInfo}.</p> * * @return the module path. It is necessarily non-{@code null}. */ public String getPath() { return path; } public void addDependency(final String dependency) { if (dependency == null) { throw new NullPointerException("dependency"); } final String normalisedDependency = normalisePath(dependency); if (normalisedDependency.equals(path)) { throw new IllegalArgumentException("Cannot add itself as a dependency."); } dependencies.add(normalisedDependency); } public void setDependencies(final Collection<String> dependencies) { if (dependencies == null) { throw new NullPointerException("dependencies"); } // Iteration is used instead of Collection#contains because not all collections support null elements. for (final String dependency : dependencies) { if (dependency == null) { throw new NullPointerException("dependencies contains null dependency."); } final String normalisedDependency = normalisePath(dependency); if (normalisedDependency.equals(path)) { throw new IllegalArgumentException("Cannot add itself as a dependency."); } } this.dependencies.clear(); for (final String dependency : dependencies) { this.dependencies.add(normalisePath(dependency)); } } /** * <p>Returns a set of module paths which this module depends upon. The set returned and * the paths it contains are necessarily non-{@code null}. The set returned is unmodifiable. * In addition, any further modification of this {@code ModuleInfo}'s dependencies by means of * the {@link #addDependency(String)} and {@link #setDependencies(Collection)} operations * is immediately visible in the set returned.</p> * * @return an unmodifiable set of this module's dependency modules. */ public Set<String> getDependencies() { return dependenciesView; } /** * <p>Sets a given attribute to this {@code ModuleInfo}. If the attribute with the given name * already exists then its value is replaced with the new value. The new attribute becomes * visible immediately via a set returned by {@link #getAttributes()}.</p> * * @param attributeName the name of the attribute. It must not be {@code null}. * Attribute names are case-sensitive. * @param value the attribute value. It can be {@code null}. * * @throws NullPointerException if <em>attributeName</em> is {@code null}. * This {@code ModuleInfo} instance is not modified in this case. */ public void addAttribute(final String attributeName, final Object value) { if (attributeName == null) { throw new NullPointerException("attributeName"); } attributes.put(attributeName, value); } public void setAttributes(final Map<String, Object> attributes) { if (attributes == null) { throw new NullPointerException("attributes"); } // Iteration is used instead of Map#containsKey because not all maps support null keys. for (final String attributeName : attributes.keySet()) { if (attributeName == null) { throw new NullPointerException("attributes contains an attribute with null name."); } } this.attributes.clear(); this.attributes.putAll(attributes); } /** * <p>Returns this module's attributes. The map returned is necessarily non-{@code null} and unmodifiable. * In addition, any further modification of this {@code ModuleInfo}'s attributes by means of * the <tt>{@link #addAttribute(String, Object)}</tt> and <tt>{@link #setAttributes(Map)}</tt> * operations is immediately visible in the map returned.</p> * * @return an unmodifiable map of this module's attributes. */ public Map<String, Object> getAttributes() { return attributesView; } static String normalisePath(final String path) { if (path.length() == 0) { return "/"; } if (path.charAt(path.length()-1) != '/') { return path + '/'; } return path; } }
package ie.omk.smpp.util; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Internal API configuration. This class holds the configuration for * the smppapi. On initialisation, it searches for a file named * "smppapi.properties". This file needs to be locatable in the classpath in one * of the following locations: /, /ie, /ie/omk, /ie/omk/smpp or the default * classloader for this class must be able to find it. * <p> * Most applications can probably accept the default settings of the API. If, * however, you're trying to eke maximum performance out of your application, * tweaking these settings may help. * </p> * <p> * Supported API properties are: <table cols="3" border="1" width="100%"> * <tr> * <th width="25%">Property name</th> * <th width="25%">Type</th> * <th width="50%">Description</th> * </tr> * * <tr> * <td><code>smppapi.net.buffersize_in</code></td> * <td>Integer</td> * <td>Sets the size of the buffer used on the incoming stream connection from * the SMSC. A plain value specified the number of bytes. A suffix of 'k' after * the number will be interpreted as kilobytes and a suffix of 'm' will be * interpreted as megabytes. For example, 4k will allocate a buffer size of 4096 * bytes.</td> * </tr> * * <tr> * <td><code>smppapi.net.buffersize_out</code></td> * <td>Integer</td> * <td>Sets the size of the buffer used on the outgoing stream connection to * the SMSC. A plain value specified the number of bytes. A suffix of 'k' after * the number will be interpreted as kilobytes and a suffix of 'm' will be * interpreted as megabytes. For example, 4k will allocate a buffer size of 4096 * bytes.</td> * </tr> * * <tr> * <td><code>smppapi.net.autoflush</code></td> * <td>Boolean</td> * <td>By default, the {@link ie.omk.smpp.net.SmscLink}class automatically * flushes the output stream after every packet written to the output stream. In * high-load environments, it may be better to turn this off and manually flush * the output stream only when required (after a short period of inactivity, for * example).</td> * </tr> * * <tr> * <td><code>smppapi.net.autoclose_snoop</code></td> * <td>Boolean</td> * <td>If snoop streams are set on the SMSC link object and this value is true * (the default), the snoop streams will be closed when the link is closed. If * false, the snoop streams will be flushed and left open when the link is * closed.</td> * </tr> * * <tr> * <td><code>smppapi.net.link_timeout</code></td> * <td>Long</td> * <td>Sets the timeout in milliseconds for network links. This value affects * how long network reads should block for but its exact interpretation is * link-implementation specific. For <code>TcpLink</code>, this value represents * the <code>SO_TIMEOUT</code> setting on the TCP/IP socket.</td> * </tr> * * <tr> * <td><code>smppapi.connection.bind_timeout</code></td> * <td>Long</td> * <td>The length of time, in milliseconds, to wait for a bind response packet * after sending a bind request. If a packet is not received within this time * period, the network connection is closed. A negative value or zero means wait * indefinitely.</td> * </tr> * * <tr> * <td><code>smppapi.connection.rcv_daemon.ioex_count</code></td> * <td>Integer</td> * <td>The number of I/O exceptions the receiver daemon will accept occurring * before exiting.</td> * </tr> * * <tr> * <td><code>smppapi.event.dispatcher</code></td> * <td>String</td> * <td>The name of a class which implements the * {@link ie.omk.smpp.event.EventDispatcher}which will be used as the default * event dispatcher for <code>Connection</code> objects.</td> * </tr> * * <tr> * <td><code>smppapi.event.threaded_dispatcher.pool_size</code></td> * <td>Integer</td> * <td>The size of the thread pool used by the * {@link ie.omk.smpp.event.ThreadedEventDispatcher}class.</td> * </tr> * * <tr> * <td><code>smppapi.event.threaded_dispatcher.queue_size</code></td> * <td>Integer</td> * <td>The size of the event FIFO queue used in the * <code>ie.omk.smpp.event.ThreadedEventDispatcher</code> class.</td> * </tr> * * <tr> * <td><code>smppapi.message.segment_size</code></td> * <td>Integer</td> * <td>The default segment size to use for concatenated short messages * using optional parameters.</td> * </tr> * * </table> * */ public final class APIConfig extends Properties { private static final String BAD_PROPERTY_VALUE = "Bad property value"; static final long serialVersionUID = 3668742926704484281L; /** * @see APIConfig */ public static final String LINK_BUFFERSIZE_IN = "smppapi.net.buffersize_in"; /** * @see APIConfig */ public static final String LINK_BUFFERSIZE_OUT = "smppapi.net.buffersize_out"; /** * @see APIConfig */ public static final String LINK_AUTO_FLUSH = "smppapi.net.autoflush"; /** * @see APIConfig */ public static final String LINK_AUTOCLOSE_SNOOP = "smppapi.net.autoclose_snoop"; /** * @see APIConfig */ public static final String LINK_TIMEOUT = "smppapi.net.link_timeout"; /** * @see APIConfig */ public static final String TOO_MANY_IO_EXCEPTIONS = "smppapi.connection.rcv_daemon.ioex_count"; /** * @see APIConfig */ public static final String EVENT_DISPATCHER_CLASS = "smppapi.event.dispatcher"; /** * @see APIConfig */ public static final String EVENT_THREAD_POOL_SIZE = "smppapi.event.threaded_dispatcher.pool_size"; /** * @see APIConfig */ public static final String EVENT_THREAD_FIFO_QUEUE_SIZE = "smppapi.event.threaded_dispatcher.queue_size"; /** * @see APIConfig */ public static final String BIND_TIMEOUT = "smppapi.connection.bind_timeout"; /** * @see APIConfig */ public static final String SEGMENT_SIZE = "smppapi.message.segment_size"; private static final Logger LOG = LoggerFactory.getLogger(APIConfig.class); private static final Map<String, Boolean> BOOLEANS = new HashMap<String, Boolean>(); /** * Paths to search for the API properties file. These should always end in * the '/' character except for the last entry which should be a blank * string. */ private static final String[] SEARCH_PATH = {"/", "/ie/", "/ie/omk/", "/ie/omk/smpp/", "", }; /** * Name of the resource to load properties from. */ private static final String PROPS_RESOURCE = "smppapi.properties"; /** * The singleton instance of the API configuration. */ private static APIConfig instance; /** * The URL that API properties are loaded from (including path info). */ private URL propsURL; static { BOOLEANS.put("1", Boolean.TRUE); BOOLEANS.put("true", Boolean.TRUE); BOOLEANS.put("on", Boolean.TRUE); BOOLEANS.put("yes", Boolean.TRUE); BOOLEANS.put("0", Boolean.FALSE); BOOLEANS.put("false", Boolean.FALSE); BOOLEANS.put("off", Boolean.FALSE); BOOLEANS.put("no", Boolean.FALSE); } /** * Construct a new APIConfig object which reads properties from the * default properties resource. */ public APIConfig() { this.propsURL = getDefaultPropertiesResource(); } /** * Construct a new APIConfig object which reads properties from the * specified URL. * @param propertiesURL The URL to read properties from. */ public APIConfig(URL propertiesURL) { this.propsURL = propertiesURL; } /** * Cause the API properties to be reloaded. The properties will be re-read * from the same location as they were initially loaded from. If the * resource has disappeared or is no longer accessible, the properties will * not be loaded and <code>false</code> will be returned to the caller. * * @return true if the properties were successfully reloaded, false * otherwise. */ public boolean reloadAPIConfig() { LOG.debug("Reloading API config properties."); try { loadAPIProperties(); } catch (IOException x) { LOG.warn("Could not reload API properties.", x); return false; } return true; } /** * Get the <code>APIConfig</code> instance. If the * <code>APIConfig</code> instance has not yet been initialised then * this method will cause the configuration to be read from the default * properties resource. The default resource will be searched for at * the following locations in the classpath: * /smppapi.properties * /ie/smppapi.properties * /ie/omk/smppapi.properties * /ie/omk/smpp/smppapi.properties * smppapi.properties * @return An initialised instance of <code>APIConfig</code>. */ public static APIConfig getInstance() { if (instance == null) { try { instance = new APIConfig(); instance.loadAPIProperties(); } catch (IOException x) { LOG.error("Could not load API properties from default resource", x); } } return instance; } /** * Set the URL which <code>APIConfig</code> reads its properties from * and load them. * @param properties */ public static void configure(URL properties) { try { if (instance == null) { instance = new APIConfig(properties); } else { instance.propsURL = properties; } instance.loadAPIProperties(); } catch (IOException x) { LOG.error("Could not load API config from {}", properties); LOG.error("Stack trace", x); } } /** * Get the value for a property. * * @param property * the name of the property to retrieve. * @return The value for <code>property</code>. * @throws ie.omk.smpp.util.PropertyNotFoundException * if <code>property</code> is not found in the configuration. */ public String getProperty(String property) throws PropertyNotFoundException { String val = super.getProperty(property); if (val == null) { throw new PropertyNotFoundException(property); } else { return val; } } /** * Get the value for a property or return a default value if it is not set. * @param property The name of the property to retrieve. * @param defaultValue The value to return if <code>property</code> is not * set. * @return The value for <code>property</code>. */ public String getProperty(String property, String defaultValue) { String val = super.getProperty(property); if (val == null) { val = defaultValue; } return val; } /** * Get the value of a property, parsed as a <code>short</code>. If the * property is not set, the default value is returned. * @param property The name of the property to retrieve the value for. * @param defaultValue The default value to return if the property is * not set. * @return The value for <code>property</code>. * @throws InvalidConfigurationException If the value cannot be parsed as * a <code>short</code>. */ public short getShort(String property, short defaultValue) throws InvalidConfigurationException { short s; try { s = getShort(property); } catch (PropertyNotFoundException x) { s = defaultValue; } return s; } /** * Get the value for a property, parsed as a Java <code>short</code>. * * @param property * the name of the property to retrive. * @throws ie.omk.smpp.util.PropertyNotFoundException * if <code>property</code> is not found in the configuration. * @throws ie.omk.smpp.util.InvalidConfigurationException * if the value is not a valid short. */ public short getShort(String property) throws InvalidConfigurationException, PropertyNotFoundException { int i = getInt(property); if (i < Short.MIN_VALUE || i > Short.MAX_VALUE) { throw new InvalidConfigurationException("Property value exceeds " + "valid short range: " + i, property); } return (short) i; } /** * Get the value for a property, parsed as a Java <code>int</code>. If * the property is not found, the default value is returned. * * @param property * the name of the property to retrive. * @param defaultValue * the value to return if the property does not exist. * @throws ie.omk.smpp.util.InvalidConfigurationException * if the value is not a valid integer. */ public int getInt(String property, int defaultValue) throws InvalidConfigurationException { int value; try { value = getInt(property); } catch (PropertyNotFoundException x) { value = defaultValue; } return value; } /** * Get the value for a property, parsed as a Java <code>int</code>. * * @param property * the name of the property to retrive. * @throws ie.omk.smpp.util.PropertyNotFoundException * if <code>property</code> is not found in the configuration. * @throws ie.omk.smpp.util.InvalidConfigurationException * if the value is not a valid integer. */ public int getInt(String property) throws InvalidConfigurationException, PropertyNotFoundException { long l; try { String n = getProperty(property); l = convertToNumber(n); if (l < (long) Integer.MIN_VALUE || l > (long) Integer.MAX_VALUE) { throw new InvalidConfigurationException("Property value exceeds" + " valid int range: " + l, property); } } catch (NumberFormatException x) { throw new InvalidConfigurationException(BAD_PROPERTY_VALUE, property); } return (int) l; } /** * Get the value for a property, parsed as a Java <code>long</code>. If * the property is not found, the default value is returned. * * @param property * the name of the property to retrive. * @param defaultValue * the value to return if the property does not exist. * @throws ie.omk.smpp.util.InvalidConfigurationException * if the value is not a valid long. */ public long getLong(String property, long defaultValue) throws InvalidConfigurationException { long l; try { l = getLong(property); } catch (PropertyNotFoundException x) { l = defaultValue; } return l; } /** * Get the value for a property, parsed as a Java <code>long</code>. * * @param property * the name of the property to retrive. * @throws ie.omk.smpp.util.PropertyNotFoundException * if <code>property</code> is not found in the configuration. * @throws ie.omk.smpp.util.InvalidConfigurationException * if the value is not a valid long. */ public long getLong(String property) throws InvalidConfigurationException, PropertyNotFoundException { long l; try { String n = getProperty(property); l = convertToNumber(n); } catch (NumberFormatException x) { throw new InvalidConfigurationException(BAD_PROPERTY_VALUE, property); } return l; } /** * Get a property as a boolean value. Any of 'on', 'yes' or 'true' * (irrelevant of case) will evaluate to <code>true</code>. Any of 'off', * 'no' or 'false' will evaluate to <code>false</code>. Boolean * parameters may also be specified as a number, where zero will equate to * <code>false</code> while non-zero will equate to <code>true</code>. * All other words will result in an InvalidConfigurationException being * thrown. * * @param property * the name of the property to look up. * @param defaultValue * the value to return if the property does not exist. * @throws InvalidConfigurationException * if the property has a value that cannot be parsed or * interpreted as boolean. */ public boolean getBoolean(String property, boolean defaultValue) throws InvalidConfigurationException { boolean value; try { value = getBoolean(property); } catch (PropertyNotFoundException x) { value = defaultValue; } return value; } /** * Get a property as a boolean value. Any of 'on', 'yes' or 'true' * (irrelevant of case) will evaluate to <code>true</code>. Any of 'off', * 'no' or 'false' will evaluate to <code>false</code>. Boolean * parameters may also be specified as a number, where zero will equate to * <code>false</code> while non-zero will equate to <code>true</code>. * All other words will result in an exception being thrown. * * @throws ie.omk.smpp.util.PropertyNotFoundException * if <code>property</code> is not found in the configuration. * @throws InvalidConfigurationException * if the property has a value that cannot be parsed or * interpreted as boolean. */ public boolean getBoolean(String property) throws InvalidConfigurationException, PropertyNotFoundException { String s = getProperty(property).toLowerCase(); Boolean bool = BOOLEANS.get(s); if (bool == null) { try { if (Integer.parseInt(s) != 0) { bool = Boolean.TRUE; } else { bool = Boolean.FALSE; } } catch (NumberFormatException x) { throw new InvalidConfigurationException( BAD_PROPERTY_VALUE, property, s); } } return bool.booleanValue(); } /** * Try to locate the default smppapi properties resource. * @return A URL pointing to the default properties resource, or * <code>null</code> if it cannot be found. */ private URL getDefaultPropertiesResource() { URL url = null; Class c = getClass(); for (int i = 0; i < SEARCH_PATH.length && url == null; i++) { url = c.getResource(SEARCH_PATH[i] + PROPS_RESOURCE); } return url; } /** * Load the properties. */ private void loadAPIProperties() throws IOException { if (propsURL != null) { load(propsURL.openStream()); if (LOG.isDebugEnabled()) { LOG.debug("Loaded API properties from {}", propsURL); StringWriter w = new StringWriter(); list(new PrintWriter(w)); LOG.debug("\n" + w.toString()); } } } /** * Convert a number string into a <code>long</code>, taking into account * base and multiplication specifiers. * @param num The String representing the number. * @return The parsed number. * @throws NumberFormatException If the String cannot be parsed as a number. */ long convertToNumber(final String num) throws NumberFormatException { int base = 10; long multiplier = 1; String s; char firstChar = num.charAt(0); char lastChar = num.charAt(num.length() - 1); if (num.startsWith("0x") || num.startsWith("0X")) { base = 16; s = num.substring(2); } else if (lastChar == 'b') { base = 2; s = num.substring(0, num.length() - 1); } else if (lastChar == 'k') { multiplier = 1024L; s = num.substring(0, num.length() - 1); } else if (lastChar == 'm') { multiplier = 1048576L; s = num.substring(0, num.length() - 1); } else if (firstChar == '0' && num.length() > 1) { base = 8; s = num.substring(1); } else { s = num; } return Long.parseLong(s, base) * multiplier; } }
package meetup.beeno; import java.util.ArrayList; import java.util.List; import java.util.Map; import meetup.beeno.util.HUtil; import meetup.beeno.util.PBUtil; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.util.Bytes; import org.apache.log4j.Logger; /** * Generates updates for secondary index tables based on an update for * the indexed table. This implementation generates index keys based * on a primary property value (from which the index is mapped) and an * optional date column, which can be appended to the key as is or as * an inverted value for reverse chronological sorting. * * Extra columns mapped in the index will be stored in index table * row, along with the primary property value and the date column (if * present), and can be used for filtering in scanning the index. * * TODO: Currently this implementation does not handle removing * secondary index rows when a value is removed!!! * * @author garyh * */ public class EntityIndexer { static final byte[] INDEX_FAMILY = Bytes.toBytes("__idx__"); static final byte[] INDEX_KEY_COLUMN = Bytes.toBytes("row"); private static final byte[] ROW_KEY_SEP = Bytes.toBytes("-"); private static Logger log = Logger.getLogger(EntityIndexer.class); private String indexTable; private HUtil.HCol primaryField; private HUtil.HCol dateField; private boolean invertDate = false; private List<HUtil.HCol> extraFields; public EntityIndexer(EntityMetadata.IndexMapping mapping) { this.indexTable = mapping.getTableName(); this.primaryField = new HUtil.HCol(mapping.getPrimaryField().getFamily(), mapping.getPrimaryField().getColumn()); this.dateField = mapping.getDateField(); this.invertDate = mapping.isDateInverted(); this.extraFields = mapping.getExtraFields(); } public String getIndexTable() { return this.indexTable; } /** * Returns a set of updates for this index table, based on the * update to the underlying table. * * @param entityUpdate * @return */ public List<Put> getIndexUpdates(Put entityUpdate) { List<Put> up = new ArrayList<Put>(1); /* TODO: handle many index records to one base record. * For example, if the primary property value contains * a collection type, a new index record could be generated * for each value in the collection. */ Put valUpdate = getUpdateForValue(entityUpdate); if (valUpdate != null) up.add(valUpdate); return up; } protected Put getUpdateForValue(Put entityUpdate) { Put put = null; // generate the index row key Map<byte[],List<KeyValue>> familyMap = entityUpdate.getFamilyMap(); // store all the indexed values byte[] primaryVal = getValue(this.primaryField.family(), this.primaryField.column(), familyMap); if (primaryVal != null && primaryVal.length > 0) { Long date = getDateValue(familyMap); put = new Put( createIndexKey(primaryVal, date, entityUpdate.getRow()) ); // sync with base timestamp put.setTimeStamp( entityUpdate.getTimeStamp() ); // store all specified values (when present) put.add(this.primaryField.family(), this.primaryField.column(), primaryVal); if (this.dateField != null && date != null) put.add(this.dateField.family(), this.dateField.column(), PBUtil.toBytes(date)); // add any extra fields for (HUtil.HCol col : this.extraFields) { byte[] val = getValue(col.family(), col.column(), familyMap); if (val != null) put.add(col.family(), col.column(), val); } // store the orig record key put.add(INDEX_FAMILY, INDEX_KEY_COLUMN, entityUpdate.getRow()); } else { // no update for primary value, skip log.debug("No primary value for index "+getIndexTable()); } return put; } protected Long getDateValue(Map<byte[],List<KeyValue>> familyMap) { Long dateVal = null; if (this.dateField != null) { byte[] rawDate = getValue(this.dateField.family(), this.dateField.column(), familyMap); HDataTypes.HField pbDate = PBUtil.readMessage(rawDate); // dates are assumed to be Long! if (pbDate != null && pbDate.getType() == HDataTypes.HField.Type.INTEGER) dateVal = pbDate.getInteger(); } return dateVal; } protected byte[] getValue(byte[] family, byte[] col, Map<byte[],List<KeyValue>> familyMap) { byte[] val = null; List<KeyValue> familyVals = familyMap.get(family); if (familyVals != null) { for (KeyValue kv : familyVals) { if (kv.matchingColumn(family, col)) { val = kv.getValue(); break; } } } return val; } /** * TODO: split this out into a separate interface for different * implementations */ public byte[] createIndexKey(byte[] primaryVal, Long date, byte[] origRow) { byte[] key = new byte[0]; HDataTypes.HField pbVal = PBUtil.readMessage(primaryVal); // order numeric types if (pbVal != null && pbVal.getType() == HDataTypes.HField.Type.INTEGER) { key = Bytes.add(key, HUtil.toOrderedBytes(pbVal.getInteger())); } else { // just use raw bytes key = Bytes.add(key, primaryVal); } // add on date, if specified if (this.dateField != null && date != null) { key = Bytes.add(key, Bytes.add(ROW_KEY_SEP, HUtil.toOrderedBytes(date, this.invertDate)) ); } // add on the original row key to ensure uniqueness if (origRow != null && origRow.length > 0) { key = Bytes.add(key, Bytes.add(ROW_KEY_SEP, origRow)); } return key; } }
package org.apache.fop.apps; // FOP import org.apache.fop.fo.ElementMapping; import org.apache.fop.fo.FOTreeBuilder; import org.apache.fop.fo.FOUserAgent; import org.apache.fop.fo.FOInputHandler; import org.apache.fop.fo.FOTreeHandler; import org.apache.fop.mif.MIFHandler; import org.apache.fop.render.Renderer; import org.apache.fop.render.awt.AWTRenderer; import org.apache.fop.rtf.renderer.RTFHandler; import org.apache.fop.tools.DocumentInputSource; import org.apache.fop.tools.DocumentReader; // Avalon import org.apache.avalon.framework.logger.ConsoleLogger; import org.apache.avalon.framework.logger.LogEnabled; import org.apache.avalon.framework.logger.Logger; // DOM import org.w3c.dom.Document; // SAX import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; // Java import java.io.IOException; import java.io.OutputStream; /** * Primary class that drives overall FOP process. * <P> * The simplest way to use this is to instantiate it with the * InputSource and OutputStream, then set the renderer desired, and * calling run(); * <P> * Here is an example use of Driver which outputs PDF: * * <PRE> * Driver driver = new Driver(new InputSource (args[0]), * new FileOutputStream(args[1])); * driver.enableLogging(myLogger); //optional * driver.setRenderer(RENDER_PDF); * driver.run(); * </PRE> * If neccessary, calling classes can call into the lower level * methods to setup and * render. Methods can be called to set the * Renderer to use, the (possibly multiple) ElementMapping(s) to * use and the OutputStream to use to output the results of the * rendering (where applicable). In the case of the Renderer and * ElementMapping(s), the Driver may be supplied either with the * object itself, or the name of the class, in which case Driver will * instantiate the class itself. The advantage of the latter is it * enables runtime determination of Renderer and ElementMapping(s). * <P> * Once the Driver is set up, the render method * is called. Depending on whether DOM or SAX is being used, the * invocation of the method is either render(Document) or * buildFOTree(Parser, InputSource) respectively. * <P> * A third possibility may be used to build the FO Tree, namely * calling getContentHandler() and firing the SAX events yourself. * <P> * Once the FO Tree is built, the format() and render() methods may be * called in that order. * <P> * Here is an example use of Driver which outputs to AWT: * * <PRE> * Driver driver = new Driver(); * driver.enableLogging(myLogger); //optional * driver.setRenderer(new org.apache.fop.render.awt.AWTRenderer(translator)); * driver.render(parser, fileInputSource(args[0])); * </PRE> */ public class Driver implements LogEnabled { /** * Render to PDF. OutputStream must be set */ public static final int RENDER_PDF = 1; /** * Render to a GUI window. No OutputStream neccessary */ public static final int RENDER_AWT = 2; /** * Render to MIF. OutputStream must be set */ public static final int RENDER_MIF = 3; /** * Render to XML. OutputStream must be set */ public static final int RENDER_XML = 4; /** * Render to PRINT. No OutputStream neccessary */ public static final int RENDER_PRINT = 5; /** * Render to PCL. OutputStream must be set */ public static final int RENDER_PCL = 6; /** * Render to Postscript. OutputStream must be set */ public static final int RENDER_PS = 7; /** * Render to Text. OutputStream must be set */ public static final int RENDER_TXT = 8; /** * Render to SVG. OutputStream must be set */ public static final int RENDER_SVG = 9; /** * Render to RTF. OutputStream must be set */ public static final int RENDER_RTF = 10; /** * the FO tree builder */ private FOTreeBuilder treeBuilder; /** * the renderer type code given by setRenderer */ private int rendererType; /** * the renderer to use to output the area tree */ private Renderer renderer; /** * the SAX ContentHandler */ private FOInputHandler foInputHandler; /** * the source of the FO file */ private InputSource source; /** * the stream to use to output the results of the renderer */ private OutputStream stream; /** * The XML parser to use when building the FO tree */ private XMLReader reader; /** * the system resources that FOP will use */ private Logger log = null; private FOUserAgent userAgent = null; /** * Main constructor for the Driver class. */ public Driver() { stream = null; } /** * Convenience constructor for directly setting input and output. * @param source InputSource to take the XSL-FO input from * @param stream Target output stream */ public Driver(InputSource source, OutputStream stream) { this(); this.source = source; this.stream = stream; } private boolean isInitialized() { return (treeBuilder != null); } /** * Initializes the Driver object. */ public void initialize() { if (isInitialized()) { throw new IllegalStateException("Driver already initialized"); } treeBuilder = new FOTreeBuilder(); treeBuilder.setUserAgent(getUserAgent()); } /** * Optionally sets the FOUserAgent instance for FOP to use. The Driver * class sets up its own FOUserAgent if none is set through this method. * @param agent FOUserAgent to use */ public void setUserAgent(FOUserAgent agent) { userAgent = agent; } private FOUserAgent getUserAgent() { if (userAgent == null) { userAgent = new FOUserAgent(); userAgent.enableLogging(getLogger()); userAgent.setBaseURL(""); } return userAgent; } public void enableLogging(Logger log) { if (this.log == null) { this.log = log; } else { getLogger().warn("Logger is already set! Won't use the new logger."); } } /** * Provide the Driver instance with a logger. * @param log the logger. Must not be <code>null</code>. * @deprecated Use #enableLogging(Logger) instead. */ public void setLogger(Logger log) { enableLogging(log); } /** * Returns the logger for use by FOP. * @return the logger * @see #enableLogging(Logger) */ protected Logger getLogger() { if (this.log == null) { this.log = new ConsoleLogger(ConsoleLogger.LEVEL_INFO); this.log.error("Logger not set. Using ConsoleLogger as default."); } return this.log; } /** * Resets the Driver so it can be reused. Property and element * mappings are reset to defaults. * The output stream is cleared. The renderer is cleared. */ public synchronized void reset() { source = null; stream = null; reader = null; if (treeBuilder != null) { treeBuilder.reset(); } } /** * Indicates whether FOP has already received input data. * @return true, if input data was received */ public boolean hasData() { return (treeBuilder.hasData()); } /** * Set the OutputStream to use to output the result of the Renderer * (if applicable) * @param stream the stream to output the result of rendering to */ public void setOutputStream(OutputStream stream) { this.stream = stream; } private void validateOutputStream() { if (this.stream == null) { throw new IllegalStateException("OutputStream has not been set"); } } /** * Set the source for the FO document. This can be a normal SAX * InputSource, or an DocumentInputSource containing a DOM document. * @see DocumentInputSource */ public void setInputSource(InputSource source) { this.source = source; } /** * Sets the reader used when reading in the source. If not set, * this defaults to a basic SAX parser. * @param reader the reader to use. */ public void setXMLReader(XMLReader reader) { this.reader = reader; } public void setRenderer(int renderer) throws IllegalArgumentException { rendererType = renderer; switch (renderer) { case RENDER_PDF: setRenderer("org.apache.fop.render.pdf.PDFRenderer"); break; case RENDER_AWT: throw new IllegalArgumentException("Use renderer form of setRenderer() for AWT"); case RENDER_PRINT: setRenderer("org.apache.fop.render.awt.AWTPrintRenderer"); break; case RENDER_PCL: setRenderer("org.apache.fop.render.pcl.PCLRenderer"); break; case RENDER_PS: setRenderer("org.apache.fop.render.ps.PSRenderer"); break; case RENDER_TXT: setRenderer("org.apache.fop.render.txt.TXTRenderer()"); break; case RENDER_MIF: //foInputHandler will be set later break; case RENDER_XML: setRenderer("org.apache.fop.render.xml.XMLRenderer"); break; case RENDER_SVG: setRenderer("org.apache.fop.render.svg.SVGRenderer"); break; case RENDER_RTF: //foInputHandler will be set later break; default: throw new IllegalArgumentException("Unknown renderer type"); } } /** * Set the Renderer to use. * @param renderer the renderer instance to use (Note: Logger must be set at this point) */ public void setRenderer(Renderer renderer) { // AWTStarter calls this function directly if (renderer instanceof AWTRenderer) { rendererType = RENDER_AWT; } renderer.setProducer(Version.getVersion()); renderer.setUserAgent(getUserAgent()); this.renderer = renderer; } /** * Returns the currently active renderer. * @return the renderer */ public Renderer getRenderer() { return renderer; } /** * Sets the renderer. * @param rendererClassName the fully qualified classname of the renderer * class to use. * @param version version number * @deprecated use renderer.setProducer(version) + setRenderer(renderer) or * just setRenderer(rendererType) which will use the default producer string. * @see #setRenderer(int) * @see #setRenderer(Renderer) */ public void setRenderer(String rendererClassName, String version) { setRenderer(rendererClassName); } public void setRenderer(String rendererClassName) throws IllegalArgumentException { try { renderer = (Renderer)Class.forName(rendererClassName).newInstance(); if (renderer instanceof LogEnabled) { ((LogEnabled)renderer).enableLogging(getLogger()); } renderer.setProducer(Version.getVersion()); renderer.setUserAgent(getUserAgent()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + rendererClassName); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + rendererClassName); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + rendererClassName); } catch (ClassCastException e) { throw new IllegalArgumentException(rendererClassName + " is not a renderer"); } } /** * Add the given element mapping. * An element mapping maps element names to Java classes. * * @param mapping the element mappingto add */ public void addElementMapping(ElementMapping mapping) { treeBuilder.addElementMapping(mapping); } /** * Add the element mapping with the given class name. * @param mappingClassName the class name representing the element mapping. */ public void addElementMapping(String mappingClassName) { treeBuilder.addElementMapping(mappingClassName); } /** * Determines which SAX ContentHandler is appropriate for the rendererType. * Structure renderers (e.g. MIF & RTF) each have a specialized * ContentHandler that directly place data into the output stream. Layout * renderers (e.g. PDF & PostScript) use a ContentHandler that builds an FO * Tree. * @return a SAX ContentHandler for handling the SAX events. */ public ContentHandler getContentHandler() { if (!isInitialized()) { initialize(); } if (rendererType != RENDER_PRINT && rendererType != RENDER_AWT) { validateOutputStream(); } // TODO: - do this stuff in a better way if (rendererType == RENDER_MIF) { foInputHandler = new MIFHandler(stream); } else if (rendererType == RENDER_RTF) { foInputHandler = new RTFHandler(stream); } else { if (renderer == null) { throw new IllegalStateException( "Renderer not set when using standard foInputHandler"); } foInputHandler = new FOTreeHandler(stream, renderer, true); } foInputHandler.enableLogging(getLogger()); treeBuilder.setUserAgent(getUserAgent()); treeBuilder.setFOInputHandler(foInputHandler); return treeBuilder; } /** * Render the FO document read by a SAX Parser from an InputHandler * @param inputHandler the input handler containing the source and * parser information. * @throws FOPException if anything goes wrong. */ public synchronized void render(InputHandler inputHandler) throws FOPException { XMLReader parser = inputHandler.getParser(); render(parser, inputHandler.getInputSource()); } /** * Render the FO document read by a SAX Parser from an InputSource. * @param parser the SAX parser. * @param source the input source the parser reads from. * @throws FOPException if anything goes wrong. */ public synchronized void render(XMLReader parser, InputSource source) throws FOPException { if (!isInitialized()) { initialize(); } parser.setContentHandler(getContentHandler()); try { parser.parse(source); } catch (SAXException e) { if (e.getException() instanceof FOPException) { // Undo exception tunneling. throw (FOPException)e.getException(); } else { throw new FOPException(e); } } catch (IOException e) { throw new FOPException(e); } } /** * Render the FO ducument represented by a DOM Document. * @param document the DOM document to read from * @throws FOPException if anything goes wrong. */ public synchronized void render(Document document) throws FOPException { if (!isInitialized()) { initialize(); } try { DocumentInputSource source = new DocumentInputSource(document); DocumentReader reader = new DocumentReader(); reader.setContentHandler(getContentHandler()); reader.parse(source); } catch (SAXException e) { if (e.getException() instanceof FOPException) { // Undo exception tunneling. throw (FOPException)e.getException(); } else { throw new FOPException(e); } } catch (IOException e) { throw new FOPException(e); } } /** * Runs the formatting and renderering process using the previously set * parser, input source, renderer and output stream. * If the renderer was not set, default to PDF. * If no parser was set, and the input source is not a dom document, * get a default SAX parser. * @throws IOException in case of IO errors. * @throws FOPException if anything else goes wrong. */ public synchronized void run() throws IOException, FOPException { if (!isInitialized()) { initialize(); } if (renderer == null) { setRenderer(RENDER_PDF); } if (source == null) { throw new FOPException("InputSource is not set."); } if (reader == null) { if (!(source instanceof DocumentInputSource)) { //TODO: (gm) rename to FOFileHandler or similar reader = org.apache.fop.apps.FOInputHandler.createParser(); } } if (source instanceof DocumentInputSource) { render(((DocumentInputSource)source).getDocument()); } else { render(reader, source); } } }
package org.apache.fop.apps; // FOP import org.apache.fop.area.AreaTree; import org.apache.fop.area.RenderPagesModel; import org.apache.fop.fo.ElementMapping; import org.apache.fop.fo.FOTreeBuilder; import org.apache.fop.fo.FOInputHandler; import org.apache.fop.fo.FOTreeHandler; import org.apache.fop.mif.MIFHandler; import org.apache.fop.render.Renderer; import org.apache.fop.render.awt.AWTRenderer; import org.apache.fop.rtf.renderer.RTFHandler; import org.apache.fop.tools.DocumentInputSource; import org.apache.fop.tools.DocumentReader; import org.apache.fop.layoutmgr.LayoutManagerLS; // Avalon import org.apache.avalon.framework.logger.ConsoleLogger; import org.apache.avalon.framework.logger.LogEnabled; import org.apache.avalon.framework.logger.Logger; // DOM /* org.w3c.dom.Document is not imported to reduce confusion with org.apache.fop.control.Document */ // SAX import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; // Java import java.io.IOException; import java.io.OutputStream; /** * Primary class that drives overall FOP process. * <P> * The simplest way to use this is to instantiate it with the * InputSource and OutputStream, then set the renderer desired, and * calling run(); * <P> * Here is an example use of Driver which outputs PDF: * * <PRE> * Driver driver = new Driver(new InputSource (args[0]), * new FileOutputStream(args[1])); * driver.enableLogging(myLogger); //optional * driver.setRenderer(RENDER_PDF); * driver.run(); * </PRE> * If neccessary, calling classes can call into the lower level * methods to setup and * render. Methods can be called to set the * Renderer to use, the (possibly multiple) ElementMapping(s) to * use and the OutputStream to use to output the results of the * rendering (where applicable). In the case of the Renderer and * ElementMapping(s), the Driver may be supplied either with the * object itself, or the name of the class, in which case Driver will * instantiate the class itself. The advantage of the latter is it * enables runtime determination of Renderer and ElementMapping(s). * <P> * Once the Driver is set up, the render method * is called. Depending on whether DOM or SAX is being used, the * invocation of the method is either render(Document) or * buildFOTree(Parser, InputSource) respectively. * <P> * A third possibility may be used to build the FO Tree, namely * calling getContentHandler() and firing the SAX events yourself. * <P> * Once the FO Tree is built, the format() and render() methods may be * called in that order. * <P> * Here is an example use of Driver which outputs to AWT: * * <PRE> * Driver driver = new Driver(); * driver.enableLogging(myLogger); //optional * driver.setRenderer(new org.apache.fop.render.awt.AWTRenderer(translator)); * driver.render(parser, fileInputSource(args[0])); * </PRE> */ public class Driver implements LogEnabled { /** * private constant to indicate renderer was not defined. */ private static final int NOT_SET = 0; /** * Render to PDF. OutputStream must be set */ public static final int RENDER_PDF = 1; /** * Render to a GUI window. No OutputStream neccessary */ public static final int RENDER_AWT = 2; /** * Render to MIF. OutputStream must be set */ public static final int RENDER_MIF = 3; /** * Render to XML. OutputStream must be set */ public static final int RENDER_XML = 4; /** * Render to PRINT. No OutputStream neccessary */ public static final int RENDER_PRINT = 5; /** * Render to PCL. OutputStream must be set */ public static final int RENDER_PCL = 6; /** * Render to Postscript. OutputStream must be set */ public static final int RENDER_PS = 7; /** * Render to Text. OutputStream must be set */ public static final int RENDER_TXT = 8; /** * Render to SVG. OutputStream must be set */ public static final int RENDER_SVG = 9; /** * Render to RTF. OutputStream must be set */ public static final int RENDER_RTF = 10; /** * the FO tree builder */ private FOTreeBuilder treeBuilder; /** * the renderer type code given by setRenderer */ private int rendererType = NOT_SET; /** * the renderer to use to output the area tree */ private Renderer renderer; /** * the SAX ContentHandler */ private FOInputHandler foInputHandler; /** * the source of the FO file */ private InputSource source; /** * the stream to use to output the results of the renderer */ private OutputStream stream; /** * The XML parser to use when building the FO tree */ private XMLReader reader; /** * the system resources that FOP will use */ private Logger log = null; private FOUserAgent userAgent = null; private Document currentDocument = null; /** * Main constructor for the Driver class. */ public Driver() { stream = null; } /** * Convenience constructor for directly setting input and output. * @param source InputSource to take the XSL-FO input from * @param stream Target output stream */ public Driver(InputSource source, OutputStream stream) { this(); this.source = source; this.stream = stream; } private boolean isInitialized() { return (treeBuilder != null); } /** * Initializes the Driver object. */ public void initialize() { if (isInitialized()) { throw new IllegalStateException("Driver already initialized"); } treeBuilder = new FOTreeBuilder(); treeBuilder.setUserAgent(getUserAgent()); } /** * Optionally sets the FOUserAgent instance for FOP to use. The Driver * class sets up its own FOUserAgent if none is set through this method. * @param agent FOUserAgent to use */ public void setUserAgent(FOUserAgent agent) { userAgent = agent; } protected FOUserAgent getUserAgent() { if (userAgent == null) { userAgent = new FOUserAgent(); userAgent.enableLogging(getLogger()); userAgent.setBaseURL(""); } return userAgent; } public void enableLogging(Logger log) { if (this.log == null) { this.log = log; } else { getLogger().warn("Logger is already set! Won't use the new logger."); } } /** * Provide the Driver instance with a logger. * @param log the logger. Must not be <code>null</code>. * @deprecated Use #enableLogging(Logger) instead. */ public void setLogger(Logger log) { enableLogging(log); } /** * Returns the logger for use by FOP. * @return the logger * @see #enableLogging(Logger) */ public Logger getLogger() { if (this.log == null) { // use ConsoleLogger as default when logger not explicitly set this.log = new ConsoleLogger(ConsoleLogger.LEVEL_INFO); } return this.log; } /** * Resets the Driver so it can be reused. Property and element * mappings are reset to defaults. * The output stream is cleared. The renderer is cleared. */ public synchronized void reset() { source = null; stream = null; reader = null; if (treeBuilder != null) { treeBuilder.reset(); } } /** * Indicates whether FOP has already received input data. * @return true, if input data was received */ public boolean hasData() { return (treeBuilder.hasData()); } /** * Set the OutputStream to use to output the result of the Renderer * (if applicable) * @param stream the stream to output the result of rendering to */ public void setOutputStream(OutputStream stream) { this.stream = stream; } private void validateOutputStream() { if (this.stream == null) { throw new IllegalStateException("OutputStream has not been set"); } } /** * Set the source for the FO document. This can be a normal SAX * InputSource, or an DocumentInputSource containing a DOM document. * @see DocumentInputSource */ public void setInputSource(InputSource source) { this.source = source; } /** * Sets the reader used when reading in the source. If not set, * this defaults to a basic SAX parser. * @param reader the reader to use. */ public void setXMLReader(XMLReader reader) { this.reader = reader; } public void setRenderer(int renderer) throws IllegalArgumentException { rendererType = renderer; switch (renderer) { case RENDER_PDF: setRenderer("org.apache.fop.render.pdf.PDFRenderer"); break; case RENDER_AWT: throw new IllegalArgumentException("Use renderer form of setRenderer() for AWT"); case RENDER_PRINT: setRenderer("org.apache.fop.render.awt.AWTPrintRenderer"); break; case RENDER_PCL: setRenderer("org.apache.fop.render.pcl.PCLRenderer"); break; case RENDER_PS: setRenderer("org.apache.fop.render.ps.PSRenderer"); break; case RENDER_TXT: setRenderer("org.apache.fop.render.txt.TXTRenderer()"); break; case RENDER_MIF: //foInputHandler will be set later break; case RENDER_XML: setRenderer("org.apache.fop.render.xml.XMLRenderer"); break; case RENDER_SVG: setRenderer("org.apache.fop.render.svg.SVGRenderer"); break; case RENDER_RTF: //foInputHandler will be set later break; default: rendererType = NOT_SET; throw new IllegalArgumentException("Unknown renderer type " + renderer); } } /** * Set the Renderer to use. * @param renderer the renderer instance to use (Note: Logger must be set at this point) */ public void setRenderer(Renderer renderer) { // AWTStarter calls this function directly if (renderer instanceof AWTRenderer) { rendererType = RENDER_AWT; } renderer.setProducer(Version.getVersion()); renderer.setUserAgent(getUserAgent()); this.renderer = renderer; } /** * Returns the currently active renderer. * @return the renderer */ public Renderer getRenderer() { return renderer; } public void setRenderer(String rendererClassName) throws IllegalArgumentException { try { renderer = (Renderer)Class.forName(rendererClassName).newInstance(); if (renderer instanceof LogEnabled) { ((LogEnabled)renderer).enableLogging(getLogger()); } renderer.setProducer(Version.getVersion()); renderer.setUserAgent(getUserAgent()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + rendererClassName); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + rendererClassName); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + rendererClassName); } catch (ClassCastException e) { throw new IllegalArgumentException(rendererClassName + " is not a renderer"); } } /** * Add the given element mapping. * An element mapping maps element names to Java classes. * * @param mapping the element mappingto add */ public void addElementMapping(ElementMapping mapping) { treeBuilder.addElementMapping(mapping); } /** * Add the element mapping with the given class name. * @param mappingClassName the class name representing the element mapping. */ public void addElementMapping(String mappingClassName) { treeBuilder.addElementMapping(mappingClassName); } /** * Determines which SAX ContentHandler is appropriate for the rendererType. * Structure renderers (e.g. MIF & RTF) each have a specialized * ContentHandler that directly place data into the output stream. Layout * renderers (e.g. PDF & PostScript) use a ContentHandler that builds an FO * Tree. * @return a SAX ContentHandler for handling the SAX events. */ public ContentHandler getContentHandler() { if (!isInitialized()) { initialize(); } if (rendererType != RENDER_PRINT && rendererType != RENDER_AWT) { validateOutputStream(); } // TODO: - do this stuff in a better way if (rendererType == RENDER_MIF) { foInputHandler = new MIFHandler(currentDocument, stream); } else if (rendererType == RENDER_RTF) { foInputHandler = new RTFHandler(currentDocument, stream); } else { if (renderer == null) { throw new IllegalStateException( "Renderer not set when using standard foInputHandler"); } foInputHandler = new FOTreeHandler(currentDocument, true); } foInputHandler.enableLogging(getLogger()); treeBuilder.setUserAgent(getUserAgent()); treeBuilder.setFOInputHandler(foInputHandler); return treeBuilder; } /** * Render the FO document read by a SAX Parser from an InputHandler * @param inputHandler the input handler containing the source and * parser information. * @throws FOPException if anything goes wrong. */ public synchronized void render(InputHandler inputHandler) throws FOPException { XMLReader parser = inputHandler.getParser(); render(parser, inputHandler.getInputSource()); } /** * This is the main render() method. The other render() methods are for * convenience, and normalize to this form, then run this. * Renders the FO document read by a SAX Parser from an InputSource. * @param parser the SAX parser. * @param source the input source the parser reads from. * @throws FOPException if anything goes wrong. */ public synchronized void render(XMLReader parser, InputSource source) throws FOPException { if (!isInitialized()) { initialize(); } /** Document creation is hard-wired for now, but needs to be made accessible through the API and/or configuration */ if (currentDocument == null) { currentDocument = new Document(this); } parser.setContentHandler(getContentHandler()); currentDocument.foInputHandler = foInputHandler; /** LayoutStrategy is hard-wired for now, but needs to be made accessible through the API and/or configuration */ if (foInputHandler instanceof FOTreeHandler) { if (currentDocument.getLayoutStrategy() == null) { currentDocument.setLayoutStrategy(new LayoutManagerLS(currentDocument)); } } treeBuilder.foTreeControl = currentDocument; try { if (foInputHandler instanceof FOTreeHandler) { FOTreeHandler foTreeHandler = (FOTreeHandler)foInputHandler; foTreeHandler.addFOTreeListener(currentDocument); currentDocument.areaTree = new AreaTree(); currentDocument.atModel = new RenderPagesModel(renderer); //this.atModel = new CachedRenderPagesModel(renderer); currentDocument.areaTree.setTreeModel(currentDocument.atModel); try { renderer.setupFontInfo(currentDocument); // check that the "any,normal,400" font exists if (!currentDocument.isSetupValid()) { throw new SAXException(new FOPException( "No default font defined by OutputConverter")); } renderer.startRenderer(stream); } catch (IOException e) { throw new SAXException(e); } } /** The following statement triggers virtually all of the processing for this document. The SAX parser fires events that are handled by the appropriate InputHandler object, which means that you will need to look in those objects to see where FOP picks up control of processing again. For Structure Renderers (e.g. MIF & RTF), the SAX events are handled directly. For Layout Renderers (e.g. PDF & PostScript), an FO Tree is built by the FOTreeHandler, which in turn fires events when a PageSequence object is complete. This allows higher-level control objects (such as this class) to work directly with PageSequence objects. See foPageSequenceComplete() where this level of control is implemented. */ parser.parse(source); if (foInputHandler instanceof FOTreeHandler) { FOTreeHandler foTreeHandler = (FOTreeHandler)foInputHandler; foTreeHandler.removeFOTreeListener(currentDocument); } } catch (SAXException e) { if (e.getException() instanceof FOPException) { // Undo exception tunneling. throw (FOPException)e.getException(); } else { throw new FOPException(e); } } catch (IOException e) { throw new FOPException(e); } } /** * This method overloads the main render() method, adding the convenience * of using a DOM Document as input. * @see #render(XMLReader, InputSource) * @param document the DOM document to read from * @throws FOPException if anything goes wrong. */ public synchronized void render(org.w3c.dom.Document document) throws FOPException { DocumentInputSource source = new DocumentInputSource(document); DocumentReader reader = new DocumentReader(); render(reader, source); } /** * Runs the formatting and renderering process using the previously set * parser, input source, renderer and output stream. * If the renderer was not set, default to PDF. * If no parser was set, and the input source is not a dom document, * get a default SAX parser. * @throws IOException in case of IO errors. * @throws FOPException if anything else goes wrong. */ public synchronized void run() throws IOException, FOPException { if (!isInitialized()) { initialize(); } if (renderer == null && rendererType != RENDER_RTF && rendererType != RENDER_MIF) { setRenderer(RENDER_PDF); } if (source == null) { throw new FOPException("InputSource is not set."); } if (reader == null) { if (!(source instanceof DocumentInputSource)) { reader = FOFileHandler.createParser(); } } if (source instanceof DocumentInputSource) { render(((DocumentInputSource)source).getDocument()); } else { render(reader, source); } } }
package simdevice; /** * * @author andreaswassmer */ public class HumiditySensor extends Sensor implements Measuring, SensorType { public HumiditySensor() { super(); this.setRange(0.0, 100.0); name = "Humidity"; type = SensorType.HUMIDITY; } @Override public String measure() { double res = this.readValueAsDouble(); return String.format("%.2f", res); } }
package main; import grid.GridAndGoals; import grid.GridGraph; import grid.StartGoalPoints; import java.util.ArrayList; import javax.swing.JFrame; import main.analysis.MazeAnalysis; import main.mazes.MazeAndTestCases; import main.mazes.StoredTestMazes; import uiandio.CloseOnExitWindowListener; import uiandio.GraphImporter; import algorithms.datatypes.Point; import draw.EditorUI; import draw.VisualiserKeyboardControls; import draw.VisualiserMouseControls; public class GridGraphVisualiser { public static void run() { //loadExisting("sc1_EbonLakes"); //loadExisting("sc1_GreenerPastures"); loadDefault("default"); //loadMaze("custommaze2.txt", "custom"); //loadMaze("lineOfSightTest.txt", "custom"); //loadExisting("sc2_blisteringsands"); //loadExisting("sc2_losttemple"); //loadExisting("baldursgate_AR0402SR"); //loadExisting("corr2_maze512-2-5"); } public static void loadMaze(String mazeFileName, String classification) { GridGraph gridGraph = GraphImporter.importGraphFromFile(mazeFileName); int dot = mazeFileName.lastIndexOf('.'); String mazeName = classification + "_" + mazeFileName.substring(0, dot); setupMainFrame(gridGraph, mazeName, null); } public static void loadExisting(String mazeName) { GridGraph gridGraph = GraphImporter.loadStoredMaze(mazeName); setupMainFrame(gridGraph, mazeName, null); } private static void loadStored(MazeAndTestCases mazeAndTestCases) { GridGraph gridGraph = mazeAndTestCases.gridGraph; String mazeName = mazeAndTestCases.mazeName; setupMainFrame(gridGraph, mazeName, null); } public static void loadDefault(String mazeName) { GridAndGoals gridAndGoals = AnyAnglePathfinding.loadMaze(); GridGraph gridGraph = gridAndGoals.gridGraph; StartGoalPoints startGoalPoints = gridAndGoals.startGoalPoints; setupMainFrame(gridGraph, mazeName, startGoalPoints); } /** * Spawns the editor visualisation window. * @param startGoalPoints */ private static void setupMainFrame(GridGraph gridGraph, String mazeName, StartGoalPoints startGoalPoints) { AlgoFunction algoFunction = AnyAnglePathfinding.setDefaultAlgoFunction(); ArrayList<ArrayList<Point>> connectedSets = MazeAnalysis.findConnectedSetsFast(gridGraph); EditorUI editorUI = new EditorUI(gridGraph, algoFunction, connectedSets, mazeName, startGoalPoints); VisualiserMouseControls mouseControls = new VisualiserMouseControls(gridGraph, editorUI); VisualiserKeyboardControls keyboardControls = new VisualiserKeyboardControls(editorUI); JFrame mainFrame = new JFrame(); mainFrame.setTitle(mazeName); mainFrame.add(editorUI); mainFrame.addWindowListener(new CloseOnExitWindowListener()); mainFrame.getContentPane().addMouseListener(mouseControls); mainFrame.getContentPane().addMouseMotionListener(mouseControls); mainFrame.addKeyListener(keyboardControls); mainFrame.setResizable(false); mainFrame.pack(); mainFrame.setLocationRelativeTo(null); mainFrame.setVisible(true); } }
package R.helper; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; public class BaseFragment extends Fragment { public BaseFragment() { super(); } public <T extends BaseActivity> T getActivityRef(Class<T> cls) { Activity act = this.getActivity(); if (act != null && (act instanceof BaseActivity)) { return (T)act; } return null; } public static <T extends BaseFragment> T newInstance(Class<T> clazz) { return BaseFragment.newInstance(clazz, null); } public static <T extends BaseFragment> T newInstance(Class<T> clazz, @Nullable Bundle b) { try { T s = (T) clazz.newInstance(); s.setArguments(b == null?new Bundle():b); return s; }catch (Exception E) { return null; } } public void onResumeFromBackStack() {} }
package abra; import joptsimple.OptionParser; /** * Manages ABRA command line options * * @author Lisle E. Mose (lmose at unc dot edu) */ public class ReAlignerOptions extends Options { private static final String INPUT_SAM = "in"; private static final String OUTPUT_SAM = "out"; private static final String REFERENCE = "ref"; private static final String TARGET_REGIONS = "targets"; private static final String TARGET_REGIONS_WITH_KMERS = "target-kmers"; private static final String KMER_SIZE = "kmer"; private static final String MIN_NODE_FREQUENCY = "mnf"; private static final String MIN_CONTIG_LENGTH = "mcl"; private static final String MIN_MAPQ = "mapq"; private static final String NUM_THREADS = "threads"; private static final String SINGLE_END = "single"; private static final String MIN_BASE_QUALITY = "mbq"; private static final String MIN_READ_CANDIDATE_FRACTION = "rcf"; private static final String MAX_AVERAGE_REGION_DEPTH = "mad"; private static final String MIN_EDGE_RATIO = "mer"; private static final String MAX_NODES = "maxn"; private static final String SKIP_ASSEMBLY = "sa"; private static final String SKIP_SOFT_CLIP = "ssc"; private static final String SOFT_CLIP = "sc"; private static final String SKIP_OBS_INDELS = "sobs"; private static final String JUNCTIONS = "junctions"; private static final String LOG_LEVEL = "log"; private static final String CONTIG_FILE = "contigs"; private static final String GTF_JUNCTIONS = "gtf"; private static final String SG_ALIGNER_SCORING = "sga"; private static final String MAX_CACHED_READS = "mcr"; private static final String KEEP_TMP = "keep-tmp"; private static final String TMP_DIR = "tmpdir"; private static final String CONSENSUS_SEQ = "cons"; private static final String MAX_MISMATCH_RATE = "mmr"; private static final String WINDOW_SIZE = "ws"; private static final String MAX_READS_IN_REGION = "mrr"; private static final String COMPRESSION_LEVEL = "cl"; private static final String CONTIG_ANCHOR = "ca"; private OptionParser parser; private boolean isValid; @Override protected OptionParser getOptionParser() { if (parser == null) { parser = new OptionParser(); parser.accepts(INPUT_SAM, "Required list of input sam or bam file(s) separated by comma").withRequiredArg().ofType(String.class); parser.accepts(OUTPUT_SAM, "Required list of output sam or bam file(s) separated by comma").withRequiredArg().ofType(String.class); parser.accepts(REFERENCE, "Genome reference location").withRequiredArg().ofType(String.class); parser.accepts(TARGET_REGIONS, "BED file containing target regions").withRequiredArg().ofType(String.class); parser.accepts(TARGET_REGIONS_WITH_KMERS, "BED-like file containing target regions with per region kmer sizes in 4th column").withRequiredArg().ofType(String.class); parser.accepts(KMER_SIZE, "Optional assembly kmer size(delimit with commas if multiple sizes specified)").withOptionalArg().ofType(String.class); parser.accepts(MIN_NODE_FREQUENCY, "Assembly minimum node frequency").withRequiredArg().ofType(Integer.class).defaultsTo(2); parser.accepts(MIN_CONTIG_LENGTH, "Assembly minimum contig length").withOptionalArg().ofType(Integer.class).defaultsTo(-1); parser.accepts(NUM_THREADS, "Number of threads").withRequiredArg().ofType(Integer.class).defaultsTo(4); parser.accepts(MIN_MAPQ, "Minimum mapping quality for a read to be used in assembly and be eligible for realignment").withOptionalArg().ofType(Integer.class).defaultsTo(20); parser.accepts(SINGLE_END, "Input is single end"); parser.accepts(MIN_BASE_QUALITY, "Minimum base quality for inclusion in assembly. This value is compared against the sum of base qualities per kmer position").withOptionalArg().ofType(Integer.class).defaultsTo(60); parser.accepts(MIN_READ_CANDIDATE_FRACTION, "Minimum read candidate fraction for triggering assembly").withRequiredArg().ofType(Double.class).defaultsTo(.01); parser.accepts(MAX_AVERAGE_REGION_DEPTH, "Regions with average depth exceeding this value will be downsampled").withRequiredArg().ofType(Integer.class).defaultsTo(250); parser.accepts(MIN_EDGE_RATIO, "Min edge pruning ratio. Default value is appropriate for relatively sensitive somatic cases. May be increased for improved speed in germline only cases.").withRequiredArg().ofType(Double.class).defaultsTo(.02); parser.accepts(MAX_NODES, "Maximum pre-pruned nodes in regional assembly").withOptionalArg().ofType(Integer.class).defaultsTo(9000); parser.accepts(SKIP_ASSEMBLY, "Skip assembly"); parser.accepts(JUNCTIONS, "Splice junctions definition file").withRequiredArg().ofType(String.class); parser.accepts(LOG_LEVEL, "Logging level (trace,debug,info,warn,error)").withRequiredArg().ofType(String.class).defaultsTo("info"); parser.accepts(CONTIG_FILE, "Optional file to which assembled contigs are written").withRequiredArg().ofType(String.class); parser.accepts(GTF_JUNCTIONS, "GTF file defining exons and transcripts").withRequiredArg().ofType(String.class); parser.accepts(SKIP_SOFT_CLIP, "Skip usage of soft clipped sequences as putative contigs"); parser.accepts(SOFT_CLIP, "Soft clip contig args [max_contigs,min_base_qual,frac_high_qual_bases,min_soft_clip_len]").withRequiredArg().ofType(String.class).defaultsTo("32,13,80,8"); parser.accepts(SG_ALIGNER_SCORING, "Scoring used for contig alignments (match, mismatch_penalty, gap_open_penalty, gap_extend_penalty)").withRequiredArg().ofType(String.class).defaultsTo("8,32,48,1"); parser.accepts(MAX_CACHED_READS, "Max number of cached reads per sample per thread").withRequiredArg().ofType(Integer.class).defaultsTo(500000); parser.accepts(SKIP_OBS_INDELS, "Do not use observed indels in original alignments to generate contigs"); parser.accepts(KEEP_TMP, "Do not delete the temporary directory"); parser.accepts(TMP_DIR, "Set the temp directory (overrides java.io.tmpdir)").withRequiredArg().ofType(String.class); parser.accepts(CONSENSUS_SEQ, "Use positional consensus sequence when aligning high quality soft clipping"); parser.accepts(MAX_MISMATCH_RATE, "Max allowed mismatch rate when mapping reads back to contigs").withRequiredArg().ofType(Double.class).defaultsTo(.05); parser.accepts(WINDOW_SIZE, "Processing window size and overlap (size,overlap)").withRequiredArg().ofType(String.class).defaultsTo("400,200"); parser.accepts(MAX_READS_IN_REGION, "Regions containing more reads than this value are not processed. Use -1 to disable.").withRequiredArg().ofType(Integer.class).defaultsTo(10000); parser.accepts(COMPRESSION_LEVEL, "Compression level of output bam file(s)").withRequiredArg().ofType(Integer.class).defaultsTo(5); parser.accepts(CONTIG_ANCHOR, "Contig anchor [M_bases_at_contig_edge, max_mismatches_at_edge").withRequiredArg().ofType(String.class).defaultsTo("10,2"); } return parser; } @Override protected void validate() { isValid = true; if (!getOptions().hasArgument(INPUT_SAM)) { isValid = false; System.err.println("Missing required input SAM/BAM file"); } if (!getOptions().hasArgument(OUTPUT_SAM)) { isValid = false; System.err.println("Missing required input SAM/BAM file"); } if (getInputFiles().length != getOutputFiles().length) { System.err.println("Number of input files must equal number of output files"); } if (!getOptions().hasArgument(REFERENCE)) { isValid = false; System.err.println("Missing required reference"); } if (getOptions().hasArgument(TARGET_REGIONS) && getOptions().hasArgument(TARGET_REGIONS_WITH_KMERS)) { isValid = false; System.err.println("Please specifiy only one of: " + TARGET_REGIONS + ", " + TARGET_REGIONS_WITH_KMERS); } if ((getOptions().hasArgument(NUM_THREADS) && (Integer) getOptions().valueOf(NUM_THREADS) < 1)) { isValid = false; System.err.println("Num threads must be greater than zero."); } if (!isValid) { printHelp(); } } public String[] getInputFiles() { String[] files = new String[0]; String sams = (String) getOptions().valueOf(INPUT_SAM); if (sams != null) { files = sams.split(","); } return files; } public String[] getOutputFiles() { String[] files = new String[0]; String sams = (String) getOptions().valueOf(OUTPUT_SAM); if (sams != null) { files = sams.split(","); } return files; } public String getReference() { return (String) getOptions().valueOf(REFERENCE); } public String getTargetRegionFile() { String file = null; if (getOptions().hasArgument(TARGET_REGIONS_WITH_KMERS)) { file = (String) getOptions().valueOf(TARGET_REGIONS_WITH_KMERS); } else { file = (String) getOptions().valueOf(TARGET_REGIONS); } return file; } public String getJunctionFile() { String file = null; if (getOptions().hasArgument(JUNCTIONS)) { file = (String) getOptions().valueOf(JUNCTIONS); } return file; } public String getGtfJunctionFile() { String file = null; if (getOptions().hasArgument(GTF_JUNCTIONS)) { file = (String) getOptions().valueOf(GTF_JUNCTIONS); } return file; } public boolean hasPresetKmers() { return getOptions().hasArgument(TARGET_REGIONS_WITH_KMERS); } public int[] getKmerSizes() { int[] kmers; if (getOptions().has(KMER_SIZE)) { String[] kmerStr = ((String) getOptions().valueOf(KMER_SIZE)).split(","); kmers = new int[kmerStr.length]; for (int i=0; i<kmerStr.length; i++) { kmers[i] = Integer.parseInt(kmerStr[i]); } } else { kmers = new int[0]; } return kmers; } public int getMinNodeFrequency() { return (Integer) getOptions().valueOf(MIN_NODE_FREQUENCY); } public int getMinContigLength() { return (Integer) getOptions().valueOf(MIN_CONTIG_LENGTH); } public int getNumThreads() { return getOptions().hasArgument(NUM_THREADS) ? (Integer) getOptions().valueOf(NUM_THREADS) : 4; } public int getMaxReadsInRegion() { return (Integer) getOptions().valueOf(MAX_READS_IN_REGION); } public double getMaxMismatchRate() { return (Double) getOptions().valueOf(MAX_MISMATCH_RATE); } public boolean isPairedEnd() { return !getOptions().has(SINGLE_END); } public boolean isSkipAssembly() { return getOptions().has(SKIP_ASSEMBLY); } public boolean isKeepTmp() { return getOptions().has(KEEP_TMP); } public String getTmpDir() { return getOptions().has(TMP_DIR) ? (String) getOptions().valueOf(TMP_DIR) : null; } public boolean useObservedIndels() { return !getOptions().has(SKIP_OBS_INDELS); } public boolean useSoftClippedReads() { return !getOptions().has(SKIP_SOFT_CLIP); } public boolean useConsensusSequence() { return getOptions().has(CONSENSUS_SEQ); } public int getMinBaseQuality() { return (Integer) getOptions().valueOf(MIN_BASE_QUALITY); } public double getMinReadCandidateFraction() { return (Double) getOptions().valueOf(MIN_READ_CANDIDATE_FRACTION); } public double getMinEdgeRatio() { return (Double) getOptions().valueOf(MIN_EDGE_RATIO); } public int getMaxAverageRegionDepth() { return (Integer) getOptions().valueOf(MAX_AVERAGE_REGION_DEPTH); } public int getMinimumMappingQuality() { return (Integer) getOptions().valueOf(MIN_MAPQ); } public int[] getSmithWatermanScoring() { String scoring = (String) getOptions().valueOf(SG_ALIGNER_SCORING); String[] fields = scoring.split(","); if (fields.length != 4) { Logger.error("4 values required for sga scoring"); throw new IllegalArgumentException("4 values required for sga scoring"); } int[] scores = new int[4]; for (int i=0; i<4; i++) { scores[i] = Integer.parseInt(fields[i].trim()); } return scores; } public int getWindowSize() { String win = (String) getOptions().valueOf(WINDOW_SIZE); String[] fields = win.split(","); if (fields.length != 2) { Logger.error("Please specify window size and overlap"); throw new IllegalArgumentException("Window size and overlap must be specified"); } return Integer.parseInt(fields[0].trim()); } public int getWindowOverlap() { String win = (String) getOptions().valueOf(WINDOW_SIZE); String[] fields = win.split(","); if (fields.length != 2) { Logger.error("Please specify window size and overlap"); throw new IllegalArgumentException("Window size and overlap must be specified"); } return Integer.parseInt(fields[1].trim()); } public int[] getContigAnchor() { String params = (String) getOptions().valueOf(CONTIG_ANCHOR); String[] fields = params.split(","); if (fields.length != 2) { Logger.error("2 values required for contig anchor"); } int[] values = new int[2]; for (int i=0; i<2; i++) { values[i] = Integer.parseInt(fields[i].trim()); } return values; } public int[] getSoftClipParams() { String params = (String) getOptions().valueOf(SOFT_CLIP); String[] fields = params.split(","); if (fields.length != 4) { Logger.error("4 values required for SW soft clip params"); } int[] values = new int[4]; for (int i=0; i<4; i++) { values[i] = Integer.parseInt(fields[i].trim()); } return values; } public String getLoggerLevel() { return (String) getOptions().valueOf(LOG_LEVEL); } public String getContigFile() { return (String) getOptions().valueOf(CONTIG_FILE); } public boolean isValid() { return isValid; } public int getMaxNodes() { return (Integer) getOptions().valueOf(MAX_NODES); } public int getMaxCachedReads() { return (Integer) getOptions().valueOf(MAX_CACHED_READS); } public int getCompressionLevel() { return (Integer) getOptions().valueOf(COMPRESSION_LEVEL); } }
package main.java.binBeats.ui; import java.awt.EventQueue; import java.awt.Toolkit; import java.awt.Color; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JTabbedPane; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListSelectionModel; import javax.swing.JButton; import javax.swing.JFormattedTextField; import javax.sound.sampled.LineUnavailableException; import javax.swing.Action; import javax.swing.Box; import javax.swing.JSlider; import javax.swing.SwingConstants; import javax.swing.ToolTipManager; import javax.swing.UIManager; import javax.swing.border.TitledBorder; import javax.swing.JScrollPane; import javax.swing.JComboBox; import net.miginfocom.swing.MigLayout; import main.java.binBeats.lib.BinBeat; import main.java.binBeats.lib.BinBeatValidator; import main.java.binBeats.lib.BinBeatsPlayer; import javax.swing.event.ChangeListener; import javax.swing.text.NumberFormatter; import javax.swing.event.ChangeEvent; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.text.NumberFormat; import java.util.Locale; import java.awt.event.ActionListener; import javax.swing.ImageIcon; /** * Displays the UI for BinBeat Player only * @author Magnus * */ public class BbUIBasic { private JFrame frmBinbeats; private NumberFormat numberFormatEn; private NumberFormatter numberFormatterEn; private BinBeat playerBinBeat; private BinBeatsPlayer binBeatsPlayer; private BinBeatValidator binBeatValidator; private boolean isPlaying = false; /** * Launch the application. */ public static void main(String[] args) { // Set System look and feel, hide from windowbuilder parser // hide>>$ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Error setting native system look and feel " + e); } // $hide<< EventQueue.invokeLater(new Runnable() { public void run() { try { BbUIBasic window = new BbUIBasic(); window.frmBinbeats.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public BbUIBasic() { initialize(); } /** * Initialize the contents of the frame and add functionality. */ private void initialize() { try { binBeatsPlayer = new BinBeatsPlayer(); } catch (LineUnavailableException e1) { // TODO: Popup e1.printStackTrace(); } binBeatValidator = new BinBeatValidator(); // TODO: Demo BinBeat playerBinBeat = new BinBeat(432, 7); /* Format numbers in text fields to display a dot as decimal separator * and to not use grouping separators for multiples of 1000. * e.g. instead of 1.333,37 display 1333.37 */ numberFormatEn = NumberFormat.getNumberInstance(Locale.ENGLISH); numberFormatEn.setGroupingUsed(false); numberFormatterEn = new NumberFormatter(numberFormatEn); // Make tooltips stay open indefinitely ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE); frmBinbeats = new JFrame(); frmBinbeats.setTitle("BinBeats"); frmBinbeats.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panelPlayer = new JPanel(); panelPlayer.setLayout(new MigLayout("", "[][][grow][grow][]", "[][][][][][][]")); frmBinbeats.getContentPane().add(panelPlayer, BorderLayout.CENTER); JLabel lblPlayerPreset = new JLabel("Preset"); panelPlayer.add(lblPlayerPreset, "cell 1 0,alignx trailing"); String[] mockupPlayerAtmosphereSelection = {"<new>", "Reasoning - Beta", "Relaxation - Alpha", "Meditation - Theta", "Deep Sleep - Delta"}; JComboBox comboBoxPlayerPresetSelection = new JComboBox(mockupPlayerAtmosphereSelection); comboBoxPlayerPresetSelection.setEditable(true); comboBoxPlayerPresetSelection.setToolTipText("Select binaural beat from preset or create a new one"); panelPlayer.add(comboBoxPlayerPresetSelection, "flowx,cell 2 0,growx"); JButton btnPlayerSave = new JButton(); btnPlayerSave.setIcon(new ImageIcon(BbUIBasic.class.getResource("/main/java/binBeats/ui/save.png"))); btnPlayerSave.setToolTipText("Save preset"); panelPlayer.add(btnPlayerSave, "flowx,cell 3 0"); JButton btnPlayerDelete = new JButton(); btnPlayerDelete.setToolTipText("Delete currently selected preset"); btnPlayerDelete.setIcon(new ImageIcon(BbUIBasic.class.getResource("/main/java/binBeats/ui/garbage.png"))); panelPlayer.add(btnPlayerDelete, "cell 3 0"); JButton btnPlayerPlay = new JButton(); btnPlayerPlay.setIcon(new ImageIcon(BbUIBasic.class.getResource("/main/java/binBeats/ui/play.png"))); btnPlayerPlay.setToolTipText("Play binaural beat as configured below"); panelPlayer.add(btnPlayerPlay, "cell 3 0"); JLabel lblPlayerCarrierFrequency = new JLabel("Carrier Frequency"); panelPlayer.add(lblPlayerCarrierFrequency, "cell 1 1,alignx trailing"); JFormattedTextField formattedTextFieldPlayerCarrier = new JFormattedTextField(numberFormatterEn); formattedTextFieldPlayerCarrier.setHorizontalAlignment(SwingConstants.RIGHT); formattedTextFieldPlayerCarrier.setValue(playerBinBeat.getCarrierFrequency()); formattedTextFieldPlayerCarrier.setToolTipText("Define the pitch of the carrier tone"); JSlider sliderPlayerCarrier = new JSlider(); sliderPlayerCarrier.setToolTipText("Define the pitch of the carrier tone"); formattedTextFieldPlayerCarrier.setColumns(6); panelPlayer.add(formattedTextFieldPlayerCarrier, "flowx,cell 2 1,alignx left"); sliderPlayerCarrier.setMinimum(20); sliderPlayerCarrier.setMaximum(1500); sliderPlayerCarrier.setMinorTickSpacing(1); sliderPlayerCarrier.setMajorTickSpacing(10); sliderPlayerCarrier.setValue((int)this.playerBinBeat.getCarrierFrequency()); panelPlayer.add(sliderPlayerCarrier, "cell 1 2 3 1,growx"); JLabel lblPlayerCarrierHz = new JLabel("Hz"); panelPlayer.add(lblPlayerCarrierHz, "cell 2 1"); JLabel labelPlayerCarrier_20 = new JLabel("20"); panelPlayer.add(labelPlayerCarrier_20, "cell 0 2,alignx right"); JLabel labelPlayerCarrier_1500 = new JLabel("1500"); panelPlayer.add(labelPlayerCarrier_1500, "cell 4 2,alignx left"); JLabel lblPlayerBeatFrequency = new JLabel("Beat Frequency"); panelPlayer.add(lblPlayerBeatFrequency, "cell 1 3,alignx trailing"); JFormattedTextField formattedTextFieldPlayerBeatFreq = new JFormattedTextField(numberFormatterEn); formattedTextFieldPlayerBeatFreq.setHorizontalAlignment(SwingConstants.RIGHT); formattedTextFieldPlayerBeatFreq.setValue(playerBinBeat.getBeatFrequency()); String beatFreqTooltip = "<html>Define the frequency of the binaural beat" + "<ul>" + "<li><strong>0.5 - 4</strong> - <em>Delta</em> - deep sleep, trance</li>" + "<li><strong>4 - 6.5</strong> - <em>Low Theta</em> - falling asleep</li>" + "<li><strong>6.5 - 8</strong> - <em>High Theta</em> - deep relaxation, meditation</li>" + "<li><strong>8 - 13</strong> - <em>Alpha</em> - light relaxation, super learning</li>" + "<li><strong>13 - 15</strong> - <em>Low Beta</em> - awareness</li>" + "<li><strong>15 - 21</strong> - <em>Medium Beta</em> - concentration</li>" + "<li><strong>21 - 30</strong> - <em>High Beta</em> - stress</li>" + "</ul></html>"; formattedTextFieldPlayerBeatFreq.setToolTipText(beatFreqTooltip); formattedTextFieldPlayerBeatFreq.setColumns(6); panelPlayer.add(formattedTextFieldPlayerBeatFreq, "flowx,cell 2 3,alignx left"); JLabel lblPlayerBeatFreqHz = new JLabel("Hz"); panelPlayer.add(lblPlayerBeatFreqHz, "cell 2 3"); JLabel labelPlayerBeatFreq_05 = new JLabel("0.5"); panelPlayer.add(labelPlayerBeatFreq_05, "cell 0 4,alignx right"); JSlider sliderPlayerBeatFreq = new JSlider(); sliderPlayerBeatFreq.setToolTipText(beatFreqTooltip); panelPlayer.add(sliderPlayerBeatFreq, "cell 1 4 3 1,growx"); JLabel labelPlayerBeatFreq_30 = new JLabel("30"); panelPlayer.add(labelPlayerBeatFreq_30, "cell 4 4,alignx left"); sliderPlayerBeatFreq.setMajorTickSpacing(10); sliderPlayerBeatFreq.setMinorTickSpacing(1); sliderPlayerBeatFreq.setMaximum(300); sliderPlayerBeatFreq.setMinimum(5); sliderPlayerBeatFreq.setValue((int)this.playerBinBeat.getBeatFrequency()*10); JLabel lblPlayerBeatVolume = new JLabel("Beat Volume"); panelPlayer.add(lblPlayerBeatVolume, "cell 1 5,alignx trailing"); JFormattedTextField formattedTextFieldPlayerBeatVol = new JFormattedTextField(numberFormatterEn); formattedTextFieldPlayerBeatVol.setHorizontalAlignment(SwingConstants.RIGHT); formattedTextFieldPlayerBeatVol.setValue(playerBinBeat.getVolume()); panelPlayer.add(formattedTextFieldPlayerBeatVol, "flowx,cell 2 5"); formattedTextFieldPlayerBeatVol.setToolTipText("Define binaural beat volume"); formattedTextFieldPlayerBeatVol.setColumns(6); JLabel labelPlayerBeatVolume_0 = new JLabel("0"); panelPlayer.add(labelPlayerBeatVolume_0, "cell 0 6,alignx right"); JSlider sliderPlayerBeatVol = new JSlider(); panelPlayer.add(sliderPlayerBeatVol, "cell 1 6 3 1,growx"); sliderPlayerBeatVol.setToolTipText("Define binaural beat volume"); sliderPlayerBeatVol.setMajorTickSpacing(10); sliderPlayerBeatVol.setMinorTickSpacing(1); sliderPlayerBeatVol.setMinimum(0); sliderPlayerBeatVol.setMaximum(100); // TODO: maybe change playerBinBeat.getVolume() to int in BinBeat Class sliderPlayerBeatVol.setValue(Math.round(playerBinBeat.getVolume())); JLabel labelPlayerBeatVolPercent = new JLabel("%"); panelPlayer.add(labelPlayerBeatVolPercent, "cell 2 5"); JLabel labelPlayerBeatVolume_100 = new JLabel("100"); panelPlayer.add(labelPlayerBeatVolume_100, "cell 4 6,alignx left"); // after all elements are initialized // Play button actions btnPlayerPlay.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(!isPlaying) { // collect data from UI in playerBinBeat // cannot use the fields' value() function because moving a slider will fill the field with int playerBinBeat.setCarrierFrequency(Float.parseFloat(formattedTextFieldPlayerCarrier.getText())); playerBinBeat.setBeatFrequency(Float.parseFloat(formattedTextFieldPlayerBeatFreq.getText())); playerBinBeat.setVolume(Float.parseFloat(formattedTextFieldPlayerBeatVol.getText())); binBeatsPlayer.setBinBeat(playerBinBeat); try { btnPlayerPlay.setIcon(new ImageIcon(BbUIBasic.class.getResource("/main/java/binBeats/ui/stop.png"))); btnPlayerPlay.setToolTipText("Stop playback"); binBeatsPlayer.play(); isPlaying = true; } catch (LineUnavailableException e1) { // TODO: Popup e1.printStackTrace(); } } else { // if Beat is already playing btnPlayerPlay.setIcon(new ImageIcon(BbUIBasic.class.getResource("/main/java/binBeats/ui/play.png"))); btnPlayerPlay.setToolTipText("Play binaural beat as configured below"); binBeatsPlayer.stop(); isPlaying = false; } } }); // Delete button btnPlayerDelete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Remove currently selected item comboBoxPlayerPresetSelection.removeItemAt(comboBoxPlayerPresetSelection.getSelectedIndex()); } }); // Save button btnPlayerSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // TODO: Actually save a BinBeat with persistence class comboBoxPlayerPresetSelection.addItem((String)comboBoxPlayerPresetSelection.getSelectedItem()); } }); // Link carrier slider and text field formattedTextFieldPlayerCarrier.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { float value = checkValidity(formattedTextFieldPlayerCarrier.getText(), "\\d+(\\.\\d*)?", 7, binBeatValidator.getCarrierFrequencyMin(), binBeatValidator.getCarrierFrequencyMax()); if (value > -1) { sliderPlayerCarrier.setValue(Math.round(value)); formattedTextFieldPlayerCarrier.setValue(value); } else { // TODO: Popup } } }); sliderPlayerCarrier.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent arg0) { formattedTextFieldPlayerCarrier.setValue(sliderPlayerCarrier.getValue()); } }); /* Link beat frequency slider and text field * Note: JSlider works with integers. * As we want to be able to change values by .1 we multiply by 10. */ formattedTextFieldPlayerBeatFreq.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { float value = checkValidity(formattedTextFieldPlayerBeatFreq.getText(), "\\d+(\\.\\d*)?", 5, binBeatValidator.getBeatFrequencyMin(), binBeatValidator.getBeatFrequencyMax()); if (value > -1){ sliderPlayerBeatFreq.setValue((int)(value*10)); formattedTextFieldPlayerBeatFreq.setValue(value); } else { // TODO: Popup } } }); sliderPlayerBeatFreq.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent arg0) { formattedTextFieldPlayerBeatFreq.setValue((float)sliderPlayerBeatFreq.getValue()/10); } }); // Link beat volume field with slider formattedTextFieldPlayerBeatVol.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { // don't allow decimal fractions for volume percentage // float value = checkValidity(formattedTextFieldPlayerBeatVol.getText(), "\\d+", 3, binBeatValidator.getVolumeMin(), binBeatValidator.getVolumeMax()); // allow decimal fractions for volume percentage float value = checkValidity(formattedTextFieldPlayerBeatVol.getText(), "\\d+(\\.\\d*)?", 5, binBeatValidator.getVolumeMin(), binBeatValidator.getVolumeMax()); if (value > -1) { sliderPlayerBeatVol.setValue(Math.round(value)); formattedTextFieldPlayerBeatVol.setValue(value); } } }); sliderPlayerBeatVol.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { formattedTextFieldPlayerBeatVol.setValue(sliderPlayerBeatVol.getValue()); } }); // After every element is added, pack window to content size and center on screen frmBinbeats.pack(); frmBinbeats.setLocationRelativeTo(null); } /** * Checks the value of a text field against a regular expression and upper and lower bounds. * Corrects the value to its upper or lower bound if necessary. * * @param typedValue the String to be checked and converted into a number * @param regex the regular expression to check if typedValue is a valid number * @param maxLength maximum length for the number to be valid * @param lowerBound lower bound to be checked against * @param upperBound upper bound to be checked against * @return the checked and corrected value or -1 if not a valid number */ private float checkValidity(String typedValue, String regex, int maxLength, float lowerBound, float upperBound){ float value = -1; // Check if typed value is a valid number if (!typedValue.matches(regex)) { System.out.println(typedValue + " is not a valid number."); return value; } try { value = Float.parseFloat(typedValue); } catch (NumberFormatException e){ System.out.println(typedValue + " is not a parsable float."); return value; } // Check for correct specifications and change if necessary if (value < lowerBound) { value = lowerBound; } else if (value > upperBound) { value = upperBound; } return value; } }
package com.adam58.model; public class User { private final String username; public User(String username) { this.username = username; } public String getUsername() { return username; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return username != null ? username.equals(user.username) : user.username == null; } @Override public int hashCode() { return username != null ? username.hashCode() : 0; } }
package com.mycompany.app; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); build(); } public static void build( ) { System.out.println( "building!" ); } }
package com.physalix.jfx; import java.util.Date; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.util.Callback; /** * Main class. * * @author Fabrice Sommavilla <fs@physalix.com> */ public class Main extends Application { private static final String STYLESHEET_PATH = "/styles/styles.css"; @Override public void start(Stage stage) { Scene scene = new Scene(new Group()); scene.getStylesheets().add(STYLESHEET_PATH); stage.setTitle("DatePicker TableCell Sample"); stage.setWidth(315); stage.setHeight(450); final ObservableList<BirthdayEvent> dataList = FXCollections.observableArrayList( new BirthdayEvent("Jacob", new Date()), new BirthdayEvent("Isabella", new Date()), new BirthdayEvent("Ethan", new Date()), new BirthdayEvent("Emma", new Date()), new BirthdayEvent("Michael", new Date()) ); TableView table = new TableView(); table.setEditable(true); TableColumn nameColumn = new TableColumn("Name"); nameColumn.setPrefWidth(90); nameColumn.setCellValueFactory( new PropertyValueFactory<BirthdayEvent, String>("name")); TableColumn dateColumn = new TableColumn("Date"); dateColumn.setEditable(true); dateColumn.setPrefWidth(75); dateColumn.setMinWidth(200); dateColumn.setCellValueFactory(new PropertyValueFactory<BirthdayEvent, Date>("date")); dateColumn.setCellFactory(new Callback<TableColumn, TableCell>() { @Override public TableCell call(TableColumn p) { DatePickerCell datePick = new DatePickerCell(dataList); return datePick; } }); table.getColumns().addAll(nameColumn, dateColumn); table.setItems(dataList); final VBox vbox = new VBox(); vbox.setSpacing(5); vbox.setPadding(new Insets(10, 0, 0, 10)); vbox.getChildren().add(table); ((Group) scene.getRoot()).getChildren().addAll(vbox); stage.setScene(scene); stage.show(); } /** * The main() method is ignored in correctly deployed JavaFX application. * main() serves only as fallback in case the application can not be * launched through deployment artifacts, e.g., in IDEs with limited FX * support. NetBeans ignores main(). * * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
package com.rox.emu.p6502; import com.rox.emu.Memory; import com.rox.emu.UnknownOpCodeException; /** * A emulated representation of MOS 6502, 8 bit * microprocessor functionality. * * @author Ross Drew */ public class CPU { private final Memory memory; private final Registers registers = new Registers(); public static final int CARRY_INDICATOR_BIT = 0x100; //The bit set on a word when a byte has carried up public static final int NEGATIVE_INDICATOR_BIT = 0x80; //The bit set on a byte when a it is negative public CPU(Memory memory) { this.memory = memory; } /** * IRL this takes 6 CPU cycles but we'll cross that bridge IF we come to it- */ public void reset(){ System.out.println("*** RESETTING >>>"); registers.setRegister(Registers.REG_ACCUMULATOR, 0x0); registers.setRegister(Registers.REG_X_INDEX, 0x0); registers.setRegister(Registers.REG_Y_INDEX, 0x0); registers.setRegister(Registers.REG_STATUS, 0x34); registers.setRegister(Registers.REG_PC_HIGH, memory.getByte(0xFFFC)); registers.setRegister(Registers.REG_PC_LOW, memory.getByte(0xFFFD)); registers.setRegister(Registers.REG_SP, 0xFF); System.out.println("...READY!"); } /** * Get the value of the 16 bit Program Counter (PC) and increment */ private int getAndStepPC(){ final int originalPC = registers.getPC(); registers.setPC(originalPC + 1); return originalPC; } private int getByteOfMemoryAt(int location, int index){ final int memoryByte = memory.getByte(location + index); System.out.println("FETCH mem[" + location + (index != 0 ? "[" + index + "]" : "") +"] --> " + memoryByte); return memoryByte; } private int setByteOfMemoryAt(int location, int index, int newByte){ memory.setByteAt(location + index, newByte); System.out.println("STORE " + newByte + " --> mem[" + location + (index != 0 ? "[" + index + "]" : "") +"]"); return (location + index); } private int getByteOfMemoryXIndexedAt(int location){ return getByteOfMemoryAt(location, registers.getRegister(Registers.REG_X_INDEX)); } private int setByteOfMemoryXIndexedAt(int location, int newByte){ return setByteOfMemoryAt(location, registers.getRegister(Registers.REG_X_INDEX), newByte); } private int getByteOfMemoryYIndexedAt(int location){ return getByteOfMemoryAt(location, registers.getRegister(Registers.REG_Y_INDEX)); } private int getByteOfMemoryAt(int location){ return getByteOfMemoryAt(location, 0); } public Registers getRegisters(){ return registers; } /** * Return the next byte from program memory, as defined * by the Program Counter. * <em>Increments the Program Counter by 1</em> * * @return byte from PC[0] */ private int nextProgramByte(){ int memoryLocation = getAndStepPC(); return getByteOfMemoryAt(memoryLocation); } /** * Combine the next two bytes in program memory, as defined by * the Program Counter into a word so that:- * * PC[0] = high order byte * PC[1] = low order byte * * <em>Increments the Program Counter by 1</em> * * @return word made up of both bytes */ private int nextProgramWord(){ int byte1 = nextProgramByte(); return (byte1 << 8) | nextProgramByte() ; } public void step(int steps){ for (int i=0; i<steps; i++) step(); } public void step() { System.out.println("\n*** STEP >>>"); int accumulatorBeforeOperation = registers.getRegister(Registers.REG_ACCUMULATOR); int opCode = nextProgramByte(); //Execute the opcode System.out.println("Instruction: " + InstructionSet.getOpCodeName(opCode) + "..."); switch (opCode){ case InstructionSet.OP_ASL_A: { int newFakeByte = registers.getRegister(Registers.REG_ACCUMULATOR) << 1; setCarryFlagBasedOn(newFakeByte); registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, newFakeByte); } break; case InstructionSet.OP_ASL_Z: { int location = nextProgramByte(); int newFakeByte = memory.getByte(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_Z_IX: { int location = nextProgramByte(); int newFakeByte = getByteOfMemoryXIndexedAt(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); setByteOfMemoryXIndexedAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_ABS_IX: { int location = nextProgramWord(); int newFakeByte = getByteOfMemoryXIndexedAt(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); setByteOfMemoryXIndexedAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_ABS: { int location = nextProgramWord(); int newFakeByte = memory.getByte(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_LSR_A: { int newFakeByte = registers.getRegister(Registers.REG_ACCUMULATOR); setBorrowFlagFor(newFakeByte); registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, newFakeByte >> 1); } break; case InstructionSet.OP_LSR_Z: { int location = nextProgramByte(); int newFakeByte = memory.getByte(location); setBorrowFlagFor(newFakeByte); newFakeByte = newFakeByte >> 1; registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_ROL_A: registers.setRegister(Registers.REG_ACCUMULATOR, performROL(registers.getRegister(Registers.REG_ACCUMULATOR))); break; case InstructionSet.OP_ROL_Z: int location = nextProgramByte(); memory.setByteAt(location, performROL(memory.getByte(location))); break; /* Not implemented and/or not published on older 6502s */ case InstructionSet.OP_ROR_A: registers.setRegister(Registers.REG_ACCUMULATOR, performROR(registers.getRegister(Registers.REG_ACCUMULATOR))); break; case InstructionSet.OP_SEC: registers.setFlag(Registers.STATUS_FLAG_CARRY); break; case InstructionSet.OP_CLC: registers.clearFlag(Registers.STATUS_FLAG_CARRY); break; case InstructionSet.OP_CLV: registers.clearFlag(Registers.STATUS_FLAG_OVERFLOW); break; case InstructionSet.OP_INC_Z: int incrementLocation = nextProgramByte(); int incrementedValue = (memory.getByte(incrementLocation) + 1) & 0xFF; registers.setFlagsBasedOn(incrementedValue); memory.setByteAt(incrementLocation, incrementedValue); break; case InstructionSet.OP_DEC_Z: int decrementLocation = nextProgramByte(); int decrementedValue = (memory.getByte(decrementLocation) - 1) & 0xFF; registers.setFlagsBasedOn(decrementedValue); memory.setByteAt(decrementLocation, decrementedValue); break; case InstructionSet.OP_INX: registers.incrementRegisterWithFlags(Registers.REG_X_INDEX); break; case InstructionSet.OP_DEX: registers.decrementRegisterWithFlags(Registers.REG_X_INDEX); break; case InstructionSet.OP_INY: registers.incrementRegisterWithFlags(Registers.REG_Y_INDEX); break; case InstructionSet.OP_DEY: registers.decrementRegisterWithFlags(Registers.REG_Y_INDEX); break; case InstructionSet.OP_LDX_I: registers.setRegisterAndFlags(Registers.REG_X_INDEX, nextProgramByte()); break; case InstructionSet.OP_LDY_I: registers.setRegisterAndFlags(Registers.REG_Y_INDEX, nextProgramByte()); break; case InstructionSet.OP_LDA_Z_IX: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramByte())); break; case InstructionSet.OP_LDA_IY: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryYIndexedAt(nextProgramWord())); break; case InstructionSet.OP_LDA_IX: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramWord())); break; case InstructionSet.OP_LDA_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte()); break; case InstructionSet.OP_LDA_ABS: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramWord())); break; case InstructionSet.OP_LDA_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_AND_Z: performAND(getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_AND_ABS: performAND(getByteOfMemoryAt(nextProgramWord())); break; case InstructionSet.OP_AND_I: performAND(nextProgramByte()); break; case InstructionSet.OP_AND_Z_IX: performAND(getByteOfMemoryXIndexedAt(nextProgramByte())); break; case InstructionSet.OP_AND_ABS_IX: performAND(getByteOfMemoryXIndexedAt(nextProgramWord())); break; case InstructionSet.OP_BIT_Z: int memData = memory.getByte(nextProgramByte()); if ((memData & registers.getRegister(Registers.REG_ACCUMULATOR)) == memData) registers.setFlag(Registers.STATUS_FLAG_ZERO); else registers.clearFlag(Registers.STATUS_FLAG_ZERO); //Set N, V to bits 7 and 6 of memory data registers.setRegister(Registers.REG_STATUS, (memData & 0b11000000) | (registers.getRegister(Registers.REG_STATUS) & 0b00111111)); break; case InstructionSet.OP_ORA_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte() | accumulatorBeforeOperation); break; case InstructionSet.OP_ORA_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte()) | accumulatorBeforeOperation); break; case InstructionSet.OP_EOR_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte() ^ accumulatorBeforeOperation); break; case InstructionSet.OP_EOR_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte()) ^ accumulatorBeforeOperation); break; case InstructionSet.OP_ADC_Z: performADC(getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_ADC_I: performADC(nextProgramByte()); break; case InstructionSet.OP_ADC_ABS: performADC(getByteOfMemoryAt(nextProgramWord())); break; case InstructionSet.OP_ADC_Z_IX: performADC(getByteOfMemoryXIndexedAt(nextProgramByte())); break; case InstructionSet.OP_SBC_I: performSBC(nextProgramByte()); break; case InstructionSet.OP_SBC_Z: performSBC(getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_STY_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_Y_INDEX)); break; case InstructionSet.OP_STA_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_ABS: memory.setByteAt(nextProgramWord(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_Z_IX: setByteOfMemoryXIndexedAt(nextProgramByte(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_ABS_IX: setByteOfMemoryXIndexedAt(nextProgramWord(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STX_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_PHA: push(registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_PLA: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, pop()); break; case InstructionSet.OP_JMP_ABS: int h = nextProgramByte(); int l = nextProgramByte(); registers.setRegister(Registers.REG_PC_HIGH, h); registers.setRegister(Registers.REG_PC_LOW, l); break; case InstructionSet.OP_BCS: branchIf(registers.getFlag(Registers.STATUS_FLAG_CARRY)); break; case InstructionSet.OP_BCC: branchIf(!registers.getFlag(Registers.STATUS_FLAG_CARRY)); break; case InstructionSet.OP_BEQ: branchIf(registers.getFlag(Registers.STATUS_FLAG_ZERO)); break; case InstructionSet.OP_BNE: branchIf(!registers.getFlag(Registers.STATUS_FLAG_ZERO)); break; case InstructionSet.OP_BMI: branchIf(registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)); break; case InstructionSet.OP_BPL: branchIf(!registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)); break; case InstructionSet.OP_BVS: branchIf(registers.getFlag(Registers.STATUS_FLAG_OVERFLOW)); break; case InstructionSet.OP_BVC: branchIf(!registers.getFlag(Registers.STATUS_FLAG_OVERFLOW)); break; case InstructionSet.OP_TAX: registers.setRegister(Registers.REG_X_INDEX, registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_TAY: registers.setRegister(Registers.REG_Y_INDEX, registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_TYA: registers.setRegister(Registers.REG_ACCUMULATOR, registers.getRegister(Registers.REG_Y_INDEX)); break; case InstructionSet.OP_TXA: registers.setRegister(Registers.REG_ACCUMULATOR, registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_TXS: registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_TSX: registers.setRegister(Registers.REG_X_INDEX, registers.getRegister(Registers.REG_SP)); registers.setFlagsBasedOn(registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_NOP: //Do nothing break; default: throw new UnknownOpCodeException("Unknown 6502 OpCode:" + opCode + " encountered.", opCode); } } private int pop(){ registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_SP) + 1); int address = 0x0100 | registers.getRegister(Registers.REG_SP); return getByteOfMemoryAt(address); } private void push(int value){ memory.setByteAt(0x0100 | registers.getRegister(Registers.REG_SP), value); registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_SP) - 1); } private int performROL(int initialValue){ int rotatedValue = (initialValue << 1) | (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 1 : 0); registers.setFlagsBasedOn(rotatedValue); setCarryFlagBasedOn(rotatedValue); return rotatedValue & 0xFF; } private int performROR(int initialValue){ int rotatedValue = (initialValue >> 1) | (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 0b10000000 : 0); setBorrowFlagFor(initialValue); registers.setFlagsBasedOn(rotatedValue); return rotatedValue & 0xFF; } private void setBorrowFlagFor(int newFakeByte) { if ((newFakeByte & 0x1) == 0x1) registers.setFlag(Registers.STATUS_FLAG_CARRY); else registers.clearFlag(Registers.STATUS_FLAG_CARRY); } private void setCarryFlagBasedOn(int newFakeByte) { if ((newFakeByte & CARRY_INDICATOR_BIT) == CARRY_INDICATOR_BIT) registers.setFlag(Registers.STATUS_FLAG_CARRY); else registers.clearFlag(Registers.STATUS_FLAG_CARRY); } private void branchIf(boolean condition){ int location = nextProgramByte(); if (condition) branchTo(location); } /** * Branch to a relative location as defined by a signed byte * * @param displacement relative (-127 -> 128) location from end of branch instruction */ private void branchTo(int displacement) { int displacementByte = displacement & 0xFF; if ((displacementByte & NEGATIVE_INDICATOR_BIT) == NEGATIVE_INDICATOR_BIT) registers.setRegister(Registers.REG_PC_LOW, registers.getRegister(Registers.REG_PC_LOW) - fromTwosComplimented(displacementByte)); else registers.setRegister(Registers.REG_PC_LOW, registers.getRegister(Registers.REG_PC_LOW) + displacementByte); } private void performAND(int byteTerm){ registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, byteTerm & registers.getRegister(Registers.REG_ACCUMULATOR)); } private void performADC(int byteTerm){ int carry = (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 1 : 0); addToAccumulator(byteTerm + carry); } //(1) compliment of carry flag added (so subtracted) as well //(2) set carry if no borrow required (A >= M[v]) private void performSBC(int byteTerm){ registers.setFlag(Registers.STATUS_FLAG_NEGATIVE); int borrow = (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 0 : 1); addToAccumulator(twosComplimentOf(byteTerm + borrow)); } private int twosComplimentOf(int byteValue){ return ((~byteValue) + 1) & 0xFF; } private int fromTwosComplimented(int byteValue){ return ((~byteValue)) & 0xFF; } /** * Perform a binary addition, setting Carry and Overflow flags as required. * * @param term term to add to the accumulator */ private void addToAccumulator(int term){ int result = registers.getRegister(Registers.REG_ACCUMULATOR) + term; //Set Carry, if bit 8 is set on new accumulator value, ignoring in 2s compliment addition (subtraction) if (!registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)){ setCarryFlagBasedOn(result); }else { registers.clearFlag(Registers.STATUS_FLAG_CARRY); } //Set Overflow if the sign of both inputs is different from the sign of the result if (((registers.getRegister(Registers.REG_ACCUMULATOR) ^ result) & (term ^ result) & 0x80) != 0) registers.setFlag(Registers.STATUS_FLAG_OVERFLOW); registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, result & 0xFF); } }
package com.rox.emu.p6502; import com.rox.emu.Memory; import com.rox.emu.UnknownOpCodeException; /** * A emulated representation of MOS 6502, 8 bit * microprocessor functionality. * * @author Ross Drew */ public class CPU { private final Memory memory; private final Registers registers = new Registers(); public static final int CARRY_INDICATOR_BIT = 0x100; //The bit set on a word when a byte has carried up public static final int NEGATIVE_INDICATOR_BIT = 0x80; //The bit set on a byte when a it is negative public CPU(Memory memory) { this.memory = memory; } /** * IRL this takes 6 CPU cycles but we'll cross that bridge IF we come to it- */ public void reset(){ System.out.println("*** RESETTING >>>"); registers.setRegister(Registers.REG_ACCUMULATOR, 0x0); registers.setRegister(Registers.REG_X_INDEX, 0x0); registers.setRegister(Registers.REG_Y_INDEX, 0x0); registers.setRegister(Registers.REG_STATUS, 0x34); registers.setRegister(Registers.REG_PC_HIGH, memory.getByte(0xFFFC)); registers.setRegister(Registers.REG_PC_LOW, memory.getByte(0xFFFD)); registers.setRegister(Registers.REG_SP, 0xFF); System.out.println("...READY!"); } /** * Get the value of the 16 bit Program Counter (PC) and increment */ private int getAndStepPC(){ final int originalPC = registers.getPC(); registers.setPC(originalPC + 1); return originalPC; } private int getByteOfMemoryAt(int location, int index){ final int memoryByte = memory.getByte(location + index); System.out.println("FETCH mem[" + location + (index != 0 ? "[" + index + "]" : "") +"] --> " + memoryByte); return memoryByte; } private int setByteOfMemoryAt(int location, int index, int newByte){ memory.setByteAt(location + index, newByte); System.out.println("STORE " + newByte + " --> mem[" + location + (index != 0 ? "[" + index + "]" : "") +"]"); return (location + index); } private int getByteOfMemoryXIndexedAt(int location){ return getByteOfMemoryAt(location, registers.getRegister(Registers.REG_X_INDEX)); } private int setByteOfMemoryXIndexedAt(int location, int newByte){ return setByteOfMemoryAt(location, registers.getRegister(Registers.REG_X_INDEX), newByte); } private int getByteOfMemoryYIndexedAt(int location){ return getByteOfMemoryAt(location, registers.getRegister(Registers.REG_Y_INDEX)); } private int getByteOfMemoryAt(int location){ return getByteOfMemoryAt(location, 0); } public Registers getRegisters(){ return registers; } /** * Return the next byte from program memory, as defined * by the Program Counter. * <em>Increments the Program Counter by 1</em> * * @return byte from PC[0] */ private int nextProgramByte(){ int memoryLocation = getAndStepPC(); return getByteOfMemoryAt(memoryLocation); } /** * Combine the next two bytes in program memory, as defined by * the Program Counter into a word so that:- * * PC[0] = high order byte * PC[1] = low order byte * * <em>Increments the Program Counter by 1</em> * * @return word made up of both bytes */ private int nextProgramWord(){ int byte1 = nextProgramByte(); return (byte1 << 8) | nextProgramByte() ; } public void step(int steps){ for (int i=0; i<steps; i++) step(); } public void step() { System.out.println("\n*** STEP >>>"); int accumulatorBeforeOperation = registers.getRegister(Registers.REG_ACCUMULATOR); int opCode = nextProgramByte(); //Execute the opcode System.out.println("Instruction: " + InstructionSet.getOpCodeName(opCode) + "..."); switch (opCode){ case InstructionSet.OP_ASL_A: { int newFakeByte = registers.getRegister(Registers.REG_ACCUMULATOR) << 1; setCarryFlagBasedOn(newFakeByte); registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, newFakeByte); } break; case InstructionSet.OP_ASL_Z: { int location = nextProgramByte(); int newFakeByte = memory.getByte(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_Z_IX: { int location = nextProgramByte(); int newFakeByte = getByteOfMemoryXIndexedAt(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); setByteOfMemoryXIndexedAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_ABS_IX: { int location = nextProgramWord(); int newFakeByte = getByteOfMemoryXIndexedAt(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); setByteOfMemoryXIndexedAt(location, newFakeByte); } break; case InstructionSet.OP_ASL_ABS: { int location = nextProgramWord(); int newFakeByte = memory.getByte(location) << 1; setCarryFlagBasedOn(newFakeByte); registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_LSR_A: { int newFakeByte = registers.getRegister(Registers.REG_ACCUMULATOR); setBorrowFlagFor(newFakeByte); registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, newFakeByte >> 1); } break; case InstructionSet.OP_LSR_Z: { int location = nextProgramByte(); int newFakeByte = memory.getByte(location); setBorrowFlagFor(newFakeByte); newFakeByte = newFakeByte >> 1; registers.setFlagsBasedOn(newFakeByte); memory.setByteAt(location, newFakeByte); } break; case InstructionSet.OP_ROL_A: registers.setRegister(Registers.REG_ACCUMULATOR, performROL(registers.getRegister(Registers.REG_ACCUMULATOR))); break; case InstructionSet.OP_ROL_Z: int location = nextProgramByte(); memory.setByteAt(location, performROL(memory.getByte(location))); break; /* Not implemented and/or not published on older 6502s */ case InstructionSet.OP_ROR_A: registers.setRegister(Registers.REG_ACCUMULATOR, performROR(registers.getRegister(Registers.REG_ACCUMULATOR))); break; case InstructionSet.OP_SEC: registers.setFlag(Registers.STATUS_FLAG_CARRY); break; case InstructionSet.OP_CLC: registers.clearFlag(Registers.STATUS_FLAG_CARRY); break; case InstructionSet.OP_CLV: registers.clearFlag(Registers.STATUS_FLAG_OVERFLOW); break; case InstructionSet.OP_INC_Z: { int incrementLocation = nextProgramByte(); int incrementedValue = (memory.getByte(incrementLocation) + 1) & 0xFF; registers.setFlagsBasedOn(incrementedValue); memory.setByteAt(incrementLocation, incrementedValue); }break; case InstructionSet.OP_INC_ABS: { int incrementLocation = nextProgramWord(); int incrementedValue = (memory.getByte(incrementLocation) + 1) & 0xFF; registers.setFlagsBasedOn(incrementedValue); memory.setByteAt(incrementLocation, incrementedValue); }break; case InstructionSet.OP_DEC_Z: { int decrementLocation = nextProgramByte(); int decrementedValue = (memory.getByte(decrementLocation) - 1) & 0xFF; registers.setFlagsBasedOn(decrementedValue); memory.setByteAt(decrementLocation, decrementedValue); }break; case InstructionSet.OP_DEC_ABS: { int decrementLocation = nextProgramWord(); int decrementedValue = (memory.getByte(decrementLocation) - 1) & 0xFF; registers.setFlagsBasedOn(decrementedValue); memory.setByteAt(decrementLocation, decrementedValue); }break; case InstructionSet.OP_INX: registers.incrementRegisterWithFlags(Registers.REG_X_INDEX); break; case InstructionSet.OP_DEX: registers.decrementRegisterWithFlags(Registers.REG_X_INDEX); break; case InstructionSet.OP_INY: registers.incrementRegisterWithFlags(Registers.REG_Y_INDEX); break; case InstructionSet.OP_DEY: registers.decrementRegisterWithFlags(Registers.REG_Y_INDEX); break; case InstructionSet.OP_LDX_I: registers.setRegisterAndFlags(Registers.REG_X_INDEX, nextProgramByte()); break; case InstructionSet.OP_LDY_I: registers.setRegisterAndFlags(Registers.REG_Y_INDEX, nextProgramByte()); break; case InstructionSet.OP_LDA_Z_IX: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramByte())); break; case InstructionSet.OP_LDA_ABS_IY: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryYIndexedAt(nextProgramWord())); break; case InstructionSet.OP_LDA_ABS_IX: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramWord())); break; case InstructionSet.OP_LDA_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte()); break; case InstructionSet.OP_LDA_ABS: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramWord())); break; case InstructionSet.OP_LDA_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_AND_Z: performAND(getByteOfMemoryAt(nextProgramByte())); break; case InstructionSet.OP_AND_ABS: performAND(getByteOfMemoryAt(nextProgramWord())); break; case InstructionSet.OP_AND_I: performAND(nextProgramByte()); break; case InstructionSet.OP_AND_Z_IX: performAND(getByteOfMemoryXIndexedAt(nextProgramByte())); break; case InstructionSet.OP_AND_ABS_IX: performAND(getByteOfMemoryXIndexedAt(nextProgramWord())); break; case InstructionSet.OP_BIT_Z: { performBIT(memory.getByte(nextProgramByte())); }break; case InstructionSet.OP_BIT_ABS: { performBIT(memory.getByte(nextProgramWord())); }break; case InstructionSet.OP_ORA_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte() | accumulatorBeforeOperation); break; case InstructionSet.OP_ORA_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte()) | accumulatorBeforeOperation); break; case InstructionSet.OP_EOR_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, nextProgramByte() ^ accumulatorBeforeOperation); break; case InstructionSet.OP_EOR_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte()) ^ accumulatorBeforeOperation); break; case InstructionSet.OP_ADC_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(getByteOfMemoryAt(nextProgramByte()))); break; case InstructionSet.OP_ADC_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(nextProgramByte())); break; case InstructionSet.OP_ADC_ABS: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(getByteOfMemoryAt(nextProgramWord()))); break; case InstructionSet.OP_ADC_Z_IX: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performADC(getByteOfMemoryXIndexedAt(nextProgramByte()))); break; //XXX Need to use 2s compliment addition (subtraction) // ? Do I deal with borrow in? does it need to manually set?! case InstructionSet.OP_CMP_I: int value = nextProgramByte(); int result = registers.getRegister(Registers.REG_ACCUMULATOR) - value; registers.setFlagsBasedOn(result & 0xFF); break; case InstructionSet.OP_SBC_I: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performSBC(nextProgramByte())); break; case InstructionSet.OP_SBC_Z: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, performSBC(getByteOfMemoryAt(nextProgramByte()))); break; case InstructionSet.OP_STY_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_Y_INDEX)); break; case InstructionSet.OP_STA_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_ABS: memory.setByteAt(nextProgramWord(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_Z_IX: setByteOfMemoryXIndexedAt(nextProgramByte(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STA_ABS_IX: setByteOfMemoryXIndexedAt(nextProgramWord(), registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_STX_Z: memory.setByteAt(nextProgramByte(), registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_PHA: push(registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_PLA: registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, pop()); break; case InstructionSet.OP_PHP: push(registers.getRegister(Registers.REG_STATUS)); break; case InstructionSet.OP_PLP://XXX registers.setRegister(Registers.REG_STATUS, pop()); break; case InstructionSet.OP_JMP_ABS: int h = nextProgramByte(); int l = nextProgramByte(); registers.setRegister(Registers.REG_PC_HIGH, h); registers.setRegister(Registers.REG_PC_LOW, l); break; case InstructionSet.OP_BCS: branchIf(registers.getFlag(Registers.STATUS_FLAG_CARRY)); break; case InstructionSet.OP_BCC: branchIf(!registers.getFlag(Registers.STATUS_FLAG_CARRY)); break; case InstructionSet.OP_BEQ: branchIf(registers.getFlag(Registers.STATUS_FLAG_ZERO)); break; case InstructionSet.OP_BNE: branchIf(!registers.getFlag(Registers.STATUS_FLAG_ZERO)); break; case InstructionSet.OP_BMI: branchIf(registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)); break; case InstructionSet.OP_BPL: branchIf(!registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)); break; case InstructionSet.OP_BVS: branchIf(registers.getFlag(Registers.STATUS_FLAG_OVERFLOW)); break; case InstructionSet.OP_BVC: branchIf(!registers.getFlag(Registers.STATUS_FLAG_OVERFLOW)); break; case InstructionSet.OP_TAX: registers.setRegister(Registers.REG_X_INDEX, registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_TAY: registers.setRegister(Registers.REG_Y_INDEX, registers.getRegister(Registers.REG_ACCUMULATOR)); break; case InstructionSet.OP_TYA: registers.setRegister(Registers.REG_ACCUMULATOR, registers.getRegister(Registers.REG_Y_INDEX)); break; case InstructionSet.OP_TXA: registers.setRegister(Registers.REG_ACCUMULATOR, registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_TXS: registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_TSX: registers.setRegister(Registers.REG_X_INDEX, registers.getRegister(Registers.REG_SP)); registers.setFlagsBasedOn(registers.getRegister(Registers.REG_X_INDEX)); break; case InstructionSet.OP_NOP: //Do nothing break; default: throw new UnknownOpCodeException("Unknown 6502 OpCode:" + opCode + " encountered.", opCode); } } private int pop(){ registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_SP) + 1); int address = 0x0100 | registers.getRegister(Registers.REG_SP); int value = getByteOfMemoryAt(address); System.out.println("POP " + value + "(" + Integer.toBinaryString(value) + ") from mem[" + address + "]"); return value; } private void push(int value){ System.out.println("PUSH " + value + "(" + Integer.toBinaryString(value) + ") to mem[" + registers.getRegister(Registers.REG_SP) + "]"); memory.setByteAt(0x0100 | registers.getRegister(Registers.REG_SP), value); registers.setRegister(Registers.REG_SP, registers.getRegister(Registers.REG_SP) - 1); } private int performROL(int initialValue){ int rotatedValue = (initialValue << 1) | (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 1 : 0); registers.setFlagsBasedOn(rotatedValue); setCarryFlagBasedOn(rotatedValue); return rotatedValue & 0xFF; } private int performROR(int initialValue){ int rotatedValue = (initialValue >> 1) | (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 0b10000000 : 0); setBorrowFlagFor(initialValue); registers.setFlagsBasedOn(rotatedValue); return rotatedValue & 0xFF; } private void performBIT(int memData) { if ((memData & registers.getRegister(Registers.REG_ACCUMULATOR)) == memData) registers.setFlag(Registers.STATUS_FLAG_ZERO); else registers.clearFlag(Registers.STATUS_FLAG_ZERO); //Set N, V to bits 7 and 6 of memory data registers.setRegister(Registers.REG_STATUS, (memData & 0b11000000) | (registers.getRegister(Registers.REG_STATUS) & 0b00111111)); } private void setBorrowFlagFor(int newFakeByte) { if ((newFakeByte & 0x1) == 0x1) registers.setFlag(Registers.STATUS_FLAG_CARRY); else registers.clearFlag(Registers.STATUS_FLAG_CARRY); } private void setCarryFlagBasedOn(int newFakeByte) { if ((newFakeByte & CARRY_INDICATOR_BIT) == CARRY_INDICATOR_BIT) registers.setFlag(Registers.STATUS_FLAG_CARRY); else registers.clearFlag(Registers.STATUS_FLAG_CARRY); } private void branchIf(boolean condition){ int location = nextProgramByte(); if (condition) branchTo(location); } /** * Branch to a relative location as defined by a signed byte * * @param displacement relative (-127 -> 128) location from end of branch instruction */ private void branchTo(int displacement) { int displacementByte = displacement & 0xFF; if ((displacementByte & NEGATIVE_INDICATOR_BIT) == NEGATIVE_INDICATOR_BIT) registers.setRegister(Registers.REG_PC_LOW, registers.getRegister(Registers.REG_PC_LOW) - fromTwosComplimented(displacementByte)); else registers.setRegister(Registers.REG_PC_LOW, registers.getRegister(Registers.REG_PC_LOW) + displacementByte); } private void performAND(int byteTerm){ registers.setRegisterAndFlags(Registers.REG_ACCUMULATOR, byteTerm & registers.getRegister(Registers.REG_ACCUMULATOR)); } private int performADC(int byteTerm){ int carry = (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 1 : 0); return addToAccumulator(byteTerm + carry); } //(1) compliment of carry flag added (so subtracted) as well //(2) set carry if no borrow required (A >= M[v]) private int performSBC(int byteTerm){ registers.setFlag(Registers.STATUS_FLAG_NEGATIVE); int borrow = (registers.getFlag(Registers.STATUS_FLAG_CARRY) ? 0 : 1); return addToAccumulator(twosComplimentOf(byteTerm + borrow)); } private int twosComplimentOf(int byteValue){ return ((~byteValue) + 1) & 0xFF; } private int fromTwosComplimented(int byteValue){ return ((~byteValue)) & 0xFF; } /** * Perform a binary addition, setting Carry and Overflow flags as required. * * @param term term to add to the accumulator */ private int addToAccumulator(int term){ int result = registers.getRegister(Registers.REG_ACCUMULATOR) + term; //Set Carry, if bit 8 is set on new accumulator value, ignoring in 2s compliment addition (subtraction) if (!registers.getFlag(Registers.STATUS_FLAG_NEGATIVE)){ setCarryFlagBasedOn(result); }else { registers.clearFlag(Registers.STATUS_FLAG_CARRY); } //Set Overflow if the sign of both inputs is different from the sign of the result if (((registers.getRegister(Registers.REG_ACCUMULATOR) ^ result) & (term ^ result) & 0x80) != 0) registers.setFlag(Registers.STATUS_FLAG_OVERFLOW); return (result & 0xFF); } }
package datability; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class Postgresql implements Database { private static final Logger LOG = LoggerFactory.getLogger(Postgresql.class); private final Connection connection; public Postgresql(Connection connection) { this.connection = Assert.notNull(connection, "A connection is required"); assertValidConnection(connection); } @Override public Database dropNotNulls(String... tables) { if (tables != null) { try { for (String table : tables) { for (String column : findNotNullColumns(table)) { LOG.info("Disabling not-null ON column '{}' of table '{}'", column, table); executeSql("ALTER TABLE " + table + " ALTER " + column + " DROP NOT NULL"); } } } catch (SQLException e) { throw new DatabaseException(e); } } return this; } @Override public Database dropPrimaryKeys(String... tables) { if (tables != null) { try { for (String table : tables) { for (String primaryKey : findPrimaryKeyConstraints(table)) { LOG.info("Disabling primary key '{}' of table '{}'", primaryKey, table); executeSql("ALTER TABLE " + table + " DROP CONSTRAINT " + primaryKey); } } } catch (SQLException e) { throw new DatabaseException(e); } } return this; } @Override public Database dropForeignKeys(String... tables) { if (tables != null) { try { for (String table : tables) { for (String foreignKey : findForeignKeyConstraints(table)) { LOG.info("Disabling foreign key '{}' of table '{}'", foreignKey, table); executeSql("ALTER TABLE " + table + " DROP CONSTRAINT " + foreignKey); } } } catch (SQLException e) { throw new DatabaseException(e); } } return this; } @Override public Database dropAll(String... tables) { if (tables != null) { dropForeignKeys(tables); dropPrimaryKeys(tables); dropNotNulls(tables); } return this; } private List<String> findNotNullColumns(String table) throws SQLException { List<String> notNullsColumns = new ArrayList<>(); String sql = "SELECT DISTINCT column_name FROM INFORMATION_SCHEMA.COLUMNS" + " WHERE column_name IS NOT NULL" + " AND columns.table_name = '" + table + "'" + " AND columns.is_nullable='NO'"; try { notNullsColumns.addAll(getFirstColumnValues(sql)); } catch (SQLException e) { throw new DatabaseException(sql, e); } // Cannot drop-non-null from columns part of a primary key notNullsColumns.removeAll(findPrimaryKeyColumns(table)); return notNullsColumns; } private List<String> findPrimaryKeyColumns(String table) throws SQLException { return getFirstColumnValues("SELECT a.attname" + " FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY (i.indkey)" + " WHERE i.indrelid = '" + table + "'::REGCLASS AND i.indisprimary"); } private List<String> findPrimaryKeyConstraints(String table) throws SQLException { return getFirstColumnValues("SELECT constraint_name" + " FROM information_schema.table_constraints" + " WHERE constraint_type = 'PRIMARY KEY'" + " AND table_name='" + table + "'"); } private List<String> findForeignKeyConstraints(String table) throws SQLException { return getFirstColumnValues("SELECT constraint_name" + " FROM information_schema.table_constraints" + " WHERE constraint_type = 'FOREIGN KEY'" + " AND table_name='" + table + "'"); } private List<String> getFirstColumnValues(String sql) throws SQLException { List<String> values = new ArrayList<>(); ResultSet rs = connection.createStatement().executeQuery(sql); while (rs.next()) { values.add(rs.getString(1)); } return values; } private void executeSql(String sql) { try { LOG.debug("Executing sql: {}", sql); connection.createStatement().execute(sql); } catch (SQLException e) { throw new DatabaseException(sql, e); } } private void assertValidConnection(Connection connection) { try { if (connection.isClosed()) { throw new DatabaseException("Connection is already closed"); } } catch (SQLException e) { throw new DatabaseException(e); } } }
package de.tarent.mica; import de.tarent.mica.model.Coord; public class Action { public static enum Type { MISSED, ATTACK, CLUSTERBOMB, WILDFIRE, SPY_DRONE, TORPEDO_NORD, TORPEDO_OST, TORPEDO_SUED, TORPEDO_WEST } private final Type type; private final Coord coord; public Action(Type type, Coord coord) { this.type = type; this.coord = coord; } public Type getType() { return type; } public Coord getCoord() { return coord; } @Override public String toString() { return type + "@" + coord; } }
package freemarker.core; import java.io.IOException; import java.util.*; import freemarker.template.*; import freemarker.template.utility.StringUtil; /** * An element representing a macro declaration. */ public final class Macro extends TemplateElement implements TemplateModel { private final String name; private final String[] argumentNames; private Map args; private String catchAll; boolean isFunction; static final Macro DO_NOTHING_MACRO = new Macro(".pass", Collections.EMPTY_LIST, freemarker.template.utility.Collections12.EMPTY_MAP, TextBlock.EMPTY_BLOCK); Macro(String name, List argumentNames, Map args, TemplateElement nestedBlock) { this.name = name; this.argumentNames = (String[])argumentNames.toArray( new String[argumentNames.size()]); this.args = args; this.nestedBlock = nestedBlock; } public String getCatchAll() { return catchAll; } public void setCatchAll(String value) { catchAll = value; } public String[] getArgumentNames() { return (String[])argumentNames.clone(); } String[] getArgumentNamesInternal() { return argumentNames; } boolean hasArgNamed(String name) { return args.containsKey(name); } public String getName() { return name; } void accept(Environment env) { env.visitMacroDef(this); } public String getCanonicalForm() { String directiveName = isFunction ? "function" : "macro"; StringBuffer buf = new StringBuffer("< buf.append(directiveName); buf.append(' '); buf.append(name); buf.append('('); int size = argumentNames.length; for (int i = 0; i<size; i++) { buf.append(argumentNames[i]); if (i != (size-1)) { buf.append(","); } } buf.append(")>"); if (nestedBlock != null) { buf.append(nestedBlock.getCanonicalForm()); } buf.append("</ buf.append(directiveName); buf.append('>'); return buf.toString(); } public String getDescription() { return (isFunction() ? "function " : "macro ") + name; } public boolean isFunction() { return isFunction; } class Context implements LocalContext { Environment.Namespace localVars; TemplateElement body; Environment.Namespace bodyNamespace; List bodyParameterNames; Context prevMacroContext; ArrayList prevLocalContextStack; Context(Environment env, TemplateElement body, List bodyParameterNames) { this.localVars = env.new Namespace(); this.prevMacroContext = env.getCurrentMacroContext(); this.bodyNamespace = env.getCurrentNamespace(); this.prevLocalContextStack = env.getLocalContextStack(); this.body = body; this.bodyParameterNames = bodyParameterNames; } Macro getMacro() { return Macro.this; } void runMacro(Environment env) throws TemplateException, IOException { sanityCheck(env); // Set default values for unspecified parameters if (nestedBlock != null) { env.visit(nestedBlock); } } // Set default parameters, check if all the required parameters are defined. void sanityCheck(Environment env) throws TemplateException { boolean resolvedAnArg, hasUnresolvedArg; Expression firstUnresolvedExpression; InvalidReferenceException firstReferenceException; do { firstUnresolvedExpression = null; firstReferenceException = null; resolvedAnArg = hasUnresolvedArg = false; for(int i = 0; i < argumentNames.length; ++i) { String argName = argumentNames[i]; if(localVars.get(argName) == null) { Expression valueExp = (Expression) args.get(argName); if (valueExp != null) { try { TemplateModel tm = valueExp.getAsTemplateModel(env); if(tm == null) { if(!hasUnresolvedArg) { firstUnresolvedExpression = valueExp; hasUnresolvedArg = true; } } else { localVars.put(argName, tm); resolvedAnArg = true; } } catch(InvalidReferenceException e) { if(!hasUnresolvedArg) { hasUnresolvedArg = true; firstReferenceException = e; } } } else { throw new TemplateException( "When calling macro " + StringUtil.jQuote(name) + ", required parameter " + StringUtil.jQuote(argName) + " (parameter #" + (i + 1) + ") was " + (localVars.containsKey(argName) ? "specified, but had null/missing value.\n" + "(Tip: If the parameter value expression on the caller side is known " + "to be legally null/missing, you may want to specify a default value " + "for it with the \"!\" operator, like " + "paramValueExpression!defaultValueExpression.)" : "not specified.\n" + "(Tip: If the omission was deliberate, you may consider making " + "the parameter optional in the macro by specifying a default value for " + "it, like " + StringUtil.encloseAsTag( getTemplate(), "#macro myMacro paramName=defaultExpr") + ".)"), env); } } } } while(resolvedAnArg && hasUnresolvedArg); if(hasUnresolvedArg) { if(firstReferenceException != null) { throw firstReferenceException; } else { firstUnresolvedExpression.invalidReferenceException(env); } } } /** * @return the local variable of the given name * or null if it doesn't exist. */ public TemplateModel getLocalVariable(String name) throws TemplateModelException { return localVars.get(name); } Environment.Namespace getLocals() { return localVars; } /** * Set a local variable in this macro */ void setLocalVar(String name, TemplateModel var) { localVars.put(name, var); } public Collection getLocalVariableNames() throws TemplateModelException { HashSet result = new HashSet(); for (TemplateModelIterator it = localVars.keys().iterator(); it.hasNext();) { result.add(it.next().toString()); } return result; } } }
package interpres.ast; import java.util.List; import java.util.ArrayList; import interpres.language.DefinitionTable; import interpres.language.values.Value; import interpres.language.values.String; public class Program extends AST { private List<AST> expressions; public Program(List<AST> expressions) { this.expressions = expressions; } public Value evaluate(DefinitionTable definitionTable) { return ListExpression.buildFunctionCall("core.list", this.expressions) .evaluate(definitionTable); } }
package io.javalin; import io.javalin.embeddedserver.jetty.websocket.WebSocketConfig; import io.javalin.security.AccessManager; import io.javalin.security.Role; import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; /** * Static methods for routes definitions in Javalin * * @see Javalin#routes(EndpointGroup) */ public class ApiBuilder { @FunctionalInterface public interface EndpointGroup { void addEndpoints(); } static void setStaticJavalin(@NotNull Javalin javalin) { staticJavalin = javalin; } static void clearStaticJavalin() { staticJavalin = null; } private static Javalin staticJavalin; private static Deque<String> pathDeque = new ArrayDeque<>(); /** * Prefixes all handlers defined in its scope with the specified path. * All paths are normalized, so you can call both * path("/path") or path("path") depending on your preference * The method can only be called inside a {@link Javalin#routes(EndpointGroup)}. */ public static void path(@NotNull String path, @NotNull EndpointGroup endpointGroup) { path = (path + "/").replaceAll("/{2,}", "/"); pathDeque.addLast(path); endpointGroup.addEndpoints(); pathDeque.removeLast(); } private static String prefixPath(@NotNull String path) { return pathDeque.stream().collect(Collectors.joining("")) + path; } private static Javalin staticInstance() { if (staticJavalin == null) { throw new IllegalStateException("The static API can only be called within a routes() call"); } return staticJavalin; } // HTTP verbs public static void get(@NotNull String path, @NotNull Handler handler) { staticInstance().get(prefixPath(path), handler); } public static void post(@NotNull String path, @NotNull Handler handler) { staticInstance().post(prefixPath(path), handler); } public static void put(@NotNull String path, @NotNull Handler handler) { staticInstance().put(prefixPath(path), handler); } public static void patch(@NotNull String path, @NotNull Handler handler) { staticInstance().patch(prefixPath(path), handler); } public static void delete(@NotNull String path, @NotNull Handler handler) { staticInstance().delete(prefixPath(path), handler); } // Filters public static void before(@NotNull String path, @NotNull Handler handler) { staticInstance().before(prefixPath(path), handler); } public static void after(@NotNull String path, @NotNull Handler handler) { staticInstance().after(prefixPath(path), handler); } // Secured HTTP verbs public static void get(@NotNull String path, @NotNull Handler handler, @NotNull List<Role> permittedRoles) { staticInstance().get(prefixPath(path), handler, permittedRoles); } public static void post(@NotNull String path, @NotNull Handler handler, @NotNull List<Role> permittedRoles) { staticInstance().post(prefixPath(path), handler, permittedRoles); } public static void put(@NotNull String path, @NotNull Handler handler, @NotNull List<Role> permittedRoles) { staticInstance().put(prefixPath(path), handler, permittedRoles); } public static void patch(@NotNull String path, @NotNull Handler handler, @NotNull List<Role> permittedRoles) { staticInstance().patch(prefixPath(path), handler, permittedRoles); } public static void delete(@NotNull String path, @NotNull Handler handler, @NotNull List<Role> permittedRoles) { staticInstance().delete(prefixPath(path), handler, permittedRoles); } // HTTP verbs (no path specified) public static void get(@NotNull Handler handler) { staticInstance().get(prefixPath(""), handler); } public static void post(@NotNull Handler handler) { staticInstance().post(prefixPath(""), handler); } public static void put(@NotNull Handler handler) { staticInstance().put(prefixPath(""), handler); } public static void patch(@NotNull Handler handler) { staticInstance().patch(prefixPath(""), handler); } public static void delete(@NotNull Handler handler) { staticInstance().delete(prefixPath(""), handler); } // Filters public static void before(@NotNull Handler handler) { staticInstance().before(prefixPath("*"), handler); } public static void after(@NotNull Handler handler) { staticInstance().after(prefixPath("*"), handler); } public static void get(@NotNull Handler handler, @NotNull List<Role> permittedRoles) { staticInstance().get(prefixPath(""), handler, permittedRoles); } public static void post(@NotNull Handler handler, @NotNull List<Role> permittedRoles) { staticInstance().post(prefixPath(""), handler, permittedRoles); } public static void put(@NotNull Handler handler, @NotNull List<Role> permittedRoles) { staticInstance().put(prefixPath(""), handler, permittedRoles); } public static void patch(@NotNull Handler handler, @NotNull List<Role> permittedRoles) { staticInstance().patch(prefixPath(""), handler, permittedRoles); } public static void delete(@NotNull Handler handler, @NotNull List<Role> permittedRoles) { staticInstance().delete(prefixPath(""), handler, permittedRoles); } public static void ws(@NotNull String path, @NotNull WebSocketConfig ws) { staticJavalin.ws(prefixPath(path), ws); } public static void ws(@NotNull String path, @NotNull Class webSocketClass) { staticJavalin.ws(prefixPath(path), webSocketClass); } public static void ws(@NotNull String path, @NotNull Object webSocketObject) { staticJavalin.ws(prefixPath(path), webSocketObject); } }
package mcjty.rftools; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.*; import cpw.mods.fml.common.network.FMLEmbeddedChannel; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import mcjty.base.ModBase; import mcjty.base.ModBaseRef; import mcjty.gui.GuiStyle; import mcjty.rftools.apideps.ComputerCraftHelper; import mcjty.rftools.blocks.blockprotector.BlockProtectors; import mcjty.rftools.blocks.dimlets.DimletSetup; import mcjty.rftools.blocks.logic.RedstoneChannels; import mcjty.rftools.blocks.screens.ScreenSetup; import mcjty.rftools.blocks.security.SecurityChannels; import mcjty.rftools.blocks.shield.ShieldSetup; import mcjty.rftools.blocks.storage.RemoteStorageIdRegistry; import mcjty.rftools.blocks.teleporter.TeleportDestinations; import mcjty.rftools.commands.CommandRftCfg; import mcjty.rftools.commands.CommandRftDb; import mcjty.rftools.commands.CommandRftDim; import mcjty.rftools.commands.CommandRftTp; import mcjty.rftools.dimension.DimensionStorage; import mcjty.rftools.dimension.ModDimensions; import mcjty.rftools.dimension.RfToolsDimensionManager; import mcjty.rftools.items.ModItems; import mcjty.rftools.items.dimlets.DimletDropsEvent; import mcjty.rftools.items.dimlets.DimletMapping; import mcjty.rftools.items.dimlets.KnownDimletConfiguration; import mcjty.rftools.items.manual.GuiRFToolsManual; import mcjty.rftools.network.DimensionSyncChannelHandler; import mcjty.rftools.playerprops.PlayerExtendedProperties; import mcjty.varia.Logging; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraftforge.common.MinecraftForge; import org.apache.commons.lang3.StringUtils; import java.util.EnumMap; @Mod(modid = RFTools.MODID, name="RFTools", dependencies = "required-after:Forge@["+RFTools.MIN_FORGE_VER+",);required-after:CoFHCore@["+RFTools.MIN_COFHCORE_VER+",)", version = RFTools.VERSION) public class RFTools implements ModBase { public static final String MODID = "rftools"; public static final String VERSION = "3.12beta1"; public static final String MIN_FORGE_VER = "10.13.2.1291"; public static final String MIN_COFHCORE_VER = "1.7.10R3.0.0B9"; @SidedProxy(clientSide="mcjty.rftools.ClientProxy", serverSide="mcjty.rftools.ServerProxy") public static CommonProxy proxy; @Mod.Instance("rftools") public static RFTools instance; // Are some mods loaded?. public boolean enderio = false; public boolean mfr = false; public boolean jabba = false; public boolean mekanism = false; public boolean draconicevolution = false; public static EnumMap<Side, FMLEmbeddedChannel> channels; /** This is used to keep track of GUIs that we make*/ private static int modGuiIndex = 0; public ClientInfo clientInfo = new ClientInfo(); public static CreativeTabs tabRfTools = new CreativeTabs("RfTools") { @Override @SideOnly(Side.CLIENT) public Item getTabIconItem() { return ModItems.rfToolsManualItem; } }; public static CreativeTabs tabRfToolsDimlets = new CreativeTabs("RfToolsDimlets") { @Override @SideOnly(Side.CLIENT) public Item getTabIconItem() { return DimletSetup.unknownDimlet; } }; public static final String SHIFT_MESSAGE = "<Press Shift>"; /** Set our custom inventory Gui index to the next available Gui index */ public static final int GUI_LIST_BLOCKS = modGuiIndex++; public static final int GUI_RF_MONITOR = modGuiIndex++; public static final int GUI_LIQUID_MONITOR = modGuiIndex++; public static final int GUI_CRAFTER = modGuiIndex++; public static final int GUI_STORAGE_SCANNER = modGuiIndex++; public static final int GUI_RELAY = modGuiIndex++; public static final int GUI_MATTER_TRANSMITTER = modGuiIndex++; public static final int GUI_MATTER_RECEIVER = modGuiIndex++; public static final int GUI_DIALING_DEVICE = modGuiIndex++; public static final int GUI_TELEPORTPROBE = modGuiIndex++; public static final int GUI_MANUAL_MAIN = modGuiIndex++; public static final int GUI_MANUAL_DIMENSION = modGuiIndex++; public static final int GUI_ENDERGENIC = modGuiIndex++; public static final int GUI_SEQUENCER = modGuiIndex++; public static final int GUI_COUNTER = modGuiIndex++; public static final int GUI_PEARL_INJECTOR = modGuiIndex++; public static final int GUI_TIMER = modGuiIndex++; public static final int GUI_ENDERMONITOR = modGuiIndex++; public static final int GUI_SHIELD = modGuiIndex++; public static final int GUI_DEVELOPERS_DELIGHT = modGuiIndex++; public static final int GUI_DIMLET_RESEARCHER = modGuiIndex++; public static final int GUI_DIMENSION_ENSCRIBER = modGuiIndex++; public static final int GUI_DIMENSION_BUILDER = modGuiIndex++; public static final int GUI_DIMLET_SCRAMBLER = modGuiIndex++; public static final int GUI_MACHINE_INFUSER = modGuiIndex++; public static final int GUI_DIMENSION_EDITOR = modGuiIndex++; public static final int GUI_ITEMFILTER = modGuiIndex++; public static final int GUI_SCREEN = modGuiIndex++; public static final int GUI_SCREENCONTROLLER = modGuiIndex++; public static final int GUI_DIMLET_WORKBENCH = modGuiIndex++; public static final int GUI_ENVIRONMENTAL_CONTROLLER = modGuiIndex++; public static final int GUI_SPAWNER = modGuiIndex++; public static final int GUI_MATTER_BEAMER = modGuiIndex++; public static final int GUI_DIMLET_FILTER = modGuiIndex++; public static final int GUI_SPACE_PROJECTOR = modGuiIndex++; public static final int GUI_BLOCK_PROTECTOR = modGuiIndex++; public static final int GUI_MODULAR_STORAGE = modGuiIndex++; public static final int GUI_REMOTE_STORAGE_ITEM = modGuiIndex++; public static final int GUI_MODULAR_STORAGE_ITEM = modGuiIndex++; public static final int GUI_REMOTE_STORAGE = modGuiIndex++; public static final int GUI_STORAGE_FILTER = modGuiIndex++; public static final int GUI_BUILDER = modGuiIndex++; public static final int GUI_CHAMBER_DETAILS = modGuiIndex++; public static final int GUI_SECURITY_MANAGER = modGuiIndex++; /** * Run before anything else. Read your config, create blocks, items, etc, and * register them with the GameRegistry. */ @EventHandler public void preInit(FMLPreInitializationEvent e) { ModBaseRef.INSTANCE = this; ModBaseRef.MODID = MODID; MinecraftForge.EVENT_BUS.register(new DimletDropsEvent()); this.proxy.preInit(e); FMLInterModComms.sendMessage("Waila", "register", "mcjty.wailasupport.WailaCompatibility.load"); FMLInterModComms.sendMessage("JAKJ_RedstoneInMotion", "blacklistSoft", Block.blockRegistry.getNameForObject(ShieldSetup.invisibleShieldBlock)); FMLInterModComms.sendMessage("JAKJ_RedstoneInMotion", "blacklistSoft", Block.blockRegistry.getNameForObject(ShieldSetup.solidShieldBlock)); FMLInterModComms.sendMessage("JAKJ_RedstoneInMotion", "blacklistSoft", Block.blockRegistry.getNameForObject(ScreenSetup.screenHitBlock)); } /** * Do your mod setup. Build whatever data structures you care about. Register recipes. */ @EventHandler public void init(FMLInitializationEvent e) { this.proxy.init(e); channels = NetworkRegistry.INSTANCE.newChannel("RFToolsChannel", DimensionSyncChannelHandler.instance); Achievements.init(); } @EventHandler public void imcCallback(FMLInterModComms.IMCEvent event) { for (FMLInterModComms.IMCMessage message : event.getMessages()) { if (message.key.equalsIgnoreCase("dimlet_blacklist")) { String dimletName = message.getStringValue(); KnownDimletConfiguration.blacklistDimlet(dimletName); } else if (message.key.equalsIgnoreCase("dimlet_configure")) { String value = message.getStringValue(); String[] splitted = StringUtils.split(value, "="); if (splitted.length < 2) { Logging.logError("Bad format for configdimlet. Needs <Type>.<Name>=<CreateCost>,<MaintainCost>,<TickCost>,<Rarity>!"); continue; } KnownDimletConfiguration.reconfigureDimlet(splitted[0], splitted[1]); } else if (message.key.equalsIgnoreCase("dimlet_preventworldgen")) { String dimletName = message.getStringValue(); KnownDimletConfiguration.preventDimletWorldGeneration(dimletName); } else if (message.key.equalsIgnoreCase("dimlet_preventloot")) { String dimletName = message.getStringValue(); KnownDimletConfiguration.preventDimletLootGeneration(dimletName); } } } @EventHandler public void serverLoad(FMLServerStartingEvent event) { event.registerServerCommand(new CommandRftDim()); event.registerServerCommand(new CommandRftTp()); event.registerServerCommand(new CommandRftDb()); event.registerServerCommand(new CommandRftCfg()); } @EventHandler public void serverStarted(FMLServerStartedEvent event) { Logging.log("RFTools: server is starting"); ModDimensions.initDimensions(); } @EventHandler public void serverStopped(FMLServerStoppedEvent event) { Logging.log("RFTools: server is stopping. Shutting down gracefully"); RfToolsDimensionManager.cleanupDimensionInformation(); TeleportDestinations.clearInstance(); RfToolsDimensionManager.clearInstance(); DimensionStorage.clearInstance(); DimletMapping.clearInstance(); RedstoneChannels.clearInstance(); SecurityChannels.clearInstance(); BlockProtectors.clearInstance(); RemoteStorageIdRegistry.clearInstance(); } /** * Handle interaction with other mods, complete your setup based on this. */ @EventHandler public void postInit(FMLPostInitializationEvent e) { this.proxy.postInit(e); enderio = Loader.isModLoaded("EnderIO"); if (enderio) { Logging.log("RFTools Detected EnderIO: enabling support"); } mfr = Loader.isModLoaded("MineFactoryReloaded"); if (mfr) { Logging.log("RFTools Detected MineFactory Reloaded: enabling support"); } jabba = Loader.isModLoaded("JABBA"); if (jabba) { Logging.log("RFTools Detected JABBA: enabling support"); } mekanism = Loader.isModLoaded("Mekanism"); if (mekanism) { Logging.log("RFTools Detected Mekanism: enabling support"); } draconicevolution = Loader.isModLoaded("DraconicEvolution"); if (draconicevolution) { Logging.log("RFTools Detected Draconic Evolution: enabling support"); } if (Loader.isModLoaded("ComputerCraft")) { Logging.log("RFTools Detected ComputerCraft: enabling support"); ComputerCraftHelper.register(); } } // Implementation for ModBase @Override public void setGuiStyle(EntityPlayerMP playerEntity, GuiStyle style) { PlayerExtendedProperties properties = PlayerExtendedProperties.getProperties(playerEntity); properties.getPreferencesProperties().setStyle(style); } @Override public GuiStyle getGuiStyle(EntityPlayer player) { return PlayerExtendedProperties.getProperties(player).getPreferencesProperties().getStyle(); } @Override public void openManual(EntityPlayer player, int bookIndex, String page) { GuiRFToolsManual.locatePage = page; player.openGui(RFTools.instance, bookIndex, player.worldObj, (int) player.posX, (int) player.posY, (int) player.posZ); } }
package model; import dataObjects.Document; import javafx.collections.ObservableList; import model.similarity.DotProduct; import model.similarity.Similarity; import model.weight.IDF; import model.weight.Weight; import utilities.TermExtractor; import java.sql.Connection; import java.sql.SQLException; import java.util.Collections; import java.util.HashMap; public class ModelOperations { private ModelDatabase db; private Weight weight; private Similarity similarity; protected ModelOperations(Connection connection, ModelDatabase db) throws SQLException{ this.db = db; weight = new IDF(connection); similarity = new DotProduct(connection); } /** * A method to evaluate a query calculating its similarity against the documents, * in order to get the documents sorted by relevance * * @param query The input query from the user * @return An ArrayList of Documents sorted by their similarity to the query */ public ObservableList<Document> evaluateQuery(String query){ HashMap<String, Integer> wordCount = TermExtractor.extractTerms(query); //Counter for word occurrence in the query ObservableList<Document> searchResult; searchResult = similarity.calculateSimilarity(wordCount); //Sort the ArrayList Collections.sort(searchResult, Collections.reverseOrder()); //Return return searchResult; } /** * A method to calculate the weights of the inserted terms */ public void calculateWeights() { weight.calculateWeights(); } }
package nl.ovapi.rid; public class Database { public final static String journeyQuery = "SELECT validdate||':'||journey.privatecode as key,journey.id,journeypatternref,timedemandgroupref,departuretime,(lowfloor or hasliftorramp) as wheelchairaccessible,o.privatecode as operatorcode,validdate::text,journey.privatecode,lineref,availabilityconditionref \n" + "FROM journey JOIN availabilityconditionday USING (availabilityconditionref) JOIN journeypattern as j ON (j.id = journeypatternref) JOIN route as r ON (r.id = routeref) JOIN line as l ON (l.id = lineref) JOIN operator as o ON (operatorref = o.id) "+ "WHERE isavailable = true AND validdate in (date 'yesterday',date 'today',date 'tomorrow') AND coalesce(monitored,true) = true AND journey.privatecode not like 'IFF:%';"; public final static String trainQuery = "SELECT validdate||':'||journey.privatecode as key,journey.id,journeypatternref,timedemandgroupref,departuretime,(lowfloor or hasliftorramp) as wheelchairaccessible,o.privatecode as operatorcode,validdate::text,journey.privatecode,lineref,blockref \n"+ "FROM journey JOIN availabilityconditionday USING (availabilityconditionref) JOIN journeypattern as j ON (j.id = journeypatternref) JOIN route as r ON (r.id = routeref) JOIN line as l ON (l.id = lineref) JOIN operator as o ON (operatorref = o.id)\n"+ "WHERE isavailable = true AND validdate in (date 'yesterday',date 'today',date 'tomorrow') AND coalesce(monitored,true) = true AND journey.privatecode like 'IFF:%'\n"+ "ORDER BY validdate,blockref,departuretime;"; public final static String journeyPatternQuery = "SELECT journeypatternref,pointorder,pointref,s.privatecode as operatorpointref,iswaitpoint,distancefromstartroute,isscheduled,split_part(coalesce(d.operator_id,dj.operator_id),':',2) as destinationcode,platformcode,directiontype,forboarding,foralighting FROM pointinjourneypattern JOIN stoppoint as s ON (s.id = pointref) LEFT JOIN destinationdisplay as d ON (d.id = destinationdisplayref) JOIN journeypattern as jp ON (jp.id = journeypatternref) LEFT JOIN destinationdisplay as dj ON (dj.id = jp.destinationdisplayref)"+ "WHERE journeypatternref in (SELECT DISTINCT journeypatternref FROM journey JOIN availabilityconditionday USING (availabilityconditionref) JOIN journeypattern as j ON (j.id = journeypatternref) JOIN route as r ON (r.id = routeref) JOIN line as l ON (l.id = lineref) WHERE isavailable = true AND validdate in (date 'yesterday',date 'today',date 'tomorrow') AND coalesce(monitored,true) = true) "+ "ORDER BY journeypatternref,pointorder;"; public final static String timepatternQuery = "SELECT timedemandgroupref,pointorder,totaldrivetime,stopwaittime FROM pointintimedemandgroup "+ "WHERE timedemandgroupref in (SELECT DISTINCT timedemandgroupref FROM journey JOIN availabilityconditionday USING (availabilityconditionref) LEFT JOIN journeypattern as j ON (j.id = journeypatternref) LEFT JOIN route as r ON (r.id = routeref) LEFT JOIN line as l ON (l.id = lineref) WHERE isavailable = true AND validdate in (date 'yesterday',date 'today',date 'tomorrow') AND coalesce(monitored,true) = true) "+ "ORDER BY timedemandgroupref,pointorder;"; public final static String stoppointQuery = "SELECT id,latitude,longitude,operator_id FROM stoppoint"; public final static String lineQuery = "SELECT id,operator_id FROM line"; public final static String gvbJourneyQuery = "select concat_ws(':',validdate,olddataownercode,oldlineplanningnumber,oldjourneynumber) as oldprivatecode,concat_ws(':',validdate,dataownercode,lineplanningnumber,journeynumber) as privatecode \n"+ "from gvb_journeynumber_mapping where validdate in (date 'yesterday', date 'today', date 'tomorrow') AND journeynumber != oldjourneynumber;;"; public final static String kv15Query = "SELECT dataownercode,messagecodedate,messagecodenumber,userstopcodes,messagepriority,messagetype,messagedurationtype,messagestarttime,messageendtime,messagecontent,reasontype,subreasontype,reasoncontent,effecttype,subeffecttype,effectcontent,advicetype,subadvicetype,advicecontent,messagetimestamp,measuretype,submeasuretype,measurecontent,lineplanningnumbers "+ "FROM kv15.stopmessage LEFT JOIN (SELECT dataownercode,messagecodedate,messagecodenumber,string_agg(userstopcode,';') as userstopcodes "+ " FROM kv15.stopmessage_userstopcode GROUP BY dataownercode,messagecodedate,messagecodenumber) as u USING (dataownercode,messagecodedate,messagecodenumber) "+ " LEFT JOIN (SELECT dataownercode,messagecodedate,messagecodenumber,string_agg(lineplanningnumber,';') as lineplanningnumbers "+ " FROM kv15.stopmessage_lineplanningnumber GROUP BY dataownercode,messagecodedate,messagecodenumber) as l USING (dataownercode,messagecodedate,messagecodenumber) "+ "WHERE ((messagetype != 'REMOVE' AND messageendtime is null) OR messageendtime > date 'now') and coalesce(isdeleted,false) = false AND (dataownercode = 'QBUZZ' OR messagepriority != 'COMMERCIAL')"; }
package org.febit.util; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import org.febit.bean.AccessFactory; import org.febit.bean.Setter; import org.febit.convert.Convert; import org.febit.convert.TypeConverter; import org.febit.lang.Defaults; import org.febit.lang.IdentityMap; import org.febit.util.agent.LazyAgent; /** * A Simple IoC. * * @author zqq90 */ public class Petite { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(Petite.class); protected static final Method[] EMPTY_METHODS = new Method[0]; protected static final Setter[] EMPTY_SETTERS = new Setter[0]; protected final TypeConverter defaultConverter; protected final IdentityMap<Class> replaceTypes; protected final Map<String, Object> beans; protected final Map<String, String> replaceNames; protected final PropsManager propsMgr; protected final GlobalBeanManager globalBeanMgr; protected final LazyAgent<PetiteGlobalBeanProvider[]> globalBeanProviders = new LazyAgent<PetiteGlobalBeanProvider[]>() { @Override protected PetiteGlobalBeanProvider[] create() { List<PetiteGlobalBeanProvider> providerList = CollectionUtil.read(ServiceLoader.load(PetiteGlobalBeanProvider.class)); PetiteGlobalBeanProvider[] providers = providerList.toArray(new PetiteGlobalBeanProvider[providerList.size()]); PriorityUtil.desc(providers); return providers; } }; protected boolean inited = false; protected Petite() { this.defaultConverter = new BeanTypeConverter(); this.propsMgr = new PropsManager(); this.globalBeanMgr = new GlobalBeanManager(); this.beans = new HashMap<>(); this.replaceTypes = new IdentityMap<>(); this.replaceNames = new HashMap<>(); } protected synchronized void _init() { if (inited) { return; } inited = true; addGlobalBean(this); initGlobals(); } protected void initGlobals() { //globals Object globalRaw = this.propsMgr.get("@global"); if (globalRaw == null) { return; } final String[] beanNames = StringUtil.toArray(globalRaw.toString()); if (beanNames.length == 0) { return; } //In case of circular reference, create all instance at once, then inject them. //create final Object[] instances = new Object[beanNames.length]; for (int i = 0; i < beanNames.length; i++) { String name = beanNames[i]; instances[i] = newInstance(resolveType(name)); addGlobalBean(instances[i]); } //inject for (int i = 0; i < instances.length; i++) { doInject(beanNames[i], instances[i]); } } public String resolveBeanName(Object bean) { if (bean instanceof Class) { return ((Class) bean).getName(); } return bean.getClass().getName(); } protected Class getReplacedType(Class type) { final Class replaceWith = replaceTypes.get(type); return replaceWith == null ? type : replaceWith; } protected String getReplacedName(String name) { final String replaceWith = replaceNames.get(name); return replaceWith == null ? name : replaceWith; } public void replace(Class replace, Class with) { this.replaceTypes.put(replace, with); this.replace(replace.getName(), with.getName()); } public void replace(String replace, String with) { this.replaceNames.put(replace, with); this.propsMgr.putProp(replace + ".@extends", with); } @SuppressWarnings("unchecked") public <T> T get(Class<T> type) { T bean = this.globalBeanMgr.get(type); if (bean != null) { return bean; } return (T) get(type.getName()); } public Object get(final String name) { Object bean = this.beans.get(name); if (bean != null) { return bean; } return createIfAbsent(name); } @SuppressWarnings("unchecked") public <T> T create(Class<T> type) { return (T) create(type.getName()); } public Object create(final String name) { Object bean; Class type = resolveType(name); bean = newInstance(type); inject(name, bean); return bean; } protected synchronized Object createIfAbsent(String name) { Object bean = this.beans.get(name); if (bean != null) { return bean; } bean = create(name); this.beans.put(name, bean); return bean; } protected Class resolveType(String name) { String type; name = getReplacedName(name); do { type = name; name = (String) this.propsMgr.get(name + ".@class"); } while (name != null); try { return ClassUtil.getClass(type); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } } protected Object newInstance(Class type) { type = getReplacedType(type); Object bean = getFreshGlobalBeanInstance(type); if (bean != null) { return bean; } return ClassUtil.newInstance(getReplacedType(type)); } protected Object getFreshGlobalBeanInstance(Class type) { for (PetiteGlobalBeanProvider globalBeanProvider : this.globalBeanProviders.get()) { if (globalBeanProvider.isSupportType(type)) { return globalBeanProvider.newInstance(type, this); } } return null; } public void inject(Object bean) { inject(resolveBeanName(bean), bean); } public void inject(final String name, final Object bean) { doInject(name, bean); } protected void doInject(final String name, final Object bean) { final Map<String, Setter> setters = AccessFactory.resolveSetters(bean.getClass()); final Map<String, Object> params = this.propsMgr.resolveParams(name); //Setters for (Map.Entry<String, Setter> entry : setters.entrySet()) { String param = entry.getKey(); Setter setter = entry.getValue(); //inject param Object paramValue = params.get(param); if (paramValue != null) { if (paramValue instanceof String) { paramValue = convert((String) paramValue, setter.getPropertyType()); } setter.set(bean, paramValue); continue; } //global Object comp = this.globalBeanMgr.get(setter.getPropertyType()); if (comp != null) { setter.set(bean, comp); continue; } } //Init for (Method method : ClassUtil.getAccessableMemberMethods(bean.getClass())) { if (method.getAnnotation(Petite.Init.class) == null) { continue; } final Class[] argTypes = method.getParameterTypes(); final Object[] args; if (argTypes.length == 0) { args = Defaults.EMPTY_OBJECTS; } else { args = new Object[argTypes.length]; for (int i = 0; i < argTypes.length; i++) { args[i] = this.globalBeanMgr.get(argTypes[i]); } } try { method.invoke(bean, args); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { //shouldn't be throw new RuntimeException(ex); } } } public void add(Object bean) { this.beans.put(resolveBeanName(bean), bean); } public void add(Class type, Object bean) { this.beans.put(resolveBeanName(type), bean); } public void add(String name, Object bean) { this.beans.put(name, bean); } public void regist(Object bean) { regist(resolveBeanName(bean), bean); } public void regist(String name, Object bean) { inject(name, bean); this.beans.put(name, bean); } protected Object convert(String string, Class cls) { return Convert.convert(string, cls, defaultConverter); } protected void addProps(Props props, Map<String, ?> parameters) { this.propsMgr.addProps(props, parameters); } public Object getProps(String name) { return this.propsMgr.get(name); } protected void addGlobalBean(Object bean) { this.globalBeanMgr.add(bean); } protected boolean isGlobalType(Class type) { for (PetiteGlobalBeanProvider globalBeanProvider : this.globalBeanProviders.get()) { if (globalBeanProvider.isSupportType(type)) { return true; } } return false; } @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public static @interface Init { } public static Builder builder() { return new Builder(); } public static class Builder { protected final Petite petite; protected Builder() { petite = new Petite(); } public Builder addProps(Props props) { this.petite.addProps(props, null); return this; } public Builder addProps(Props props, Map<String, ?> parameters) { this.petite.addProps(props, parameters); return this; } public Builder addProps(Map<String, ?> parameters) { this.petite.addProps(null, parameters); return this; } public Builder addGlobalBean(Object bean) { this.petite.addGlobalBean(bean); return this; } public Petite build() { petite._init(); return petite; } } protected class GlobalBeanManager { protected final IdentityMap<Object> container = new IdentityMap<>(); //Store immature beans. protected final IdentityMap internalCache = new IdentityMap(64); public void add(Object bean) { //regist all impls Class rootType = bean.getClass(); for (Class cls : ClassUtil.impls(bean)) { //only regist spec types if (cls != rootType && !Petite.this.isGlobalType(cls)) { continue; } this.container.put(cls, bean); } } public <T> T get(Class<T> type) { T bean = (T) this.container.get(type); if (bean != null) { return bean; } if (!Petite.this.isGlobalType(type)) { return null; } return createIfAbsent(type); } /** * . * <p> * NOTE: synchronized * </p> * * @param <T> * @param type * @return */ protected synchronized <T> T createIfAbsent(final Class<T> type) { T target; if ((target = (T) container.get(type)) != null) { return target; } if ((target = (T) internalCache.get(type)) != null) { return target; } Class replacedType = getReplacedType(type); if (replacedType != type) { if ((target = (T) container.get(replacedType)) != null) { return (T) container.putIfAbsent(type, target); } if ((target = (T) internalCache.get(replacedType)) != null) { return (T) internalCache.putIfAbsent(type, target); } } target = (T) Petite.this.newInstance(replacedType); internalCache.put(type, target); if (replacedType != type) { internalCache.put(replacedType, target); } Petite.this.inject(target.getClass().getName(), target); container.put(type, target); internalCache.remove(type); if (replacedType != type) { container.put(replacedType, target); internalCache.remove(replacedType); } add(target); return target; } } protected static final class Entry { protected final String name; protected final Object value; protected final Entry next; protected Entry(String name, Object value, Entry next) { this.name = name; this.value = value; this.next = next; } } protected static class PropsManager { protected final Map<String, Object> datas; protected final Map<String, Entry> entrys; public PropsManager() { this.datas = new HashMap<>(); this.entrys = new HashMap<>(); } public Object get(String key) { return this.datas.get(key); } public void putProp(String key, Object value) { this.datas.put(key, value); int index = key.lastIndexOf('.'); int index2; if (index > 0 && (index2 = index + 1) < key.length() && key.charAt(index2) != '@') { String beanName = key.substring(0, index); this.entrys.put(beanName, new Entry(key.substring(index2), value, this.entrys.get(beanName))); } } public void addProps(Props props, Map<String, ?> parameters) { if (props == null) { props = new Props(); } final Map<String, Object> extras; if (parameters != null) { extras = new HashMap<>(); for (Map.Entry<String, ?> entry : parameters.entrySet()) { String key = entry.getKey(); if (key == null) { continue; } key = key.trim(); Object value = entry.getValue(); if (value instanceof String) { int len = key.length(); if (len > 0) { if (key.charAt(len - 1) == '+') { props.append(key.substring(0, len - 1).trim(), (String) value); } else { props.set(key, (String) value); } } } else { extras.put(key, value); } } } else { extras = null; } addProps(props); if (extras != null) { addProps(extras); } } public void addProps(Props props) { if (props == null) { return; } for (String key : props.keySet()) { putProp(key, props.get(key)); } } public void addProps(Map<String, Object> map) { if (map == null) { return; } for (Map.Entry<String, Object> entrySet : map.entrySet()) { putProp(entrySet.getKey(), entrySet.getValue()); } } public Map<String, Object> resolveParams(String key) { final LinkedList<String> keys = new LinkedList<>(); do { keys.addFirst(key); key = (String) this.datas.get(key + ".@class"); } while (key != null); final Map<String, Object> params = new HashMap<>(); final Set<String> injected = new HashSet<>(); for (String beanName : keys) { resolveParams(beanName, params, injected); } return params; } protected void resolveParams(final String beanName, final Map<String, Object> params, final Set<String> injected) { if (injected.contains(beanName)) { return; } injected.add(beanName); //inject @extends first Object extendProfiles = datas.get(beanName.concat(".@extends")); if (extendProfiles != null) { for (String profile : StringUtil.toArray(String.valueOf(extendProfiles))) { resolveParams(profile, params, injected); } } Entry entry = entrys.get(beanName); while (entry != null) { params.put(entry.name, entry.value); entry = entry.next; } } } protected class BeanTypeConverter implements TypeConverter { @Override public Object convert(String raw, Class type) { if (raw == null) { return null; } if (Object[].class.isAssignableFrom(type)) { String[] names = StringUtil.toArrayExcludeCommit(raw); Object[] beans = (Object[]) Array.newInstance(type.getComponentType(), names.length); for (int i = 0; i < names.length; i++) { beans[i] = Petite.this.get(names[i]); } return beans; } return Petite.this.get(raw); } } }
package org.jenetics; import static org.jenetics.util.object.Verify; import static org.jenetics.util.object.eq; import static org.jenetics.util.object.hashCodeOf; import static org.jenetics.util.object.nonNull; import java.util.Iterator; import javolution.lang.Immutable; import javolution.lang.Realtime; import javolution.text.Text; import javolution.xml.XMLFormat; import javolution.xml.XMLSerializable; import javolution.xml.stream.XMLStreamException; import org.jenetics.util.Array; import org.jenetics.util.Function; import org.jenetics.util.Factory; import org.jenetics.util.ISeq; import org.jenetics.util.Seq; import org.jenetics.util.Verifiable; import org.jenetics.util.object; public final class Genotype<T extends Gene<?, T>> implements Factory<Genotype<T>>, Iterable<Chromosome<T>>, Verifiable, XMLSerializable, Realtime, Immutable { private static final long serialVersionUID = 2L; private final ISeq<Chromosome<T>> _chromosomes; private final int _ngenes; //Caching isValid value. private volatile Boolean _valid = null; private Genotype(final ISeq<Chromosome<T>> chromosomes, final int ngenes) { assert(chromosomes != null); assert(ngenes(chromosomes) == ngenes); _chromosomes = chromosomes; _ngenes = ngenes; } private static int ngenes(final Seq<? extends Chromosome<?>> chromosomes) { int ngenes = 0; for (int i = chromosomes.length(); --i >= 0;) { ngenes += chromosomes.get(i).length(); } return ngenes; } /** * Return the chromosome at the given index. It is guaranteed, that the * returned chromosome is not null. * * @param index Chromosome index. * @return The Chromosome. * @throws IndexOutOfBoundsException if (index < 0 || index >= _length). */ public Chromosome<T> getChromosome(final int index) { assert(_chromosomes != null); assert(_chromosomes.get(index) != null); return _chromosomes.get(index); } /** * Return the first chromosome. * * @return The first chromosome. */ public Chromosome<T> getChromosome() { assert(_chromosomes != null); assert(_chromosomes.get(0) != null); return _chromosomes.get(0); } /** * Return the first {@link Gene} of the first {@link Chromosome} of this * {@code Genotype}. * * @return the first {@link Gene} of the first {@link Chromosome} of this * {@code Genotype}. */ public T getGene() { assert(_chromosomes != null); assert(_chromosomes.get(0) != null); return _chromosomes.get(0).getGene(); } public ISeq<Chromosome<T>> toSeq() { return _chromosomes; } @Override public Iterator<Chromosome<T>> iterator() { return _chromosomes.iterator(); } /** * Getting the number of _chromosomes of this genotype. * * @return number of _chromosomes. */ public int length() { return _chromosomes.length(); } /** * Return the number of genes this genotype consists of. This is the sum of * the number of genes of the genotype chromosomes. * * @return Return the number of genes this genotype consists of. */ public int getNumberOfGenes() { return _ngenes; } /** * Test if this genotype is valid. A genotype is valid if all its * {@link Chromosome}s are valid. * * @return true if this genotype is valid, false otherwise. */ @Override public boolean isValid() { if (_valid == null) { _valid = _chromosomes.foreach(Verify) == -1; } return _valid; } /** * Return a new, random genotype by creating new, random chromosomes (calling * the {@link Chromosome#newInstance()} method) from the chromosomes of this * genotype. */ @Override public Genotype<T> newInstance() { final Array<Chromosome<T>> chromosomes = new Array<>(length()); for (int i = 0; i < length(); ++i) { chromosomes.set(i, _chromosomes.get(i).newInstance()); } return new Genotype<>(chromosomes.toISeq(), _ngenes); } Genotype<T> newInstance(final ISeq<Chromosome<T>> chromosomes) { return new Genotype<>(chromosomes, _ngenes); } @Override public int hashCode() { return hashCodeOf(getClass()).and(_chromosomes).value(); } @Override public boolean equals(final Object o) { if (o == this) { return true; } if (!(o instanceof Genotype<?>)) { return false; } final Genotype<?> gt = (Genotype<?>)o; return eq(_chromosomes, gt._chromosomes); } @Override public Text toText() { return new Text(_chromosomes.toString()); } @Override public String toString() { return _chromosomes.toString(); } /** * Return a converter which access the chromosome array of this genotype. */ public static <T extends Gene<?, T>> Function<Genotype<T>, ISeq<Chromosome<T>>> Chromosomes() { return new Function<Genotype<T>, ISeq<Chromosome<T>>>() { @Override public ISeq<Chromosome<T>> apply(final Genotype<T> value) { return value.toSeq(); } }; } /** * Return a converter which access the chromosome with the given index of * this genotype. */ public static <T extends Gene<?, T>> Function<Genotype<T>, Chromosome<T>> Chromosome(final int index) { return new Function<Genotype<T>, Chromosome<T>>() { @Override public Chromosome<T> apply(final Genotype<T> value) { return value.getChromosome(index); } }; } /** * Return a converter which access the first chromosome of this genotype. */ public static <T extends Gene<?, T>> Function<Genotype<T>, Chromosome<T>> Chromosome() { return new Function<Genotype<T>, Chromosome<T>>() { @Override public Chromosome<T> apply(final Genotype<T> value) { return value.getChromosome(); } }; } public static <G extends Gene<?, G>> Genotype<G> valueOf( final ISeq<? extends Chromosome<G>> chromosomes ) { nonNull(chromosomes, "Chromosomes"); if (chromosomes.length() == 0) { throw new IllegalArgumentException("Chromosomes must be given."); } return new Genotype<>( chromosomes.upcast(chromosomes), ngenes(chromosomes) ); } /** * Create a new Genotype from a given {@link Chromosome} * * @param chromosome The <code>Chromosome</code> array the <code>Genotype</code> * consists of. * @throws NullPointerException if <code>chromosome</code> is null. */ public static <G extends Gene<?, G>> Genotype<G> valueOf( final Chromosome<G> chromosome ) { nonNull(chromosome, "Chromosome"); return new Genotype<>( new Array<>(chromosome).toISeq(), chromosome.length() ); } public static <G extends Gene<?, G>> Genotype<G> valueOf( final Chromosome<G> ch1, final Chromosome<G> ch2 ) { nonNull(ch1, "Chromosome 1"); nonNull(ch2, "Chromosome 2"); return new Genotype<>( new Array<>(ch1, ch2).toISeq(), ch1.length() + ch2.length() ); } public static <G extends Gene<?, G>> Genotype<G> valueOf( final Chromosome<G> ch1, final Chromosome<G> ch2, final Chromosome<G> ch3 ) { nonNull(ch1, "Chromosome 1"); nonNull(ch2, "Chromosome 2"); nonNull(ch3, "Chromosome 3"); return new Genotype<>( new Array<>(ch1, ch2, ch3).toISeq(), ch1.length() + ch2.length() + ch3.length() ); } public static <G extends Gene<?, G>> Genotype<G> valueOf( final Chromosome<G> ch1, final Chromosome<G> ch2, final Chromosome<G> ch3, final Chromosome<G> ch4 ) { nonNull(ch1, "Chromosome 1"); nonNull(ch2, "Chromosome 2"); nonNull(ch3, "Chromosome 3"); nonNull(ch4, "Chromosome 4"); return new Genotype<>( new Array<>(ch1, ch2, ch3, ch4).toISeq(), ch1.length() + ch2.length() + ch3.length() + ch4.length() ); } @SafeVarargs public static <G extends Gene<?, G>> Genotype<G> valueOf( final Chromosome<G>... chromosomes ) { final Array<Chromosome<G>> array = new Array<>(chromosomes); if (array.foreach(object.NonNull) != -1) { throw new NullPointerException("One of the given chromosomes is null."); } return valueOf(array.toISeq()); } @SuppressWarnings({ "unchecked", "rawtypes"}) static final XMLFormat<Genotype> XML = new XMLFormat<Genotype>(Genotype.class) { private static final String LENGTH = "length"; private static final String NGENES = "ngenes"; @Override public Genotype newInstance( final Class<Genotype> cls, final InputElement xml ) throws XMLStreamException { final int length = xml.getAttribute(LENGTH, 0); final int ngenes = xml.getAttribute(NGENES, 0); final Array<Chromosome> chromosomes = new Array<>(length); for (int i = 0; i < length; ++i) { final Chromosome<?> c = xml.getNext(); chromosomes.set(i, c); } return new Genotype(chromosomes.toISeq(), ngenes); } @Override public void write(final Genotype gt, final OutputElement xml) throws XMLStreamException { xml.setAttribute(LENGTH, gt.length()); xml.setAttribute(NGENES, gt.getNumberOfGenes()); for (int i = 0; i < gt.length(); ++i) { xml.add(gt._chromosomes.get(i)); } } @Override public void read(final InputElement xml, final Genotype gt) { } }; }
package org.opennars.main; import org.apache.commons.lang3.StringUtils; import org.opennars.entity.*; import org.opennars.interfaces.Timable; import org.opennars.interfaces.pub.Reasoner; import org.opennars.io.ConfigReader; import org.opennars.io.Narsese; import org.opennars.io.Narsese.InvalidInputException; import org.opennars.io.Symbols; import org.opennars.io.events.AnswerHandler; import org.opennars.io.events.EventEmitter; import org.opennars.io.events.EventEmitter.EventObserver; import org.opennars.io.events.Events; import org.opennars.io.events.Events.CyclesEnd; import org.opennars.io.events.Events.CyclesStart; import org.opennars.io.events.OutputHandler; import org.opennars.io.events.OutputHandler.ERR; import org.opennars.language.Inheritance; import org.opennars.language.SetExt; import org.opennars.language.Tense; import org.opennars.language.Term; import org.opennars.operator.Operator; import org.opennars.plugin.Plugin; import org.opennars.plugin.perception.SensoryChannel; import org.opennars.storage.LevelBag; import org.opennars.storage.Memory; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /** * Non-Axiomatic Reasoner * * Instances of this represent a reasoner connected to a Memory, and set of Input and Output channels. * * All state is contained within Memory. A Nar is responsible for managing I/O channels and executing * memory operations. It executesa series sof cycles in two possible modes: * * step mode - controlled by an outside system, such as during debugging or testing * * thread mode - runs in a pausable closed-loop at a specific maximum framerate. */ public class Nar extends SensoryChannel implements Reasoner, Serializable, Runnable { public Parameters narParameters = new Parameters(); /* System clock, relatively defined to guarantee the repeatability of behaviors */ private Long cycle = new Long(0); /** * The information about the version and date of the project. */ public static final String VERSION = "Open-NARS v1.6.6pre2"; /** * The project web sites. */ public static final String WEBSITE = " Open-NARS website: http://code.google.com/p/open-org.opennars/ \n" + " NARS website: http://sites.google.com/site/narswang/ \n" + " Github website: http://github.com/opennars/ \n" + " IRC: http://webchat.freenode.net/?channels=org.opennars \n"; private transient Thread[] threads = null; protected transient Map<Term,SensoryChannel> sensoryChannels = new HashMap<>(); public void addSensoryChannel(final String term, final SensoryChannel channel) { try { sensoryChannels.put(new Narsese(this).parseTerm(term), channel); } catch (final InvalidInputException ex) { Logger.getLogger(Nar.class.getName()).log(Level.SEVERE, null, ex); throw new IllegalStateException("Could not add sensory channel.", ex); } } public void SaveToFile(final String name) throws IOException { final FileOutputStream outStream = new FileOutputStream(name); final ObjectOutputStream stream = new ObjectOutputStream(outStream); stream.writeObject(this); outStream.close(); } public static Nar LoadFromFile(final String name) throws IOException, ClassNotFoundException, IllegalAccessException, ParseException, ParserConfigurationException, SAXException, NoSuchMethodException, InstantiationException, InvocationTargetException { final FileInputStream inStream = new FileInputStream(name); final ObjectInputStream stream = new ObjectInputStream(inStream); final Nar ret = (Nar) stream.readObject(); ret.memory.event = new EventEmitter(); ret.plugins = new ArrayList<>(); ret.sensoryChannels = new HashMap<>(); List<Plugin> pluginsToAdd = ConfigReader.loadParamsFromFileAndReturnPlugins(ret.usedConfigFilePath, ret, ret.narParameters); for(Plugin p : pluginsToAdd) { ret.addPlugin(p); } return ret; } long minCyclePeriodMS; /** * The name of the reasoner */ protected String name; /** * The memory of the reasoner */ public final Memory memory; public static class Lock extends Object implements Serializable { } //Because AtomicInteger/Double ot supported by teavm public static class PortableInteger implements Serializable { public PortableInteger(){} final Lock lock = new Lock(); int VAL = 0; public PortableInteger(final int VAL){synchronized(lock){this.VAL = VAL;}} public void set(final int VAL){synchronized(lock){this.VAL = VAL;}} public int get() {return this.VAL;} public float floatValue() {return (float)this.VAL;} public float doubleValue() {return (float)this.VAL;} public int intValue() {return this.VAL;} public int incrementAndGet(){int ret = 0; synchronized(lock){this.VAL++; ret=this.VAL;} return ret;} } public static class PortableDouble implements Serializable { final Lock lock = new Lock(); public PortableDouble(){} double VAL = 0; public PortableDouble(final double VAL){synchronized(lock){this.VAL = VAL;}} public void set(final double VAL){synchronized(lock){this.VAL = VAL;}} public double get() {return this.VAL;} public float floatValue() {return (float)this.VAL;} public float doubleValue() {return (float)this.VAL;} public int intValue() {return (int)this.VAL;} } /*Nar Parameters which can be changed during runtime.*/ public class RuntimeParameters implements Serializable { public final PortableInteger threadsAmount = new PortableInteger(1); public final PortableInteger noiseLevel = new PortableInteger(100); public final PortableDouble conceptForgetDurations = new PortableDouble(narParameters.CONCEPT_FORGET_DURATIONS); public final PortableDouble termLinkForgetDurations = new PortableDouble(narParameters.TERMLINK_FORGET_DURATIONS); public final PortableDouble taskLinkForgetDurations = new PortableDouble(narParameters.TASKLINK_FORGET_DURATIONS); public final PortableDouble eventForgetDurations = new PortableDouble(narParameters.EVENT_FORGET_DURATIONS); public final PortableDouble projectionDecay = new PortableDouble(narParameters.PROJECTION_DECAY); public RuntimeParameters() { } } public final RuntimeParameters param; public class PluginState implements Serializable { final public Plugin plugin; boolean enabled = false; public PluginState(final Plugin plugin) { this(plugin,true); } public PluginState(final Plugin plugin, final boolean enabled) { this.plugin = plugin; setEnabled(enabled); } public void setEnabled(final boolean enabled) { if (this.enabled == enabled) return; plugin.setEnabled(Nar.this, enabled); this.enabled = enabled; emit(Events.PluginsChange.class, plugin, enabled); } public boolean isEnabled() { return enabled; } } protected transient List<PluginState> plugins = new ArrayList<>(); //was CopyOnWriteArrayList /** Flag for running continuously */ private boolean running = false; /** used by stop() to signal that a running loop should be interrupted */ private boolean stopped = false; private boolean threadYield; public static final String DEFAULTCONFIG_FILEPATH = "../opennars/src/main/config/defaultConfig.xml"; public Nar(long narId) throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { this(narId, DEFAULTCONFIG_FILEPATH); } public String usedConfigFilePath = ""; // constructs the NAR and loads a config from the filepath public Nar(long narId, String configFilePath) throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, SAXException, IllegalAccessException, ParseException, ClassNotFoundException { List<Plugin> pluginsToAdd = ConfigReader.loadParamsFromFileAndReturnPlugins(configFilePath, this, this.narParameters); final Memory m = new Memory(this.narParameters, new RuntimeParameters(), new LevelBag(narParameters.CONCEPT_BAG_LEVELS, narParameters.CONCEPT_BAG_SIZE, this.narParameters), new LevelBag<>(narParameters.NOVEL_TASK_BAG_LEVELS, narParameters.NOVEL_TASK_BAG_SIZE, this.narParameters), new LevelBag<>(narParameters.SEQUENCE_BAG_LEVELS, narParameters.SEQUENCE_BAG_SIZE, this.narParameters), new LevelBag<>(narParameters.OPERATION_BAG_LEVELS, narParameters.OPERATION_BAG_SIZE, this.narParameters)); this.memory = m; this.memory.narId = narId; this.param = m.param; this.usedConfigFilePath = configFilePath; for(Plugin p : pluginsToAdd) { //adding after memory is constructed, as memory depends on the loaded params!! this.addPlugin(p); } } public Nar() throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { this(java.util.UUID.randomUUID().getLeastSignificantBits(), DEFAULTCONFIG_FILEPATH); } /** * Reset the system with an empty memory and reset clock. Called locally and * from {@link NARControls}. */ public void reset() { memory.reset(); } /** * Generally the text will consist of Task's to be parsed in Narsese, but * may contain other commands recognized by the system. The creationTime * will be set to the current memory cycle time, but may be processed by * memory later according to the length of the input queue. */ private boolean addMultiLineInput(final String text) { if(text.contains("\n")) { final String[] lines = text.split("\n"); for(final String s : lines) { addInput(s); if(!running) { this.cycle(); } } return true; } return false; } private boolean addCommand(final String text) { if(text.startsWith("**")) { this.reset(); return true; } else if(text.startsWith("*decisionthreshold=")) { final Double value = Double.valueOf(text.split("decisionthreshold=")[1]); narParameters.DECISION_THRESHOLD = value.floatValue(); return true; } else if(text.startsWith("*volume=")) { final Integer value = Integer.valueOf(text.split("volume=")[1]); param.noiseLevel.set(value); return true; } if(StringUtils.isNumeric(text)) { final Integer retVal = Integer.parseInt(text); if(!running) { for(int i=0;i<retVal;i++) { this.cycle(); } } return true; } else { return false; } } public void addInput(String text) { text = text.trim(); final Narsese narsese = new Narsese(this); if(addMultiLineInput(text)) { return; } //Ignore any input that is just a comment if(text.startsWith("\'") || text.startsWith("//") ||text.trim().length() <= 0) return; if(addCommand(text)) { return; } final Task task; try { task = narsese.parseTask(text); } catch (final InvalidInputException e) { throw new IllegalStateException("Invalid input: " + text, e); } //check if it should go to a sensory channel instead: final Term t = task.getTerm(); if(t != null && t instanceof Inheritance) { final Term predicate = ((Inheritance) t).getPredicate(); if(this.sensoryChannels.containsKey(predicate)) { final Inheritance inh = (Inheritance) task.sentence.term; final SetExt subj = (SetExt) inh.getSubject(); //map to pei's -1 to 1 indexing schema if(subj.term[0].term_indices == null) { final String variable = subj.toString().split("\\[")[0]; final String[] vals = subj.toString().split("\\[")[1].split("\\]")[0].split(","); final double height = Double.parseDouble(vals[0]); final double width = Double.parseDouble(vals[1]); final int wval = (int) Math.round((width+1.0f)/2.0f*(this.sensoryChannels.get(predicate).width-1)); final int hval = (int) Math.round(((height+1.0f)/2.0f*(this.sensoryChannels.get(predicate).height-1))); final String ev = task.sentence.isEternal() ? " " : " :|: "; final String newInput = "<"+variable+"["+hval+","+wval+"]} --> " + predicate + ">" + task.sentence.punctuation + ev + task.sentence.truth.toString(); this.emit(OutputHandler.IN.class, task); this.addInput(newInput); return; } this.sensoryChannels.get(predicate).addInput(task, this); return; } } //else input into NARS directly: this.memory.inputTask(this, task); } public void addInputFile(final String s) { try (final BufferedReader br = new BufferedReader(new FileReader(s))) { String line; while ((line = br.readLine()) != null) { if(!line.isEmpty()) { this.addInput(line); } } } catch (final IOException ex) { Logger.getLogger(Nar.class.getName()).log(Level.SEVERE, null, ex); throw new IllegalStateException("Could not open specified file", ex); } } /** gets a concept if it exists, or returns null if it does not */ public Concept concept(final String concept) throws InvalidInputException { return memory.concept(new Narsese(this).parseTerm(concept)); } public Nar ask(final String termString, final AnswerHandler answered) throws InvalidInputException { final Sentence sentenceForNewTask = new Sentence( new Narsese(this).parseTerm(termString), Symbols.QUESTION_MARK, null, new Stamp(this, memory, Tense.Eternal)); final BudgetValue budget = new BudgetValue( narParameters.DEFAULT_QUESTION_PRIORITY, narParameters.DEFAULT_QUESTION_DURABILITY, 1, narParameters); final Task t = new Task(sentenceForNewTask, budget, Task.EnumType.INPUT); addInput(t, this); if (answered!=null) { answered.start(t, this); } return this; } public Nar askNow(final String termString, final AnswerHandler answered) throws InvalidInputException { final Sentence sentenceForNewTask = new Sentence( new Narsese(this).parseTerm(termString), Symbols.QUESTION_MARK, null, new Stamp(this, memory, Tense.Present)); final BudgetValue budgetForNewTask = new BudgetValue( narParameters.DEFAULT_QUESTION_PRIORITY, narParameters.DEFAULT_QUESTION_DURABILITY, 1, narParameters); final Task t = new Task(sentenceForNewTask, budgetForNewTask, Task.EnumType.INPUT); addInput(t, this); if (answered!=null) { answered.start(t, this); } return this; } public Nar addInput(final Task t, final Timable time) { this.memory.inputTask(this, t); return this; } /** attach event handler */ public void on(final Class c, final EventObserver o) { memory.event.on(c, o); } /** remove event handler */ public void off(final Class c, final EventObserver o) { memory.event.on(c, o); } /** set an event handler. useful for multiple events. */ public void event(final EventObserver e, final boolean enabled, final Class... events) { memory.event.set(e, enabled, events); } public void addPlugin(final Plugin p) { if(p instanceof SensoryChannel) { this.addSensoryChannel(((SensoryChannel) p).getName(), (SensoryChannel) p); } if (p instanceof Operator) { memory.addOperator((Operator)p); } final PluginState ps = new PluginState(p); plugins.add(ps); emit(Events.PluginsChange.class, p, null); } public void removePlugin(final PluginState ps) { if (plugins.remove(ps)) { final Plugin p = ps.plugin; if (p instanceof Operator) { memory.removeOperator((Operator)p); } if (p instanceof SensoryChannel) { sensoryChannels.remove(p); } //TODO sensory channels can be plugins ps.setEnabled(false); emit(Events.PluginsChange.class, null, p); } } public List<PluginState> getPlugins() { return Collections.unmodifiableList(plugins); } public void start(final long minCyclePeriodMS) { this.minCyclePeriodMS = minCyclePeriodMS; if (threads == null) { threads = new Thread[this.param.threadsAmount.get()]; for(int i=0;i<this.param.threadsAmount.get();i++) { threads[i] = new Thread(this, "Inference"+i); threads[i].start(); } } running = true; } /** * Stop the inference process, killing its thread. */ public void stop() { if (threads!=null) { for(Thread thread : threads) { thread.interrupt(); } threads = null; } stopped = true; running = false; } /** Execute a fixed number of cycles.*/ public void cycles(final int cycles) { memory.allowExecution = true; emit(CyclesStart.class); final boolean wasRunning = running; running = true; stopped = false; for(int i=0;i<cycles;i++) { cycle(); } running = wasRunning; emit(CyclesEnd.class); } /** Main loop executed by the Thread. Should not be called directly. */ @Override public void run() { stopped = false; while (running && !stopped) { emit(CyclesStart.class); cycle(); emit(CyclesEnd.class); if (minCyclePeriodMS > 0) { try { Thread.sleep(minCyclePeriodMS); } catch (final InterruptedException e) { } } else if (threadYield) { Thread.yield(); } } } public void emit(final Class c, final Object... o) { memory.event.emit(c, o); } /** * A frame, consisting of one or more Nar memory cycles */ public void cycle() { try { memory.cycle(this); synchronized (cycle) { cycle++; } } catch (final Exception e) { if(MiscFlags.SHOW_REASONING_ERRORS) { emit(ERR.class, e); } throw e; } } @Override public String toString() { return memory.toString(); } public long time() { return cycle; } public boolean isRunning() { return running; } public long getMinCyclePeriodMS() { return minCyclePeriodMS; } /** When b is true, Nar will call Thread.yield each run() iteration that minCyclePeriodMS==0 (no delay). * This is for improving program responsiveness when Nar is run with no delay. */ public void setThreadYield(final boolean b) { this.threadYield = b; } }
package org.opennars.main; import org.apache.commons.lang3.StringUtils; import org.opennars.entity.*; import org.opennars.interfaces.Timable; import org.opennars.interfaces.pub.Reasoner; import org.opennars.io.ConfigReader; import org.opennars.io.Narsese; import org.opennars.io.Narsese.InvalidInputException; import org.opennars.io.Symbols; import org.opennars.io.events.AnswerHandler; import org.opennars.io.events.EventEmitter; import org.opennars.io.events.EventEmitter.EventObserver; import org.opennars.io.events.Events; import org.opennars.io.events.Events.CyclesEnd; import org.opennars.io.events.Events.CyclesStart; import org.opennars.io.events.OutputHandler.ERR; import org.opennars.language.Inheritance; import org.opennars.language.SetExt; import org.opennars.language.Tense; import org.opennars.language.Term; import org.opennars.operator.Operator; import org.opennars.plugin.Plugin; import org.opennars.plugin.perception.SensoryChannel; import org.opennars.storage.LevelBag; import org.opennars.storage.Memory; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.text.ParseException; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import org.opennars.plugin.mental.Emotions; import org.opennars.plugin.mental.InternalExperience; /** * Non-Axiomatic Reasoner * * Instances of this represent a reasoner connected to a Memory, and set of Input and Output channels. * * All state is contained within Memory. A Nar is responsible for managing I/O channels and executing * memory operations. It executesa series sof cycles in two possible modes: * * step mode - controlled by an outside system, such as during debugging or testing * * thread mode - runs in a pausable closed-loop at a specific maximum framerate. */ public class Nar extends SensoryChannel implements Reasoner, Serializable, Runnable { public Parameters narParameters = new Parameters(); /* System clock, relatively defined to guarantee the repeatability of behaviors */ private Long cycle = new Long(0); /** * The information about the version and date of the project. */ public static final String VERSION = "Open-NARS v1.6.6pre3"; /** * The project web sites. */ public static final String WEBSITE = " Open-NARS website: http://code.google.com/p/open-org.opennars/ \n" + " NARS website: http://sites.google.com/site/narswang/ \n" + " Github website: http://github.com/opennars/ \n" + " IRC: http://webchat.freenode.net/?channels=org.opennars \n"; private transient Thread[] threads = null; protected transient Map<Term,SensoryChannel> sensoryChannels = new HashMap<>(); public void addSensoryChannel(final String term, final SensoryChannel channel) { try { sensoryChannels.put(new Narsese(this).parseTerm(term), channel); } catch (final InvalidInputException ex) { Logger.getLogger(Nar.class.getName()).log(Level.SEVERE, null, ex); throw new IllegalStateException("Could not add sensory channel.", ex); } } public void SaveToFile(final String name) throws IOException { final FileOutputStream outStream = new FileOutputStream(name); final ObjectOutputStream stream = new ObjectOutputStream(outStream); stream.writeObject(this); outStream.close(); } public static Nar LoadFromFile(final String name) throws IOException, ClassNotFoundException, IllegalAccessException, ParseException, ParserConfigurationException, SAXException, NoSuchMethodException, InstantiationException, InvocationTargetException { final FileInputStream inStream = new FileInputStream(name); final ObjectInputStream stream = new ObjectInputStream(inStream); final Nar ret = (Nar) stream.readObject(); ret.memory.event = new EventEmitter(); ret.plugins = new ArrayList<>(); ret.sensoryChannels = new HashMap<>(); List<Plugin> pluginsToAdd = ConfigReader.loadParamsFromFileAndReturnPlugins(ret.loadedFromResources, ret.usedConfigFilePath, ret, ret.narParameters); for(Plugin p : pluginsToAdd) { ret.addPlugin(p); } return ret; } volatile long minCyclePeriodMS; /** * The name of the reasoner */ protected String name; /** * The memory of the reasoner */ public final Memory memory; public class PluginState implements Serializable { final public Plugin plugin; boolean enabled = false; public PluginState(final Plugin plugin) { this(plugin,true); } public PluginState(final Plugin plugin, final boolean enabled) { this.plugin = plugin; setEnabled(enabled); } public void setEnabled(final boolean enabled) { if (this.enabled == enabled) return; plugin.setEnabled(Nar.this, enabled); this.enabled = enabled; emit(Events.PluginsChange.class, plugin, enabled); } public boolean isEnabled() { return enabled; } } protected transient List<PluginState> plugins = new ArrayList<>(); //was CopyOnWriteArrayList /** Flag for running continuously */ private boolean running = false; /** used by stop() to signal that a running loop should be interrupted */ private boolean stopped = false; private boolean threadYield; public static final String DEFAULTCONFIG_FILEPATH = "./config/defaultConfig.xml"; public Nar(long narId) throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { this(narId, true, DEFAULTCONFIG_FILEPATH); } public Nar(long narId, String configFilePath) throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { this(narId, false, configFilePath); } public String usedConfigFilePath = ""; public boolean loadedFromResources = false; // constructs the NAR and loads a config from the filepath public Nar(long narId, boolean loadFromResources, String configFilePath) throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, SAXException, IllegalAccessException, ParseException, ClassNotFoundException { List<Plugin> pluginsToAdd = ConfigReader.loadParamsFromFileAndReturnPlugins(loadFromResources, configFilePath, this, this.narParameters); final Memory m = new Memory(this.narParameters, new LevelBag(narParameters.CONCEPT_BAG_LEVELS, narParameters.CONCEPT_BAG_SIZE, this.narParameters), new LevelBag<>(narParameters.NOVEL_TASK_BAG_LEVELS, narParameters.NOVEL_TASK_BAG_SIZE, this.narParameters), new LevelBag<>(narParameters.SEQUENCE_BAG_LEVELS, narParameters.SEQUENCE_BAG_SIZE, this.narParameters), new LevelBag<>(narParameters.OPERATION_BAG_LEVELS, narParameters.OPERATION_BAG_SIZE, this.narParameters)); this.memory = m; this.memory.narId = narId; this.usedConfigFilePath = configFilePath; this.loadedFromResources = loadFromResources; for(Plugin p : pluginsToAdd) { //adding after memory is constructed, as memory depends on the loaded params!! this.addPlugin(p); } } public Nar() throws IOException, InstantiationException, InvocationTargetException, NoSuchMethodException, ParserConfigurationException, IllegalAccessException, SAXException, ClassNotFoundException, ParseException { this(java.util.UUID.randomUUID().getLeastSignificantBits(), true, DEFAULTCONFIG_FILEPATH); } /** * Reset the system with an empty memory and reset clock. Called locally. */ public void reset() { memory.reset(); } /** * Generally the text will consist of Task's to be parsed in Narsese, but * may contain other commands recognized by the system. The creationTime * will be set to the current memory cycle time, but may be processed by * memory later according to the length of the input queue. */ private boolean addMultiLineInput(final String text) { if(text.contains("\n")) { final String[] lines = text.split("\n"); for(final String s : lines) { addInput(s); if(!running) { this.cycle(); } } return true; } return false; } private boolean addCommand(final String text) { if(text.startsWith("**")) { this.reset(); return true; } else if(text.startsWith("*decisionthreshold=")) { //TODO use reflection for narParameters, allow to set others too final Double value = Double.valueOf(text.split("decisionthreshold=")[1]); narParameters.DECISION_THRESHOLD = value.floatValue(); return true; } else if(text.startsWith("*volume=")) { final Integer value = Integer.valueOf(text.split("volume=")[1]); narParameters.VOLUME = value; return true; } else if(text.startsWith("*threads=")) { final Integer value = Integer.valueOf(text.split("*threads=")[1]); narParameters.THREADS_AMOUNT = value; return true; } else if(text.startsWith("*speed=")) { final Integer value = Integer.valueOf(text.split("*speed")[1]); this.minCyclePeriodMS = value; return true; } else if(StringUtils.isNumeric(text)) { final Integer retVal = Integer.parseInt(text); if(!running) { for(int i=0;i<retVal;i++) { this.cycle(); } } return true; } else { return false; } } public void addInput(String text) { text = text.trim(); final Narsese narsese = new Narsese(this); if(addMultiLineInput(text)) { return; } //Ignore any input that is just a comment if(text.startsWith("\'") || text.startsWith("//") ||text.trim().length() <= 0) return; if(addCommand(text)) { return; } final Task task; try { task = narsese.parseTask(text); } catch (final InvalidInputException e) { throw new IllegalStateException("Invalid input: " + text, e); } //check if it should go to a sensory channel instead: final Term t = task.getTerm(); if(t != null && t instanceof Inheritance) { final Term predicate = ((Inheritance) t).getPredicate(); if(this.sensoryChannels.containsKey(predicate)) { final Inheritance inh = (Inheritance) task.sentence.term; final SetExt subj = (SetExt) inh.getSubject(); //map to pei's -1 to 1 indexing schema if(subj.term[0].term_indices == null) { final String variable = subj.toString().split("\\[")[0]; final String[] vals = subj.toString().split("\\[")[1].split("\\]")[0].split(","); final double height = Double.parseDouble(vals[0]); final double width = Double.parseDouble(vals[1]); final int wval = (int) Math.round((width+1.0f)/2.0f*(this.sensoryChannels.get(predicate).width-1)); final int hval = (int) Math.round(((height+1.0f)/2.0f*(this.sensoryChannels.get(predicate).height-1))); final String ev = task.sentence.isEternal() ? " " : " :|: "; final String newInput = "<"+variable+"["+hval+","+wval+"]} --> " + predicate + ">" + task.sentence.punctuation + ev + task.sentence.truth.toString(); //this.emit(OutputHandler.IN.class, task); too expensive to print each input task :) this.addInput(newInput); return; } this.sensoryChannels.get(predicate).addInput(task, this); return; } } //else input into NARS directly: this.memory.inputTask(this, task); } public void addInputFile(final String s) { try (final BufferedReader br = new BufferedReader(new FileReader(s))) { String line; while ((line = br.readLine()) != null) { if(!line.isEmpty()) { this.addInput(line); } } } catch (final IOException ex) { Logger.getLogger(Nar.class.getName()).log(Level.SEVERE, null, ex); throw new IllegalStateException("Could not open specified file", ex); } } /** gets a concept if it exists, or returns null if it does not */ public Concept concept(final String concept) throws InvalidInputException { return memory.concept(new Narsese(this).parseTerm(concept)); } public Nar ask(final String termString, final AnswerHandler answered) throws InvalidInputException { final Sentence sentenceForNewTask = new Sentence( new Narsese(this).parseTerm(termString), Symbols.QUESTION_MARK, null, new Stamp(this, memory, Tense.Eternal)); final BudgetValue budget = new BudgetValue( narParameters.DEFAULT_QUESTION_PRIORITY, narParameters.DEFAULT_QUESTION_DURABILITY, 1, narParameters); final Task t = new Task(sentenceForNewTask, budget, Task.EnumType.INPUT); addInput(t, this); if (answered!=null) { answered.start(t, this); } return this; } public Nar askNow(final String termString, final AnswerHandler answered) throws InvalidInputException { final Sentence sentenceForNewTask = new Sentence( new Narsese(this).parseTerm(termString), Symbols.QUESTION_MARK, null, new Stamp(this, memory, Tense.Present)); final BudgetValue budgetForNewTask = new BudgetValue( narParameters.DEFAULT_QUESTION_PRIORITY, narParameters.DEFAULT_QUESTION_DURABILITY, 1, narParameters); final Task t = new Task(sentenceForNewTask, budgetForNewTask, Task.EnumType.INPUT); addInput(t, this); if (answered!=null) { answered.start(t, this); } return this; } public Nar addInput(final Task t, final Timable time) { this.memory.inputTask(this, t); return this; } /** attach event handler */ public void on(final Class c, final EventObserver o) { memory.event.on(c, o); } /** remove event handler */ public void off(final Class c, final EventObserver o) { memory.event.on(c, o); } /** set an event handler. useful for multiple events. */ public void event(final EventObserver e, final boolean enabled, final Class... events) { memory.event.set(e, enabled, events); } public void addPlugin(final Plugin p) { if(p instanceof SensoryChannel) { this.addSensoryChannel(((SensoryChannel) p).getName(), (SensoryChannel) p); } else if (p instanceof Operator) { memory.addOperator((Operator)p); } else if(p instanceof Emotions) { memory.emotion = (Emotions) p; } else if(p instanceof InternalExperience) { memory.internalExperience = (InternalExperience) p; } final PluginState ps = new PluginState(p); plugins.add(ps); emit(Events.PluginsChange.class, p, null); } public void removePlugin(final PluginState ps) { if (plugins.remove(ps)) { final Plugin p = ps.plugin; if (p instanceof Operator) { memory.removeOperator((Operator)p); } if (p instanceof SensoryChannel) { sensoryChannels.remove(p); } //TODO sensory channels can be plugins ps.setEnabled(false); emit(Events.PluginsChange.class, null, p); } } public List<PluginState> getPlugins() { return Collections.unmodifiableList(plugins); } public void start(final long minCyclePeriodMS) { this.minCyclePeriodMS = minCyclePeriodMS; if (threads == null) { int n_threads = narParameters.THREADS_AMOUNT; threads = new Thread[n_threads]; for(int i=0;i<n_threads;i++) { threads[i] = new Thread(this, "Inference"+i); threads[i].start(); } } running = true; } public void start() { start(narParameters.MILLISECONDS_PER_STEP); } /** * Stop the inference process, killing its thread. */ public void stop() { if (threads!=null) { for(Thread thread : threads) { thread.interrupt(); } threads = null; } stopped = true; running = false; } /** Execute a fixed number of cycles.*/ public void cycles(final int cycles) { memory.allowExecution = true; emit(CyclesStart.class); final boolean wasRunning = running; running = true; stopped = false; for(int i=0;i<cycles;i++) { cycle(); } running = wasRunning; emit(CyclesEnd.class); } /** Main loop executed by the Thread. Should not be called directly. */ @Override public void run() { stopped = false; while (running && !stopped) { emit(CyclesStart.class); cycle(); emit(CyclesEnd.class); if (minCyclePeriodMS > 0) { try { Thread.sleep(minCyclePeriodMS); } catch (final InterruptedException e) { } } else if (threadYield) { Thread.yield(); } } } public void emit(final Class c, final Object... o) { memory.event.emit(c, o); } /** * A frame, consisting of one or more Nar memory cycles */ public void cycle() { try { memory.cycle(this); synchronized (cycle) { cycle++; } } catch (final Exception e) { if(MiscFlags.SHOW_REASONING_ERRORS) { emit(ERR.class, e); } throw e; } } @Override public String toString() { return memory.toString(); } public long time() { if(narParameters.STEPS_CLOCK) { return cycle; } else { return System.currentTimeMillis(); } } public boolean isRunning() { return running; } public long getMinCyclePeriodMS() { return minCyclePeriodMS; } /** When b is true, Nar will call Thread.yield each run() iteration that minCyclePeriodMS==0 (no delay). * This is for improving program responsiveness when Nar is run with no delay. */ public void setThreadYield(final boolean b) { this.threadYield = b; } }
package plotter.tail; import java.awt.AWTEvent; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Shape; import java.awt.Stroke; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.MessageFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.TimeZone; import java.util.regex.Pattern; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFormattedTextField; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JSplitPane; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import plotter.DateNumberFormat; import plotter.DoubleData; import plotter.Legend; import plotter.xy.LinearXYAxis; import plotter.xy.XYAxis; public class TailPlot { private List<DataFile> dataFiles = new ArrayList<DataFile>(); private XYFormat slopeFormat; private XYFormat locationFormat; private XYPlotFrame frame; private XYAxis xAxis; private XYAxis yAxis; private XYAxis y2Axis; private Iterator<Color> colors; private MetaAxis metaX = new MetaAxis() { public List<DoubleData> getDatasets() { List<DoubleData> datasets = new ArrayList<DoubleData>(); for(DataFile dataFile : dataFiles) { for(Field f : dataFile.getFields()) { datasets.add(f.getDataset().getXData()); } } return datasets; } @Override protected void logscaleUpdated(boolean logscale) { locationFormat.setLogX(logscale); slopeFormat.setLogX(logscale); frame.getPlot().repaint(); } }; private MetaAxis metaY = new MetaAxis() { @Override public List<DoubleData> getDatasets() { List<DoubleData> datasets = new ArrayList<DoubleData>(); for(DataFile dataFile : dataFiles) { for(Field f : dataFile.getFields()) { if(!f.isOnY2()) { datasets.add(f.getDataset().getYData()); } } } return datasets; } @Override protected void logscaleUpdated(boolean logscale) { locationFormat.setLogY(logscale); slopeFormat.setLogY(logscale); frame.getPlot().repaint(); } }; private MetaAxis metaY2 = new MetaAxis() { @Override public List<DoubleData> getDatasets() { List<DoubleData> datasets = new ArrayList<DoubleData>(); for(DataFile dataFile : dataFiles) { for(Field f : dataFile.getFields()) { if(!f.isOnY2()) { datasets.add(f.getDataset().getYData()); } } } return datasets; } @Override protected void logscaleUpdated(boolean logscale) { frame.getPlot().repaint(); } }; private String title; private JCheckBox autorestartCheckbox; public static void main(String[] args) { try { new TailPlot().run(args); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } void usage(String msg) { if(msg != null) { System.err.println(msg); } System.err.println("Usage: TailPlot file [options] [ file [options] ... ]"); System.err.println("Plots a file, displaying new data as it is generated (analogous to 'tail -f')"); System.err.println("If no file is specified, standard input is read."); System.err.println("File-specific options must come after the relevant file name, although general options may appear anywhere."); System.err.println(); System.err.println("General options:"); System.err.println(" --x-format=FMT display format of the X axis. Example: time,YYY-MM-dd_HH:mm:ss to display as a timestamp (default: number)"); System.err.println(" --y-format=FMT display format of the Y axis. Example: time,YYY-MM-dd_HH:mm:ss to display as a timestamp (default: number)"); System.err.println(" --y2-format=FMT display format of the Y2 axis. Example: time,YYY-MM-dd_HH:mm:ss to display as a timestamp (default: number)"); System.err.println(" -t, --title=TITLE set the window title (defaults to the file name)"); System.err.println(" --scroll-width=AMT amount of data to keep on screen (in X axis units)"); System.err.println(" --help display this message"); System.err.println(); System.err.println("File-specific options:"); System.err.println(" -F, --field-separator=REGEX set the field separator regex (default: [,\\t ]+)"); System.err.println(" -f, --fields=FIELDS field names (separated by the field separator)"); System.err.println(" -s, --select=FIELDS comma-separated list of field indices to plot (1-based)"); System.err.println(" --y2=FIELDS comma-separated list of field indices to place on the Y2 axis (1-based)"); System.err.println(" -x, --x=INDEX index of field to use as X value. Note that X values must be monotonically increasing. (1-based, default: line number is X value)"); System.err.println(" --field-format=FIELD,FMT input format of a field. Example: 1,time,YYY-MM-dd_HH:mm:ss to read field 1 as a timestamp (default: number)"); System.err.println(" -h, --header-line use the first line as a header line"); System.err.println(); System.err.println("Notes:"); System.err.println(" If both --fields and --header-line are specified, the first line is skipped, and field names are taken from --fields."); System.err.println(); System.err.println(" For compatibility with legacy scripts, if only one file is specified, the options may come before the file name, although this usage is discouraged."); System.err.println(); System.err.println("Examples:"); System.err.println(" Plot the first and third fields, with the third on the Y2 axis"); System.err.println(" TailPlot file --select=1,3 --y2=3"); System.err.println(); System.err.println(" Plot the first field of fileA and the third field of fileB"); System.err.println(" TailPlot fileA --select=1 fileB --select=3"); System.exit(1); } private void parseArgsLegacy(String[] args) { DataFile dataFile = new DataFile(this); title = null; String scrollWidthString = null; for(int i = 0; i < args.length; i++) { if(args[i].equals("-F")) { dataFile.setFieldSeparator(Pattern.compile(args[++i])); } else if(args[i].startsWith("--field-separator=")) { dataFile.setFieldSeparator(Pattern.compile(args[i].substring("--field-separator=".length()))); } else if(args[i].equals("-f")) { dataFile.setFieldString(args[++i]); } else if(args[i].startsWith("--fields=")) { dataFile.setFieldString(args[i].substring("--fields=".length())); } else if(args[i].equals("-s")) { dataFile.setSelection(parseIntList(args[++i])); } else if(args[i].startsWith("--select=")) { dataFile.setSelection(parseIntList(args[i].substring("--select=".length()))); } else if(args[i].startsWith("--y2=")) { dataFile.setY2(parseIntList(args[i].substring("--y2=".length()))); } else if(args[i].startsWith("-x")) { dataFile.setX(Integer.parseInt(args[++i])); } else if(args[i].startsWith("--x=")) { dataFile.setX(Integer.parseInt(args[i].substring("--x=".length()))); } else if(args[i].startsWith("--field-format=")) { String s = args[i].substring("--field-format=".length()); int ix = s.indexOf(","); int fieldIx = Integer.parseInt(s.substring(0, ix)); String format = s.substring(ix + 1); NumberFormat fmt; try { fmt = parseFormat(format); } catch(ParseException e) { System.err.println(e.getMessage()); System.exit(-1); fmt = null; } dataFile.addFieldFormat(fieldIx, fmt); } else if(args[i].startsWith("--x-format=")) { String format = args[i].substring("--x-format=".length()); NumberFormat fmt; try { fmt = parseFormat(format); } catch(ParseException e) { System.err.println(e.getMessage()); System.exit(-1); fmt = null; } metaX.setFormat(fmt); } else if(args[i].startsWith("--y-format=")) { String format = args[i].substring("--y-format=".length()); NumberFormat fmt; try { fmt = parseFormat(format); } catch(ParseException e) { System.err.println(e.getMessage()); System.exit(-1); fmt = null; } metaY.setFormat(fmt); } else if(args[i].startsWith("--y2-format=")) { String format = args[i].substring("--y2-format=".length()); NumberFormat fmt; try { fmt = parseFormat(format); } catch(ParseException e) { System.err.println(e.getMessage()); System.exit(-1); fmt = null; } metaY2.setFormat(fmt); } else if(args[i].equals("--header-line") || args[i].equals("-h")) { dataFile.setHeaderLine(true); } else if(args[i].equals("-t")) { title = args[++i]; } else if(args[i].startsWith("--title=")) { title = args[i].substring("--title=".length()); } else if(args[i].startsWith("--scroll-width=")) { scrollWidthString = args[i].substring("--scroll-width=".length()); } else if(args[i].equals("--help") || args[i].equals("-h")) { usage(null); } else if(args[i].startsWith("-")) { usage("Unrecognized option: " + args[i]); } else { if(dataFile.getFile() != null) { // Multiple files have been specified. Use the new parser instead. parseArgs(args); return; } dataFile.setFile(new File(args[i])); } } dataFile.init(); if(title == null) { if(dataFile.getFile() == null) { title = "<standard input>"; } else { title = dataFile.getFile().getPath(); } } if(scrollWidthString != null) { try { NumberFormat format = metaX.getFormat(); metaX.setScrollWidth(format.parse(scrollWidthString).doubleValue()); } catch(ParseException e) { System.err.println("Invalid X value for scroll width: " + scrollWidthString); } } dataFiles.add(dataFile); } private void parseArgs(String[] args) { title = null; String scrollWidthString = null; DataFile dataFile = null; for(int i = 0; i < args.length; i++) { if(args[i].equals("-F")) { if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.setFieldSeparator(Pattern.compile(args[++i])); } } else if(args[i].startsWith("--field-separator=")) { if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.setFieldSeparator(Pattern.compile(args[i].substring("--field-separator=".length()))); } } else if(args[i].equals("-f")) { if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.setFieldString(args[++i]); } } else if(args[i].startsWith("--fields=")) { if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.setFieldString(args[i].substring("--fields=".length())); } } else if(args[i].equals("-s")) { if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.setSelection(parseIntList(args[++i])); } } else if(args[i].startsWith("--select=")) { if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.setSelection(parseIntList(args[i].substring("--select=".length()))); } } else if(args[i].startsWith("--y2=")) { if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.setY2(parseIntList(args[i].substring("--y2=".length()))); } } else if(args[i].startsWith("-x")) { if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.setX(Integer.parseInt(args[++i])); } } else if(args[i].startsWith("--x=")) { if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.setX(Integer.parseInt(args[i].substring("--x=".length()))); } } else if(args[i].startsWith("--field-format=")) { String s = args[i].substring("--field-format=".length()); int ix = s.indexOf(","); int fieldIx = Integer.parseInt(s.substring(0, ix)); String format = s.substring(ix + 1); NumberFormat fmt; try { fmt = parseFormat(format); } catch(ParseException e) { System.err.println(e.getMessage()); System.exit(-1); fmt = null; } if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.addFieldFormat(fieldIx, fmt); } } else if(args[i].startsWith("--x-format=")) { String format = args[i].substring("--x-format=".length()); NumberFormat fmt; try { fmt = parseFormat(format); } catch(ParseException e) { System.err.println(e.getMessage()); System.exit(-1); fmt = null; } metaX.setFormat(fmt); } else if(args[i].startsWith("--y-format=")) { String format = args[i].substring("--y-format=".length()); NumberFormat fmt; try { fmt = parseFormat(format); } catch(ParseException e) { System.err.println(e.getMessage()); System.exit(-1); fmt = null; } metaY.setFormat(fmt); } else if(args[i].startsWith("--y2-format=")) { String format = args[i].substring("--y2-format=".length()); NumberFormat fmt; try { fmt = parseFormat(format); } catch(ParseException e) { System.err.println(e.getMessage()); System.exit(-1); fmt = null; } metaY2.setFormat(fmt); } else if(args[i].equals("--header-line") || args[i].equals("-h")) { if(dataFile == null) { usage(args[i] + " must be used after file argument"); } else { dataFile.setHeaderLine(true); } } else if(args[i].equals("-t")) { title = args[++i]; } else if(args[i].startsWith("--title=")) { title = args[i].substring("--title=".length()); } else if(args[i].startsWith("--scroll-width=")) { scrollWidthString = args[i].substring("--scroll-width=".length()); } else if(args[i].equals("--help") || args[i].equals("-h")) { usage(null); } else if(args[i].startsWith("-")) { usage("Unrecognized option: " + args[i]); } else { dataFile = new DataFile(this); dataFile.setFile(new File(args[i])); dataFiles.add(dataFile); } } for(DataFile file : dataFiles) { file.init(); } if(title == null) { StringBuilder b = new StringBuilder(); for(DataFile file : dataFiles) { if(b.length() > 0) { b.append(", "); } if(file.getFile() == null) { b.append("<standard input>"); } else { b.append(file.getFile().getPath()); } } title = b.toString(); } if(scrollWidthString != null) { try { NumberFormat format = metaX.getFormat(); metaX.setScrollWidth(format.parse(scrollWidthString).doubleValue()); } catch(ParseException e) { System.err.println("Invalid X value for scroll width: " + scrollWidthString); } } } public void run(String[] args) throws IOException { // If multiple files are specified, the legacy parser will hand over to the new parser. parseArgsLegacy(args); boolean restartable = true; for(DataFile dataFile : dataFiles) { if(dataFile.getFile() == null) { restartable = false; } } frame = new XYPlotFrame(); boolean useY2 = false; for(DataFile dataFile : dataFiles) { if(dataFile.isUseY2()) { useY2 = true; } } frame.setUseY2(useY2); frame.setUseLegend(true); JPanel content = new JPanel(); JPanel settings = new JPanel(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; GridBagConstraints labelConstraints = new GridBagConstraints(); labelConstraints.gridwidth = 1; labelConstraints.insets = new Insets(0, 0, 0, 5); labelConstraints.anchor = GridBagConstraints.LINE_START; settings.add(metaX.createAutoscaleCheckbox("Auto-scale X axis"), constraints); settings.add(metaY.createAutoscaleCheckbox("Auto-scale Y axis"), constraints); if(useY2) { settings.add(metaY2.createAutoscaleCheckbox("Auto-scale Y2 axis"), constraints); } frame.addAxisListener(metaX); frame.addAxisListener(metaY); if(useY2) { frame.addAxisListener(metaY2); } settings.add(metaX.createLogscaleCheckbox("Logarithmic X axis"), constraints); settings.add(metaY.createLogscaleCheckbox("Logarithmic Y axis"), constraints); if(useY2) { settings.add(metaY2.createLogscaleCheckbox("Logarithmic Y2 axis"), constraints); } JLabel xminLabel = new JLabel("X minimum:"); JFormattedTextField xminText = metaX.createMinTextField(); xminLabel.setLabelFor(xminText); settings.add(xminLabel, labelConstraints); settings.add(xminText, constraints); JLabel xmaxLabel = new JLabel("X maximum:"); JFormattedTextField xmaxText = metaX.createMaxTextField(); xmaxLabel.setLabelFor(xmaxText); settings.add(xmaxLabel, labelConstraints); settings.add(xmaxText, constraints); JLabel yminLabel = new JLabel("Y minimum:"); JFormattedTextField yminText = metaY.createMinTextField(); yminLabel.setLabelFor(yminText); settings.add(yminLabel, labelConstraints); settings.add(yminText, constraints); JLabel ymaxLabel = new JLabel("Y maximum:"); JFormattedTextField ymaxText = metaY.createMaxTextField(); ymaxLabel.setLabelFor(ymaxText); settings.add(ymaxLabel, labelConstraints); settings.add(ymaxText, constraints); if(useY2) { JLabel y2minLabel = new JLabel("Y2 minimum:"); JFormattedTextField y2minText = metaY2.createMinTextField(); y2minLabel.setLabelFor(y2minText); settings.add(y2minLabel, labelConstraints); settings.add(y2minText, constraints); JLabel y2maxLabel = new JLabel("Y2 maximum:"); JFormattedTextField y2maxText = metaY2.createMaxTextField(); y2maxLabel.setLabelFor(y2maxText); settings.add(y2maxLabel, labelConstraints); settings.add(y2maxText, constraints); } autorestartCheckbox = new JCheckBox("Auto-restart if file shrinks"); autorestartCheckbox.setSelected(restartable); autorestartCheckbox.setEnabled(restartable); autorestartCheckbox.setToolTipText("Reload data if a file shrinks"); settings.add(autorestartCheckbox, constraints); final JCheckBox showLegendCheckbox = new JCheckBox("Show legend"); showLegendCheckbox.setSelected(true); showLegendCheckbox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { frame.getLegend().setVisible(showLegendCheckbox.isSelected()); } }); showLegendCheckbox.setToolTipText("Display the plot legend"); settings.add(showLegendCheckbox, constraints); JLabel xMarginLabel = new JLabel("Bottom margin:"); final JSpinner xMarginSpinner = new JSpinner(); xMarginSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if(xAxis != null) { int value = (Integer) xMarginSpinner.getValue(); xAxis.setPreferredSize(new Dimension(xAxis.getPreferredSize().width, value)); xAxis.getParent().revalidate(); yAxis.setStartMargin(value); yAxis.revalidate(); if(y2Axis != null) { y2Axis.setStartMargin(value); y2Axis.revalidate(); } } } }); xMarginSpinner.setModel(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); xMarginSpinner.setToolTipText("Number of pixels below the main plot area"); xMarginLabel.setLabelFor(xMarginSpinner); settings.add(xMarginLabel, labelConstraints); settings.add(xMarginSpinner, constraints); JLabel yMarginLabel = new JLabel("Left margin:"); final JSpinner yMarginSpinner = new JSpinner(); yMarginSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if(yAxis != null) { int value = (Integer) yMarginSpinner.getValue(); yAxis.setPreferredSize(new Dimension(value, yAxis.getPreferredSize().height)); yAxis.getParent().revalidate(); xAxis.setStartMargin(value); xAxis.revalidate(); } } }); yMarginSpinner.setModel(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); yMarginSpinner.setToolTipText("Number of pixels to the left of the main plot area"); yMarginLabel.setLabelFor(yMarginSpinner); settings.add(yMarginLabel, labelConstraints); settings.add(yMarginSpinner, constraints); final JSpinner y2MarginSpinner; if(!useY2) { y2MarginSpinner = null; } else { JLabel y2MarginLabel = new JLabel("Right margin:"); y2MarginSpinner = new JSpinner(); y2MarginSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if(y2Axis != null) { int value = (Integer) y2MarginSpinner.getValue(); y2Axis.setPreferredSize(new Dimension(value, y2Axis.getPreferredSize().height)); y2Axis.getParent().revalidate(); xAxis.setEndMargin(value); xAxis.revalidate(); } } }); y2MarginSpinner.setModel(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); y2MarginSpinner.setToolTipText("Number of pixels to the right of the main plot area"); y2MarginLabel.setLabelFor(y2MarginSpinner); settings.add(y2MarginLabel, labelConstraints); settings.add(y2MarginSpinner, constraints); } final JButton restartButton = new JButton("Restart"); restartButton.setEnabled(restartable); restartButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { for(DataFile dataFile : dataFiles) { dataFile.restart(); } } }); restartButton.setToolTipText("Reload data from file(s)"); settings.add(restartButton, constraints); JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, settings, content); splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(0); frame.setContentPane(splitPane); frame.setTitle(title); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setup(content); xAxis = (LinearXYAxis) frame.getXAxis(); yAxis = frame.getYAxis(); y2Axis = frame.getY2Axis(); xMarginSpinner.setValue(xAxis.getPreferredSize().height); yMarginSpinner.setValue(yAxis.getPreferredSize().width); if(useY2) { y2MarginSpinner.setValue(y2Axis.getPreferredSize().width); } metaX.setAxis(xAxis); metaY.setAxis(yAxis); metaY2.setAxis(y2Axis); String axisToolTipText = "Shift-drag to move/translate, ctrl-drag to scale, click and hold to display marker line"; xAxis.setToolTipText(axisToolTipText); yAxis.setToolTipText(axisToolTipText); if(useY2) { y2Axis.setToolTipText(axisToolTipText); } MessageFormat innerSlopeFormat = new MessageFormat("<html><b>&Delta;x:</b> {0} <b>&Delta;y:</b> {1}</html>"); MessageFormat innerLocationFormat = new MessageFormat("<html><b>X:</b> {0} &nbsp; <b>Y:</b> {1}</html>"); NumberFormat xFormat = metaX.getFormat(); if(xFormat != null) { innerSlopeFormat.setFormatByArgumentIndex(0, xFormat); innerLocationFormat.setFormatByArgumentIndex(0, xFormat); } NumberFormat yFormat = metaY.getFormat(); if(yFormat != null) { innerSlopeFormat.setFormatByArgumentIndex(1, yFormat); innerLocationFormat.setFormatByArgumentIndex(1, yFormat); } slopeFormat = new XYFormat(innerSlopeFormat); locationFormat = new XYFormat(innerLocationFormat); frame.getLocationDisplay().setFormat(locationFormat); frame.getSlopeLineDisplay().setTextFormat(slopeFormat); colors = new Iterator<Color>() { Color[] colors = new Color[] { Color.red, Color.green, Color.blue, Color.yellow, Color.orange, Color.cyan, Color.magenta, Color.pink, Color.gray, Color.white }; int ix; @Override public boolean hasNext() { return true; } @Override public Color next() { Color c = colors[ix]; ix = (ix + 1) % colors.length; return c; } @Override public void remove() { throw new UnsupportedOperationException(); } }; Legend legend = frame.getLegend(); frame.getToolkit().addAWTEventListener( new LegendDragListener(legend, frame.getContents(), frame.getPlot()), AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.KEY_EVENT_MASK); legend.setToolTipText("Shift-drag to move legend"); frame.setSize(400, 300); frame.setVisible(true); for(DataFile dataFile : dataFiles) { dataFile.start(); } } private NumberFormat parseFormat(String format) throws ParseException { NumberFormat fmt; if(format.equals("date")) { DateFormat f = DateFormat.getDateInstance(); f.setTimeZone(TimeZone.getTimeZone("GMT")); fmt = new DateNumberFormat(f); } else if(format.startsWith("date,")) { SimpleDateFormat f = new SimpleDateFormat(format.substring("date,".length())); f.setTimeZone(TimeZone.getTimeZone("GMT")); fmt = new DateNumberFormat(f); } else if(format.equals("time")) { DateFormat f = DateFormat.getTimeInstance(); f.setTimeZone(TimeZone.getTimeZone("GMT")); fmt = new DateNumberFormat(f); } else if(format.startsWith("time,")) { SimpleDateFormat f = new SimpleDateFormat(format.substring("time,".length())); f.setTimeZone(TimeZone.getTimeZone("GMT")); fmt = new DateNumberFormat(f); } else if(format.equals("number")) { fmt = NumberFormat.getInstance(); } else if(format.startsWith("number,")) { fmt = new DecimalFormat(format.substring("number,".length())); } else { throw new ParseException("Unrecognized number format: " + format, 0); } return fmt; } private int[] parseIntList(String s) { String[] data = s.split(","); int[] selection = new int[data.length]; for(int i = 0; i < selection.length; i++) { selection[i] = Integer.parseInt(data[i].trim()); } return selection; } void addPlotLine(String name, MultiplexingXYPlotLine pline, Stroke highlightStroke, Shape highlightPointFill, Shape highlightPointOutline) { frame.addPlotLine(name, pline, highlightStroke, highlightPointFill, highlightPointOutline); } public XYAxis getXAxis() { return xAxis; } public XYAxis getYAxis() { return yAxis; } public XYAxis getY2Axis() { return y2Axis; } public Color nextColor() { return colors.next(); } public void resetMinMax() { metaY.resetMinMax(); metaY2.resetMinMax(); metaX.resetMinMax(); } public void commitMinMax() { metaY.commitMinMax(); metaY2.commitMinMax(); metaX.commitMinMax(); } public MetaAxis getMetaX() { return metaX; } public MetaAxis getMetaY() { return metaY; } public MetaAxis getMetaY2() { return metaY2; } public boolean isAutorestart() { return autorestartCheckbox.isSelected(); } }
package services; import java.util.Collection; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import domain.Route; import domain.RouteOffer; import domain.SizePrice; import domain.User; import repositories.RouteRepository; @Service @Transactional public class RouteService { @Autowired private RouteRepository routeRepository; @Autowired private ActorService actorService; @Autowired private UserService userService; @Autowired private SizePriceService sizePriceService; @Autowired private RouteOfferService routeOfferService; public RouteService() { super(); } public Route create() { Assert.isTrue(actorService.checkAuthority("USER"), "Only an user can create a route"); Route result; User user; Date date; result = new Route(); user = userService.findByPrincipal(); date = new Date(); result.setCreator(user); result.setDate(date); return result; } public Route save(Route route) { Assert.notNull(route); Assert.isTrue(checkDates(route), "The departure date must be greater than the current date and the arrival date greater than the departure date."); Assert.isTrue(checkItemEnvelope(route.getItemEnvelope()), "ItemEnvelope must be open, closed or both."); if(route.getVehicle() != null) { Assert.isTrue(route.getCreator().getId() == route.getVehicle().getUser().getId(), "Both Ids must be the same."); } User user; Date date; user = userService.findByPrincipal(); date = new Date(); if(route.getId() == 0) { route.setCreator(user); route.setDate(date); route = routeRepository.save(route); } else { route = routeRepository.save(route); } return route; } public void delete(Route route) { Assert.notNull(route); Assert.isTrue(route.getId() != 0); Assert.isTrue(actorService.checkAuthority("USER"), "Only an user can delete routes"); User user; Collection<User> users; Collection<SizePrice> sizePrices; Collection<RouteOffer> routeOffers; user = userService.findByPrincipal(); users = userService.findAllByRoutePurchased(route.getId()); Assert.isTrue(user.getId() == route.getCreator().getId(), "Only the user who created the route can delete it"); Assert.isTrue(users.isEmpty(), "User can not delete a route if he has purchasers"); sizePrices = sizePriceService.findAllByRouteId(route.getId()); for(SizePrice s : sizePrices) { sizePriceService.delete(s); } routeOffers = routeOfferService.findAllByRouteId(route.getId()); for(RouteOffer ro : routeOffers) { routeOfferService.delete(ro); } routeRepository.delete(route); } public Route findOne(int routeId) { Route result; result = routeRepository.findOne(routeId); return result; } public Collection<Route> findAll() { Collection<Route> result; result = routeRepository.findAll(); return result; } public void flush() { routeRepository.flush(); } private boolean checkItemEnvelope(String itemEnvelope) { boolean res; res = false; if(itemEnvelope.equals("Open") || itemEnvelope.equals("Closed") || itemEnvelope.equals("Both") || itemEnvelope.equals("Abierto") || itemEnvelope.equals("Cerrado") || itemEnvelope.equals("Ambos")) { res = true; } return res; } private boolean checkDates(Route route) { boolean res; res = true; if(route.getDate().compareTo(route.getDepartureTime()) >= 0) { res = false; } if(route.getDepartureTime().compareTo(route.getArriveTime()) >= 0) { res = false; } return res; } }
package water.api; import java.util.ArrayList; import water.Futures; import water.Key; import water.util.FileIntegrityChecker; public class ImportFiles extends Request { static final int API_WEAVER=1; // This file has auto-gen'd doc & json fields static public JSONDoc[] DOC_JSON; // Initialized from Auto-Gen code. // This Request supports the HTML 'GET' command, and this is the help text // for GET. static final String DOC_GET = " Map a file from the local host filesystem into H2O memory. Data is "+ "loaded lazily, when the Key is read (usually in a Parse command). "+ "(Warning: Every host in the cluster must have this file visible locally!)"; // HTTP REQUEST PARAMETERS static final String path_help = "File or directory to import."; protected transient final ExistingFile path = new ExistingFile("path"); // JSON OUTPUT FIELDS static final String filesHelp="Files imported. Imported files are merely Keys mapped over the existing files. No data is loaded until the Key is used (usually in a Parse command)"; String[] files; static final String keysHelp="Keys of imported files, Keys map 1-to-1 with imported files."; String[] keys; static final String failsHelp="File names that failed the integrity check, can be empty."; String[] fails; static final String DOC_4 = "Error JSON elements\n"+ " "\n"+ " error [string]\n"+ "\n"+ " Required argument not specified.\n"+ "\n"+ " File not found.\n"+ "\n"+ "HTTP response codes\n"+ " " \n"+ " 200 OK\n"+ "\n"+ " Success and error responses are identical.\n"+ "\n"+ "Success Example\n"+ " "\n"+ ".. literalinclude:: ImportFiles_success_1.rest\n"+ "\n"+ "Error Example\n"+ " "\n"+ ".. literalinclude:: ImportFiles_error_1.rest\n"; @Override protected Response serve() { FileIntegrityChecker c = FileIntegrityChecker.check(path.value()); ArrayList<String> afails = new ArrayList(); ArrayList<String> afiles = new ArrayList(); ArrayList<String> akeys = new ArrayList(); Futures fs = new Futures(); for( int i = 0; i < c.size(); ++i ) { Key k = c.importFile(i, fs); if( k == null ) { afails.add(c.getFileName(i)); } else { afiles.add(c.getFileName(i)); akeys .add(k.toString()); } } fs.blockForPending(); fails = afails.toArray(new String[0]); files = afiles.toArray(new String[0]); keys = akeys .toArray(new String[0]); return new Response(Response.Status.done, this); } // HTML builder @Override public StringBuilder toHTML( StringBuilder sb ) { if( files.length > 1 ) sb.append("<div class='alert'>") .append(Parse.link("*"+path.value()+"*", "Parse all into hex format")) .append(" </div>"); DocGen.HTML.title(sb,"files"); DocGen.HTML.arrayHead(sb); for( int i=0; i<files.length; i++ ) sb.append("<tr><td><a href='Parse.html?source_key=").append(keys[i]). append("'>").append(files[i]).append("</a></td></tr>"); DocGen.HTML.arrayTail(sb); if( fails.length > 0 ) DocGen.HTML.array(DocGen.HTML.title(sb,"fails"),fails); return sb; } }
// V e r t i c a l s B u i l d e r // // This software is released under the terms of the GNU General Public // // to report bugs & suggestions. // package omr.sheet; import omr.Main; import omr.ProcessingException; import omr.check.Check; import omr.check.CheckSuite; import omr.check.FailureResult; import omr.check.SuccessResult; import omr.constant.Constant; import omr.constant.ConstantSet; import omr.glyph.Glyph; import omr.glyph.GlyphDirectory; import omr.glyph.GlyphLag; import omr.glyph.Shape; import omr.glyph.ui.GlyphBoard; import omr.stick.Stick; import omr.stick.StickSection; import omr.stick.StickView; import omr.ui.BoardsPane; import omr.ui.FilterBoard; import omr.ui.PixelBoard; import omr.ui.ScrollLagView; import omr.ui.SectionBoard; import omr.ui.Zoom; import omr.util.Logger; import omr.util.Predicate; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.*; /** * Class <code>VerticalsBuilder</code> is in charge of retrieving all the * vertical sticks of all systems in the sheet at hand. Bars are assumed to * have been already recognized, so this accounts for stems, vertical edges * of endings, and potentially parts of alterations (sharp, natural, flat). * * @author Herv&eacute Bitteur * @version $Id$ */ public class VerticalsBuilder implements GlyphDirectory { private static final Constants constants = new Constants(); private static final Logger logger = Logger.getLogger(VerticalsBuilder.class); // Success codes private static final SuccessResult STEM = new SuccessResult("Stem"); // Failure codes private static final FailureResult TOO_LIMITED = new FailureResult("Stem-TooLimited"); private static final FailureResult TOO_SHORT = new FailureResult("Stem-TooShort"); private static final FailureResult TOO_FAT = new FailureResult("Stem-TooFat"); private static final FailureResult TOO_HIGH_ADJACENCY = new FailureResult("Stem-TooHighAdjacency"); private static final FailureResult OUTSIDE_SYSTEM = new FailureResult("Stem-OutsideSystem"); private static final FailureResult TOO_HOLLOW = new FailureResult("Stem-TooHollow"); private static final FailureResult NO_CHUNK = new FailureResult("Stem-NoChunk"); // The containing sheet private final Sheet sheet; // Lag of vertical runs private final GlyphLag vLag; private final VerticalArea verticalsArea; private MyView view; // VerticalsBuilder // public VerticalsBuilder (Sheet sheet) throws ProcessingException { this.sheet = sheet; Scale scale = sheet.getScale(); // We re-use the same vertical lag (but not the sticks) from Bars. vLag = sheet.getVerticalLag(); // We cannot reuse the sticks, since thick sticks are allowed for // bars but not for stems. So, let's rebuild the stick area from // the initial lag. verticalsArea = new VerticalArea (sheet, vLag, new MySectionPredicate(), scale.fracToPixels(constants.maxStemThickness)); // Split these candidates per system SystemSplit.splitVerticalSticks(sheet, verticalsArea.getSticks()); // Now process each system area on turn int totalStemNb = 0; // Iterate on systems for (SystemInfo system : sheet.getSystems()) { totalStemNb += retrieveVerticals(system); } if (constants.displayFrame.getValue() && Main.getJui() != null) { displayFrame(); } logger.info(totalStemNb + " stem(s) found"); } // getEntity // public Glyph getEntity (Integer id) { return vLag.getGlyph(id); } // displayFrame // private void displayFrame () { // Specific rubber display view = new MyView(); view.colorize(); // Ids of recognized glyphs List<Integer> knownIds = new ArrayList<Integer>(); knownIds.add(GlyphBoard.NO_VALUE); for (SystemInfo system : sheet.getSystems()) { for (Glyph glyph : system.getGlyphs()) { if (glyph.isStem()) { knownIds.add(new Integer(glyph.getId())); } } } // Create a hosting frame for the view sheet.getAssembly().addViewTab ("Verticals", new ScrollLagView(view), new BoardsPane (view, new PixelBoard(), new SectionBoard(vLag.getLastVertexId()), new GlyphBoard(vLag.getLastGlyphId(), knownIds), new FilterBoard())); } // retrieveVerticals // private int retrieveVerticals (SystemInfo system) throws ProcessingException { // Define the suite of Checks StemCheckSuite suite = new StemCheckSuite(system); double minResult = constants.minCheckResult.getValue(); int stemNb = 0; List<Stick> sticks = system.getVerticalSticks(); if (logger.isDebugEnabled()) { logger.debug("Searching verticals among " + sticks.size() + " sticks from " + system); } for (Stick stick : sticks) { // Run the various Checks double res = suite.pass(stick); if (logger.isDebugEnabled()) { logger.debug("suite=> " + res + " for " + stick); } if (res >= minResult) { stick.setResult(STEM); stick.setShape(Shape.COMBINING_STEM); system.getGlyphs().add(stick); stemNb++; } else { stick.setResult(TOO_LIMITED); } } // (Re)Sort the modified list of glyphs, by abscissa system.sortGlyphs(); if (logger.isDebugEnabled()) { logger.debug("Found " + stemNb + " stems"); } return stemNb; } // MyView // private class MyView extends StickView { public MyView () { super(vLag, null, VerticalsBuilder.this); } // colorize // public void colorize () { super.colorize(); final int viewIndex = lag.getViews().indexOf(this); // All remaining vertical sticks clutter for (Stick stick : verticalsArea.getSticks()) { stick.colorize(lag, viewIndex, Color.red); } // Use light gray color for past successful entities sheet.colorize(lag, viewIndex, Color.lightGray); // Iterate on systems for (SystemInfo system : sheet.getSystems()) { // Use bright yellow color for recognized stems for (Glyph glyph : system.getGlyphs()) { if (glyph.isStem()) { Stick stick = (Stick) glyph; stick.colorize(lag, viewIndex, Color.yellow); // TBD, // use // glyph.colorize ??? } } } } // renderItems // public void renderItems (Graphics g) { Zoom z = getZoom(); // Render all physical info known so far sheet.render(g, z); Scale scale = sheet.getScale(); int nWidth = scale.fracToPixels(constants.chunkWidth); int nHeight = scale.fracToPixels(constants.chunkHeight); // Render the contour of the verticals for (SystemInfo system : sheet.getSystems()) { for (Glyph glyph : system.getGlyphs()) { if (glyph.isStem()) { Stick stick = (Stick) glyph; stick.renderContour(g, z); //stick.renderChunk(g, z, nHeight, nWidth); stick.renderLine(g, z); } } } // TBD Render the contour of the unlucky candidates also? } // glyphSelected // @Override protected void glyphSelected (Glyph glyph, Point pt) { try { if (glyph instanceof Stick) { SystemInfo systemInfo = sheet.getSystemAtY(pt.y); StemCheckSuite suite = new StemCheckSuite(systemInfo); Stick stick = (Stick) glyph; filterMonitor.tellHtml(suite.passHtml(null, stick)); } } catch (ProcessingException ex) { } } // deassignGlyph // @Override public void deassignGlyph (Glyph glyph) { Shape shape = glyph.getShape(); switch (shape) { case COMBINING_STEM : logger.info("Deassign a " + shape); sheet.getGlyphPane() .cancelStems(Collections.singletonList(glyph)); break; default : } } } // MinLengthCheck // private class MinLengthCheck extends Check<Stick> { protected MinLengthCheck () throws ProcessingException { super("MinLength", constants.minStemLengthLow.getValue(), constants.minStemLengthHigh.getValue(), true, TOO_SHORT); } // Retrieve the length data protected double getValue (Stick stick) { return sheet.getScale().pixelsToFrac(stick.getLength()); } } // MaxAspectCheck // private static class MaxAspectCheck extends Check<Stick> { protected MaxAspectCheck () { super("MaxAspect", constants.maxStemAspectLow.getValue(), constants.maxStemAspectHigh.getValue(), false, TOO_FAT); } // Retrieve the ratio thickness / length protected double getValue (Stick stick) { return stick.getAspect(); } } // FirstAdjacencyCheck // private static class FirstAdjacencyCheck extends Check<Stick> { protected FirstAdjacencyCheck () { super("LeftAdj", constants.maxStemAdjacencyLow.getValue(), constants.maxStemAdjacencyHigh.getValue(), false, TOO_HIGH_ADJACENCY); } // Retrieve the adjacency value protected double getValue (Stick stick) { int length = stick.getLength(); return (double) stick.getFirstStuck() / (double) length; } } // LastAdjacencyCheck // private static class LastAdjacencyCheck extends Check<Stick> { protected LastAdjacencyCheck () { super("RightAdj", constants.maxStemAdjacencyLow.getValue(), constants.maxStemAdjacencyHigh.getValue(), false, TOO_HIGH_ADJACENCY); } // Retrieve the adjacency value protected double getValue (Stick stick) { int length = stick.getLength(); return (double) stick.getLastStuck() / (double) length; } } // LeftCheck // private class LeftCheck extends Check<Stick> { protected LeftCheck (int val) throws ProcessingException { super("LeftLimit", val, val, true, OUTSIDE_SYSTEM); } // Retrieve the stick abscissa protected double getValue (Stick stick) { return stick.getFirstPos(); } } // RightCheck // private class RightCheck extends Check<Stick> { protected RightCheck (int val) throws ProcessingException { super("RightLimit", val, val, false, OUTSIDE_SYSTEM); } // Retrieve the stick abscissa protected double getValue (Stick stick) { return stick.getFirstPos(); } } // MinDensityCheck // private class MinDensityCheck extends Check<Stick> { protected MinDensityCheck () { super("MinDensity", constants.minDensityLow.getValue(), constants.minDensityHigh.getValue(), true, TOO_HOLLOW); } // Retrieve the density protected double getValue (Stick stick) { Rectangle rect = stick.getBounds(); double area = rect.width * rect.height; return (double) stick.getWeight() / area; } } // // MinChunkCheck // // /** // * Class <code>MinChunkCheck</code> checks for presence of a chunk (beam // * or note head) at top or bottom // */ // private class MinChunkCheck // extends Check<Stick> // // Half-dimensions for window at top and bottom, checking for // // chunks // private final int nWidth; // private final int nHeight; // protected MinChunkCheck () // throws ProcessingException // super("MinChunk", 0, 0, true, NO_CHUNK); // // Adjust chunk window according to system scale (problem, we // // have sheet scale and stave scale, not system scale...) // Scale scale = sheet.getScale(); // nWidth = scale.fracToPixels(constants.chunkWidth); // nHeight = scale.fracToPixels(constants.chunkHeight); // int area = 2 * nWidth * nHeight; // setLowHigh(area * constants.chunkRatioLow.getValue(), // area * constants.chunkRatioHigh.getValue()); // if (logger.isDebugEnabled()) { // logger.debug("MinPixLow=" + getLow() + ", MinPixHigh=" // + getHigh()); // protected double getValue (Stick stick) // // Retrieve the biggest stick chunk either at top or bottom // int res = 0; // res = Math.max(res, stick.getAliensAtStartFirst(nHeight, nWidth)); // res = Math.max(res, stick.getAliensAtStartLast(nHeight, nWidth)); // res = Math.max(res, stick.getAliensAtStopFirst(nHeight, nWidth)); // res = Math.max(res, stick.getAliensAtStopLast(nHeight, nWidth)); // if (logger.isDebugEnabled()) { // logger.debug("MinAliens= " + res + " for " + stick); // return res; // StemCheckSuite // private class StemCheckSuite extends CheckSuite<Stick> { public StemCheckSuite (SystemInfo info) throws ProcessingException { super("Stems " + info, constants.minCheckResult.getValue()); add(1, new MinLengthCheck()); add(1, new MaxAspectCheck()); add(1, new FirstAdjacencyCheck()); add(1, new LastAdjacencyCheck()); add(0, new LeftCheck(info.getLeft())); add(0, new RightCheck(info.getLeft() + info.getWidth())); add(2, new MinDensityCheck()); // This step is much too expensive (and not really useful ...) ////add(2, new MinChunkCheck()); if (logger.isDebugEnabled()) { dump(); } } } // MySectionPredicate // private static class MySectionPredicate extends VerticalArea.SectionPredicate { public boolean check (StickSection section) { // We process section for which glyph is null, NOISE, STRUCTURE boolean result = section.getGlyph() == null || !section.getGlyph().isWellKnown(); return result; } } // Constants // private static class Constants extends ConstantSet { Constant.Boolean displayFrame = new Constant.Boolean (true, "Should we display a frame on the stem sticks"); Constant.Integer maxDeltaLength = new Constant.Integer (4, "Maximum difference in run length to be part of the same section"); Constant.Double maxStemAspectLow = new Constant.Double (0.08, "Low Maximum aspect ratio for a stem stick"); Constant.Double maxStemAspectHigh = new Constant.Double (0.10, "High Maximum aspect ratio for a stem stick"); Constant.Double maxStemAdjacencyLow = new Constant.Double (0.60, "Low Maximum adjacency ratio for a stem stick"); Constant.Double maxStemAdjacencyHigh = new Constant.Double (0.70, "High Maximum adjacency ratio for a stem stick"); Scale.Fraction maxStemThickness = new Scale.Fraction (0.3, "Maximum thickness of an interesting vertical stick"); Scale.Fraction minStemLengthLow = new Scale.Fraction (2.5, "Low Minimum length for a stem"); Scale.Fraction minStemLengthHigh = new Scale.Fraction (3.5, "High Minimum length for a stem"); Constant.Double minCheckResult = new Constant.Double (0.50, "Minimum result for suite of check"); Scale.Fraction minForeWeight = new Scale.Fraction (1.25, "Minimum foreground weight for a section to be kept"); Constant.Double minDensityLow = new Constant.Double (0.8, "Low Minimum density for a stem"); Constant.Double minDensityHigh = new Constant.Double (0.9, "High Minimum density for a stem"); Scale.Fraction chunkHeight = new Scale.Fraction (0.33, "Height of half area to look for chunks"); Constant.Double chunkRatioLow = new Constant.Double (0.25, "LowMinimum ratio of alien pixels to detect chunks"); Constant.Double chunkRatioHigh = new Constant.Double (0.25, "HighMinimum ratio of alien pixels to detect chunks"); Scale.Fraction chunkWidth = new Scale.Fraction (0.33, "Width of half area to look for chunks"); Constants () { initialize(); } } }
package cc3k; import character.*; import floor.*; import java.util.*; import town.MainInteraction; /* * CC3K Ver 0.1.2 * Danny & Louis version * This is the main App class, still under construction */ public class App { final int maxRow = 25; final int maxCol = 79; private int level = 1; private boolean won = false; private boolean ascended = false; private Floor pFloor = null; Scanner input = new Scanner(System.in); private int calcScore(Player player){ int score; if (player.getRace().equals("Human")){ score = (int) (player.getGold() * 1.5); } else { score = player.getGold(); } return score; } private boolean checkStair(Floor floor,Obj obj, Player ply){ if (obj != null){ if(obj.getType() == 4){ if (level == 10){ System.out.println("You Win"); System.out.println("Score: " + calcScore(ply)); won = true; return true; } else{ level++; floor.ascend(); floor.spawn(); ply.resetBuff(); floor.changemsg("Player character has spawned "); ascended = true; return true; } } } return false; } private boolean direcTrap(String direc){ if(!"no".equals(direc) && !"we".equals(direc) && !"so".equals(direc) && !"ea".equals(direc) && !"nw".equals(direc) && !"ne".equals(direc) && !"se".equals(direc) && !"sw".equals(direc)){ System.err.println("Bad Input"); return false; } else return true; } private void startGame(){ String cmd; String direc; Player player; Obj tempObj; player = newGame(); pFloor = Floor.getInst(); while(true){ // Checking for death/victory if (player.getHp() <= 0){ System.out.println("You Died"); System.out.println("Score: " + calcScore(player)); cmd = "q"; } else{ if(won){ won = false; cmd = "q"; } else cmd = input.next(); } //cmd recognition and action if ("q".equals(cmd) || "r".equals(cmd)){ break; } else if ("town".equals(cmd)){ MainInteraction.visitShop(); pFloor.changemsg("Player just visited town."); } else if ("s1".equals(cmd)) { if ("attack".equals(player.getS1Type())) { direc = input.next(); player.castSkill(direc, 1); } else { player.castSkill("", 1); } } else if ("s2".equals(cmd)) { if ("attack".equals(player.getS2Type())) { direc = input.next(); player.castSkill(direc, 2); } else { player.castSkill("", 2); } } else if ("job".equals(cmd)) { player.listSkills(); continue; } else if ("u".equals(cmd) || "a".equals(cmd)){ direc = input.next(); while(!direcTrap(direc)){ direc = input.next(); } ascended = false; if ("u".equals(cmd)){ // TODO continue; } else player.attack(direc); } else{ if(direcTrap(cmd)){ int r = player.getpr(); int c = player.getpc(); if (cmd.equals("no")) tempObj = pFloor.getObj(r-1, c); else if (cmd.equals("ne")) tempObj = pFloor.getObj(r-1, c+1); else if (cmd.equals("ea")) tempObj = pFloor.getObj(r, c+1); else if (cmd.equals("se")) tempObj = pFloor.getObj(r+1, c+1); else if (cmd.equals("so")) tempObj = pFloor.getObj(r+1, c); else if (cmd.equals("sw")) tempObj = pFloor.getObj(r+1, c-1); else if (cmd.equals("we")) tempObj = pFloor.getObj(r, c-1); else tempObj = pFloor.getObj(r-1, c-1); if(!checkStair(pFloor, tempObj, player)){ player.makeMove(cmd); ascended = false; } } else continue; } if (!won && !("r".equals(cmd))){ for (int r = 0; r < maxRow; r++){ for (int c = 0; c < maxCol; c++){ tempObj = pFloor.getObj(r, c); if (tempObj != null){ if (tempObj.getType() == 1){ Enemy enemy = (Enemy) tempObj; enemy.resetMoved(); } } } } if (!ascended){ for (int r = 0; r < maxRow; r++){ for (int c = 0; c < maxCol; c++){ tempObj = pFloor.getObj(r, c); if (tempObj != null){ if (tempObj.getType() == 1){ Enemy enemy = (Enemy) tempObj; enemy.randMove(); } } } } } display(); } } } /* This function may have lots of pass by value/reference error occurring, due to the c++ version applied a lot of reference techniques. */ private Player newGame(){ Player player = null; String cmd; boolean badInput; for (int x = 0; x < 50; x++) System.out.println('\n'); System.out.println("Welcome to CC3K ver 0.1.2"); System.out.println("Choose your race:"); System.out.println("Human(h), Elves(e), Dwarf(d), Orc(o)"); System.out.println(); System.out.println("Quit(q) Help(?)"); do{ cmd = input.next(); // Scanner in? if (!("h".equals(cmd)) && !("e".equals(cmd)) && !("d".equals(cmd)) && !("o".equals(cmd)) && !("q".equals(cmd)) && !("?".equals(cmd))){ System.out.println("Bad Input, try again\n"); badInput = true; } else{ badInput = false; Player.resetPlayer(); if ("h".equals(cmd)) player = Player.getPlayer(0); else if ("e".equals(cmd)) player = Player.getPlayer(2); else if ("d".equals(cmd)) player = Player.getPlayer(1); else if ("o".equals(cmd)) player = Player.getPlayer(3); else if ("q".equals(cmd)){ System.exit(0); } else if ("?".equals(cmd)){ help(); badInput = true; //Setting badinput here to be true is to //loop the input one more time, let player rechoose. } } }while(badInput); // Let player choose a job System.out.println("Choose your job:"); System.out.println("Swordsman(0), Rogue(1), Acolyte(2)"); cmd = input.next(); badInput = true; while(badInput) { if (player != null) { if ("0".equals(cmd)) { player.setJob(0); } else if ("1".equals(cmd)) { player.setJob(1); } else if ("2".equals(cmd)) { player.setJob(2); } badInput = false; } else { badInput = true; } } level = 1; pFloor = Floor.getInst(); pFloor.spawn(); pFloor.changemsg("Player character has spawned"); display(); return player; } private void display() { Player player = Player.getPlayer(); pFloor.display(); System.out.printf("Race: " + player.getRace() + " "); System.out.printf(" Gold " + player.getGold()); System.out.println("\t\t\t\t\t\tFloor " + level); System.out.println("HP: " + player.getHp()); System.out.println("MP: " + player.getMp()); System.out.println("Atk: " + player.getAtk()); System.out.println("Def: " + player.getDef()); System.out.println("Str: " + player.getStr() + " Dex: " + player.getDex() + " Int: " + player.getInt()); System.out.println("Job: " + player.getJob().toLowerCase()); System.out.println("s1. " + player.getS1() + " s2. " + player.getS2()); System.out.print("Action: "); pFloor.showMsg(); System.out.println(); pFloor.clearmsg(); } private void help() { System.out.println("Move: "); System.out.println("no = move north"); System.out.println("ea = move east"); System.out.println("so = move south"); System.out.println("we = move west"); System.out.println("nw = move northwest"); System.out.println("ne = move northeast"); System.out.println("se = move southeast"); System.out.println("sw = move southwest"); System.out.println(); System.out.println("Attack: "); System.out.println("input 'a' followed by direction"); System.out.println("e.g.: ano = attack north"); System.out.println(); System.out.println("Use potion: "); System.out.println("input 'u' followed by direction"); System.out.println(); System.out.println("Cast skill: "); System.out.println("input 's1' or 's2' followed by direction"); } public static void main(String[] args) { new App().startGame(); System.exit(0); } }
package def; import java.io.*; import java.util.*; import java.net.*; //import net.sf.json.*; public class Main implements Runnable{ Printer p; int pageBegin,pageEnd; ArrayList<String> topicsString; ArrayList<Topic> topics; FileWriter fw; public static void main(String[] args) throws Exception{ Main no1=new Main(0,3); Thread no1_thread=new Thread(no1); no1_thread.start(); } public void run(){ // TODO Auto-generated method stub topicsString=new ArrayList<String>(); topics=new ArrayList<Topic>(); p=new Printer(); for(int i=pageBegin;i<pageEnd;i++){ getTopic(i); } workTopic(); printToFile(); } public synchronized void printToFile(){ try{ fw=new FileWriter("./output.txt",true); fw.write("{\n"); for(int i=0;i<topics.size();i++){ String title=topics.get(i).title; String id=topics.get(i).id; String text=topics.get(i).text; String user=topics.get(i).user; title=title.replaceAll("\"","'"); text=text.replaceAll("\"","'"); user=user.replaceAll("\"","'"); fw.write("[{\"id\":\""+id+"\",\"title\":\""+title+"\""+title+"\",\"text\":\""+text+"\",\"user\":\""+user+"\"},\n"); } fw.write("\n]\n}"); fw.flush(); fw.close(); }catch(Exception e){ e.printStackTrace(); } } public Main(int pageBegin,int pageEnd){ this.pageBegin=pageBegin; this.pageEnd=pageEnd; } public void getTopic(int page){ String url="http://tieba.baidu.com/f?kw=%E5%B0%91%E5%B9%B4%E7%94%B5%E8%84%91%E4%B8%96%E7%95%8C&ie=utf-8&pn=" +workPage(page); String html=sendGet(url); String[] footer=html.split("<span class=\"card_numLabel\"></span>"); String[] header=footer[1].split("<span class=\"red_text\">"); //String[] topicStr=header[0].split("<div class=\"threadlist_abs threadlist_abs_onlyline"); String[] topicStr=header[0].split("<div class=\"col2_right j_threadlist_li_right \">"); /*for(int i=0;i<topicStr.length-1;i++){ topicsString.add(topicStr[i+1]); }*/ topicsString.add(topicStr[1]); topicsString.add(topicStr[2]); } public void workTopic(){ for(int i=0;i<topicsString.size();i++){ String atopic=topicsString.get(i); String id=getMiddleText(atopic, "<a href=\"/p/", "\" title="); String title=getMiddleText(atopic,"target=\"_blank\" class=\"j_th_tit \">","</a></div><div class=\"threadlist_author pull_right"); String user=getMiddleText(atopic,"title=\": ","\"data-field=(.*)><i class=\"icon_author\"></i><span class"); String text=getArticle(id); topics.add(new Topic(id,title,text,user)); } } public String getArticle(String id){ String url="http://tieba.baidu.com/p/"+id; String html=sendGet(url); return getMiddleText(html,"class=\"d_post_content j_d_post_content \">", "<div class=\"user-hide-post-down\" style=\"display: none;\">"); } public String getMiddleText(String text,String header,String footer){ String[] work_footer=text.split(header); String[] work_header=work_footer[1].split(footer); return work_header[0]; } public int workPage(int page){ if(page==0){ return 0; }else{ return page*50; } } public String sendGet(String url) { String result = ""; BufferedReader in = null; try { String urlNameString = url; URL realUrl = new URL(urlNameString); // URL URLConnection connection = realUrl.openConnection(); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.connect(); Map<String, List<String>> map = connection.getHeaderFields(); // BufferedReaderURL in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.err.println("Sent get message error!" + e); e.printStackTrace(); } // finally finally { try { System.out.println("Sent get message '"+url+"' successfully!"); if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } }
package eco; import java.util.Random; import eco.Eco; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; public class Main { public static Random random = new Random(); public static final int fov = 90; public static final int height = 620; public static final int width = 854; public static volatile int year = 1; public static volatile int wheatPrice = 20; public static volatile int oldtWheat = 0; public static volatile int aggDemand; public static volatile int oldaggDemand; public volatile static int tAcres = 1000; public static volatile float fBirthRate = 0.03f; public static volatile float fDeathRate = 0.02f; public static volatile float wBirthRate = 0.008f; public static volatile float wDeathRate = 0.002f; public static void main(String[] args) { System.out.println("Welcome to EcoLand!"); init(); tick(); } public static void tick(){ for(int i = 1; i < 2000; i++){ year = i; //One tick is 1 year int wPop = Warrior.wPop(); int fPop = Farmer.fPop(); int tPop = wPop + fPop; int farmPacks = Wheat.farmPacks(tAcres); int unemployedFarmers = Wheat.unemployedFarmers(farmPacks, fPop); int employedFarmers = Wheat.employedFarmers(fPop, unemployedFarmers); Warrior.wHunger(wPop); Wheat.tWheat(fPop, tAcres, employedFarmers); aggDemand = ((Farmer.fHunger * Farmer.fPop) + (Warrior.wHunger * Warrior.wPop)); wheatPrice = Market.wheatPrice(wheatPrice); int tMoney = Money.tMoney(Wheat.tWheat, Warrior.wHunger, Farmer.fHunger, wheatPrice); System.out.println("Year: " + year); System.out.println("Wheat Produced this year: " + Wheat.tWheat); System.out.println("Price of wheat: " + wheatPrice); System.out.println("Total number of Warriors: " + wPop); System.out.println("Total number of Farmers: " + fPop); System.out.println(" Unemployed Farmers: " + unemployedFarmers); System.out.println(" Employed Farmers: " + employedFarmers); System.out.println("Total Population: " + tPop); System.out.println("Money in the Treasury: " + tMoney); System.out.println("\n"); oldaggDemand = aggDemand; oldtWheat = Wheat.tWheat; //Render.drawString("yourmessage", 10, 10); tPop = Eco.tryToUpdatePop(); tAcres= Eco.tick(year); } Eco.simDone(); } public static void init(){ //Initializes the simulation Money.tMoney = 500; Wheat.tWheat = 10; Warrior.wPop(); Warrior.wHunger(Warrior.wPop); Farmer.fPop(); Farmer.fHunger(Farmer.fPop); Eco.init(); } public static int randInt(int max){ //Returns a random number below max. return random.nextInt(max); } public static int randInt(int min, int max){ //Returns a random number between min and max. return min + random.nextInt((max + 1)- min); } public static void ioUpdate(){ if (Keyboard.isKeyDown(Keyboard.KEY_R)){ Render.rot -= 0.5f; } if (Keyboard.isKeyDown(Keyboard.KEY_F)){ Render.rot += 0.5f; } if (Keyboard.isKeyDown(Keyboard.KEY_W)){ Render.z += 0.1f; Render.camera.moveForward(0.1f); } if (Keyboard.isKeyDown(Keyboard.KEY_A)){ Render.x -= 0.1f; Render.camera.moveRight(0.1f); } if (Keyboard.isKeyDown(Keyboard.KEY_S)){ Render.z -= 0.1f; Render.camera.moveBack(0.1f); } if (Keyboard.isKeyDown(Keyboard.KEY_D)){ Render.x += 0.1f; Render.camera.moveLeft(0.1f); } if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)){ //Render.y += 0.01f; Render.camera.moveDown(0.1f); } if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)){ //Render.y -= 0.01f; Render.camera.moveUp(0.1f); } if (Keyboard.isKeyDown(Keyboard.KEY_O)){ World.messages.add(new Message("dank messages", 10, 10, 300)); } } }
package nl.sense_os.commonsense.client.viz.data; import nl.sense_os.commonsense.client.viz.data.timeseries.BackEndDataPoint; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; public class GetSensorDataResponseJso extends JavaScriptObject { protected GetSensorDataResponseJso() { // empty protected constructor } /** * Creates a GetSensorDataResponseJso from the JSON response from CommonSense. Also converts any * "embedded" JSON-disguised-as-String objects, so that e.g. * <code>{"foo":"{\"bar\":\"baz\"}"}</code> will get completely converted. * * @param source * Raw response from CommonSense. * @return JavaScriptObject representing the response. */ public final static native GetSensorDataResponseJso create(String source) /*-{ function stripslashes(str) { return (str + '').replace(/\\(.?)/g, function(s, n1) { switch (n1) { case '\\': return '\\'; case '0': return '\u0000'; case '': return ''; default: return n1; } }); } var stripped = stripslashes(source); var jsonFixed = stripped.replace(/:\"{/g, ':{').replace(/}\"/g, '}'); return eval('(' + jsonFixed + ')'); }-*/; /** * @return The 'data' property of the response, containing an array with sensor data. If 'data' * is undefined, an empty array is returned. */ public final native JsArray<BackEndDataPoint> getData() /*-{ if (undefined != this.data) { return this.data; } else { return []; } }-*/; /** * @return The 'total' property of the response. If 'total' is undefined, -1 is returned. */ public final native int getTotal() /*-{ if (undefined != this.total) { return this.total; } else { return -1; } }-*/; }
package org.adaptlab.chpir.android.participanttracker.models; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.adaptlab.chpir.android.activerecordcloudsync.SendReceiveModel; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import com.activeandroid.query.Select; @Table(name = "Participant") public class Participant extends SendReceiveModel { private static final String TAG = "Participant"; private static final String LABEL_DELIMITER = " "; @Column(name = "SentToRemote") private boolean mSent; @Column(name = "ParticipantType", onUpdate = Column.ForeignKeyAction.CASCADE, onDelete = Column.ForeignKeyAction.CASCADE) private ParticipantType mParticipantType; @Column(name = "UUID") private String mUUID; @Column(name = "RemoteId", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) private Long mRemoteId; public Participant() { super(); mUUID = UUID.randomUUID().toString(); mSent = false; } public Participant(ParticipantType participantType) { super(); mParticipantType = participantType; mUUID = UUID.randomUUID().toString(); mSent = false; } @Override public JSONObject toJSON() { JSONObject json = new JSONObject(); try { JSONObject jsonObject = new JSONObject(); // TODO: Change to participant id jsonObject.put("participant_type_id", getParticipantType().getRemoteId()); jsonObject.put("uuid", getUUID()); if (this.getRemoteId() == null) { jsonObject.put("device_uuid", AdminSettings.getInstance().getDeviceIdentifier()); jsonObject.put("device_label", AdminSettings.getInstance().getDeviceLabel()); } json.put("participant", jsonObject); } catch (JSONException je) { Log.e(TAG, "JSON exception", je); } return json; } public ParticipantType getParticipantType() { return mParticipantType; } public void setParticipantType(ParticipantType participantType) { mParticipantType = participantType; } public String getUUID() { return mUUID; } public void setUUID(String uuid) { mUUID = uuid; } public static List<Participant> getAll() { return new Select().from(Participant.class).orderBy("Id ASC").execute(); } public static List<Participant> getAllByParticipantType(ParticipantType participantType) { return new Select().from(Participant.class).where("ParticipantType = ?", participantType.getId()).orderBy("Id DESC").execute(); } public static List<Participant> getAllByParticipantType(ParticipantType participantType, String query) { return new Select("Participant.*") .distinct() .from(Participant.class) .innerJoin(ParticipantProperty.class) .on("Participant.Id = ParticipantProperty.Participant AND Participant.ParticipantType = ? AND ParticipantProperty.Value LIKE ?", participantType.getId(), "%" + query + "%") .orderBy("Participant.Id DESC") .execute(); } public boolean hasParticipantProperty(Property property) { if (getId() == null) return false; for (ParticipantProperty participantProperty : getParticipantProperties()) { if (participantProperty.getProperty().equals(property)) { return true; } } return false; } /* * If a participant property already exist for this type, return it. * * If it does not exist, return a new participant property initialized * with a null value. * */ public ParticipantProperty getParticipantProperty(Property property) { for (ParticipantProperty participantProperty : getParticipantProperties()) { if (participantProperty.getProperty().equals(property)) { return participantProperty; } } return new ParticipantProperty(this, property, null); } /* * If a relationship already exist for this type, return it. * * If it does not exist, return a new relationship. * */ public Relationship getRelationshipByRelationshipType(RelationshipType relationshipType) { for (Relationship relationship : getRelationships()) { if (relationship.getRelationshipType().equals(relationshipType)) { return relationship; } } return new Relationship(relationshipType); } public boolean hasRelationshipByRelationshipType(RelationshipType relationshipType) { if (getId() == null) return false; for (Relationship relationship : getRelationships()) { if (relationship.getRelationshipType().equals(relationshipType)) { return true; } } return false; } public static int getCount() { return getAll().size(); } public static int getCountByParticipantType(ParticipantType participantType) { return getAllByParticipantType(participantType).size(); } public static Participant findById(Long id) { return new Select().from(Participant.class).where("Id = ?", id).executeSingle(); } public static Participant findByRemoteId(Long remoteId) { return new Select().from(Participant.class).where("RemoteId = ?", remoteId).executeSingle(); } public static Participant findByUUID(String uuid) { return new Select().from(Participant.class).where("UUID = ?", uuid).executeSingle(); } public List<ParticipantProperty> getParticipantProperties() { return new Select().from(ParticipantProperty.class).where("Participant = ?", getId()).execute(); } public List<Relationship> getRelationships() { return new Select().from(Relationship.class).where("ParticpantOwner = ?", getId()).orderBy("RelationshipType ASC").execute(); } @Override public boolean isSent() { return mSent; } @Override public boolean readyToSend() { return true; //TODO: For Testing...FIX - also in ParticipantProperty } @Override public void setAsSent() { mSent = true; } public List<Property> getProperties() { return Property.getAllByParticipantType(getParticipantType()); } public String getLabel() { String label = ""; for (ParticipantProperty participantProperty : getParticipantProperties()) { if (participantProperty.getProperty().getUseAsLabel()) { if (!label.isEmpty()) label += LABEL_DELIMITER; label += participantProperty.getValue(); } } if (label.isEmpty()) { return mUUID; } else { return label; } } @Override public void createObjectFromJSON(JSONObject jsonObject) { try { String uuid = jsonObject.getString("uuid"); Participant participant = Participant.findByUUID(uuid); if (participant == null) { participant = this; } participant.setUUID(uuid); Long remoteId = jsonObject.getLong("id"); participant.setRemoteId(remoteId); Long participantTypeId = jsonObject.getLong("participant_type_id"); ParticipantType participantType = ParticipantType.findByRemoteId(participantTypeId); if (participantType != null) { participant.setParticipantType(participantType); } if (jsonObject.isNull("deleted_at")) { participant.save(); } else { Log.i(TAG, "deleted participant: " + jsonObject.toString()); Participant p = Participant.findByUUID(uuid); if (p != null) { p.delete(); } } } catch (JSONException je) { Log.e(TAG, "Error parsing object json", je); } } private void setRemoteId(Long id) { mRemoteId = id; } @Override public Long getRemoteId() { return mRemoteId; } public String getMetadata() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put("participant_uuid", getUUID()); jsonObject.put("participant_type", getParticipantType().getLabel()); for (ParticipantProperty participantProperty : getMetadataParticipantProperties(this)) { jsonObject.put(participantProperty.getProperty().getLabel(), participantProperty.getValue()); } // Add metadata for relationships for (Relationship relationship : getRelationships()) { jsonObject.put(relationship.getRelationshipType().getLabel(), relationship.getParticipantRelated().getUUID()); for (ParticipantProperty participantProperty : getMetadataParticipantProperties(relationship.getParticipantRelated())) { jsonObject.put(relationship.getRelationshipType().getLabel() + " - " + participantProperty.getProperty().getLabel(), participantProperty.getValue()); } } return jsonObject.toString(); } private List<ParticipantProperty> getMetadataParticipantProperties(Participant participant) { List<ParticipantProperty> participantProperties = new ArrayList<ParticipantProperty>(); for (Property property : participant.getProperties()) { if (property.isIncludedInMetadata()) { if (participant.hasParticipantProperty(property)) { participantProperties.add(participant.getParticipantProperty(property)); } } } return participantProperties; } }
package org.ensembl.healthcheck.testcase.generic; import org.ensembl.healthcheck.DatabaseRegistry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase; /** * Check that the attrib_type table is the same in all necessary databases. */ public class AttribTypeAcrossSpecies extends MultiDatabaseTestCase { private DatabaseType[] types = {DatabaseType.CORE, DatabaseType.OTHERFEATURES, DatabaseType.VEGA}; /** * Creates a new instance of AttribTypeTablesAcrossSpecies */ public AttribTypeAcrossSpecies() { addToGroup("release"); setDescription("Check that the attrib_type table contains the same information for all databases with the same species."); } /** * Make sure that the assembly tables are all the same. * * @param dbr * The database registry containing all the specified databases. * @return True if the assembly table is the same across all the species in * the registry. */ public boolean run(DatabaseRegistry dbr) { return checkTableAcrossSpecies("attrib_type", dbr, types, "attrib_type tables all the same", "attrib_type tables are different", "WHERE code NOT LIKE 'GeneNo%'"); } // run } // AttribTypeTablesAcrossSpecies
package hangman; import java.awt.BorderLayout; import java.io.FileNotFoundException; import javax.swing.JFrame; public class HangmanRunner { public static void main(String[] args) throws FileNotFoundException { JFrame frame = new JFrame("HANGMAN!"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); // frame.setAlwaysOnTop(true); HangmanPanel HangmanPanel = new HangmanPanel(); frame.add(HangmanPanel, BorderLayout.CENTER); frame.setSize(700, 700); frame.setVisible(true); } }