diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/cache/TableAreaLayout.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/cache/TableAreaLayout.java index fcf60d031..acc0445fd 100644 --- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/cache/TableAreaLayout.java +++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/cache/TableAreaLayout.java @@ -1,1300 +1,1300 @@ /*********************************************************************** * Copyright (c) 2004, 2007 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.report.engine.layout.pdf.cache; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import org.eclipse.birt.report.engine.api.InstanceID; import org.eclipse.birt.report.engine.content.ICellContent; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IReportContent; import org.eclipse.birt.report.engine.content.IRowContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.content.ITableContent; import org.eclipse.birt.report.engine.css.engine.StyleConstants; import org.eclipse.birt.report.engine.layout.LayoutUtil; import org.eclipse.birt.report.engine.layout.area.IArea; import org.eclipse.birt.report.engine.layout.area.impl.AbstractArea; import org.eclipse.birt.report.engine.layout.area.impl.AreaFactory; import org.eclipse.birt.report.engine.layout.area.impl.CellArea; import org.eclipse.birt.report.engine.layout.area.impl.ContainerArea; import org.eclipse.birt.report.engine.layout.area.impl.RowArea; import org.eclipse.birt.report.engine.layout.area.impl.TableArea; import org.eclipse.birt.report.engine.layout.area.impl.TextArea; import org.eclipse.birt.report.engine.layout.pdf.BorderConflictResolver; import org.eclipse.birt.report.engine.layout.pdf.PDFTableLM.TableLayoutInfo; import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil; import org.eclipse.birt.report.engine.presentation.UnresolvedRowHint; import org.w3c.dom.css.CSSValue; //FIXME add DropCell extends CellArea public class TableAreaLayout { protected CursorableList rows = new CursorableList(); /** * Border conflict resolver */ protected BorderConflictResolver bcr = new BorderConflictResolver( ); protected TableLayoutInfo layoutInfo = null; protected ITableContent tableContent; protected ICellContent lastCellContent; protected int startCol; protected int endCol; protected boolean hasDropCell = true; protected Row unresolvedRow; protected boolean firstRow = true; public TableAreaLayout(ITableContent tableContent, TableLayoutInfo layoutInfo, int startCol, int endCol) { this.tableContent = tableContent; this.layoutInfo = layoutInfo; this.startCol = startCol; this.endCol = endCol; } public void initTableLayout(UnresolvedRowHint hint) { if(hint!=null) { IReportContent report = tableContent.getReportContent( ); IRowContent rowContent = report.createRowContent( ); InstanceID rowId = InstanceID.parse( hint.getRowId( )); rowContent.setInstanceID( rowId ); rowContent.setParent( tableContent ); RowArea rowArea = AreaFactory.createRowArea( rowContent ); unresolvedRow = new Row(rowArea, startCol, endCol, false); for(int i=startCol; i<=endCol; i++) { ICellContent cellContent = report.createCellContent( ); hint.initUnresolvedCell( cellContent, rowId, i ); cellContent.setParent( rowContent ); CellArea cellArea = AreaFactory.createCellArea( cellContent ); unresolvedRow.addArea( cellArea ); i = i + cellArea.getColSpan( ) - 1; } } } public void setUnresolvedRow(Row row) { this.unresolvedRow = row; } public Row getUnresolvedRow() { return (Row)rows.getCurrent( ); } protected int resolveBottomBorder(CellArea cell, boolean isLast) { IStyle tableStyle = tableContent.getComputedStyle( ); IContent cellContent = cell.getContent( ); IStyle columnStyle = getColumnStyle( cell.getColumnID( ) ); IStyle cellAreaStyle = cell.getStyle( ); if(isLast) { IStyle cellContentStyle = cellContent.getComputedStyle( ); IStyle rowStyle = ((IContent)cellContent.getParent()).getComputedStyle( ) ; bcr.resolveTableBottomBorder( tableStyle, rowStyle, columnStyle, cellContentStyle, cellAreaStyle ); } else { bcr.resolveTableBottomBorder( tableStyle, null, columnStyle, null, cellAreaStyle ); } return PropertyUtil.getDimensionValue( cellAreaStyle .getProperty( StyleConstants.STYLE_BORDER_BOTTOM_WIDTH ) ); } protected void add(ContainerArea area, ArrayList rows) { if(area instanceof RowArea) { rows.add( area ); } else { Iterator iter = area.getChildren( ); while(iter.hasNext( )) { ContainerArea container = (ContainerArea)iter.next(); add(container, rows); } } } public void remove(TableArea table) { firstRow = true; ArrayList rowColloection = new ArrayList(); add(table, rowColloection); Iterator iter = rows.iterator( ); while(iter.hasNext( )) { Row row = (Row)iter.next( ); if(rowColloection.contains( row.getArea( ) )) { iter.remove( ); } } rows.resetCursor( ); } protected IStyle getLeftCellContentStyle(Row lastRow, int columnID) { if(lastCellContent!=null && lastCellContent.getColumn( ) + lastCellContent.getColSpan( )<= columnID) { if(lastRow!=null && columnID>0) { CellArea cell = lastRow.getCell( columnID-1 ); if(cell!=null && cell.getRowSpan( )<0 && cell.getContent( )!=null) { return cell.getContent( ).getComputedStyle( ); } } return lastCellContent.getComputedStyle( ); } if(lastRow!=null && columnID>0) { CellArea cell = lastRow.getCell( columnID-1 ); if(cell!=null && cell.getRowSpan( )>1 && cell.getContent( )!=null) { return cell.getContent( ).getComputedStyle( ); } } return null; } /** * resolve cell border conflict * * @param cellArea */ public void resolveBorderConflict( CellArea cellArea, boolean isFirst ) { IContent cellContent = cellArea.getContent( ); int columnID = cellArea.getColumnID( ); int colSpan = cellArea.getColSpan( ); IRowContent row = (IRowContent) cellContent.getParent( ); IStyle cellContentStyle = cellContent.getComputedStyle( ); IStyle cellAreaStyle = cellArea.getStyle( ); IStyle tableStyle = tableContent.getComputedStyle( ); IStyle rowStyle = row.getComputedStyle( ); IStyle columnStyle = getColumnStyle( columnID ); IStyle preRowStyle = null; IStyle preColumnStyle = getColumnStyle( columnID - 1 ); IStyle leftCellContentStyle = null; IStyle topCellStyle = null; Row lastRow = null; if(rows.size( )>0 ) { lastRow = (Row)rows.getCurrent( ); } leftCellContentStyle = getLeftCellContentStyle(lastRow, columnID); if(lastRow!=null) { preRowStyle = lastRow.getContent( ).getComputedStyle( ); CellArea cell = lastRow.getCell( columnID ); if(cell!=null && cell.getContent( )!=null) { topCellStyle = cell.getContent( ).getComputedStyle( ); } } //FIXME if ( rows.size( ) == 0 && lastRow==null) { // resolve top border if(isFirst) { bcr.resolveTableTopBorder( tableStyle, rowStyle, columnStyle, cellContentStyle, cellAreaStyle ); } else { bcr.resolveTableTopBorder( tableStyle, null, columnStyle, null, cellAreaStyle ); } // resolve left border if ( columnID == startCol ) { bcr.resolveTableLeftBorder( tableStyle, rowStyle, columnStyle, cellContentStyle, cellAreaStyle ); } else { bcr.resolveCellLeftBorder( preColumnStyle, columnStyle, leftCellContentStyle, cellContentStyle, cellAreaStyle ); } // resovle right border if ( columnID + colSpan - 1 == endCol ) { bcr.resolveTableRightBorder( tableStyle, rowStyle, columnStyle, cellContentStyle, cellAreaStyle ); } } else { if(isFirst) { bcr.resolveCellTopBorder( preRowStyle, rowStyle, topCellStyle, cellContentStyle, cellAreaStyle ); } else { bcr.resolveCellTopBorder( preRowStyle, null, topCellStyle, null, cellAreaStyle ); } // resolve left border if ( columnID == startCol ) { // first column bcr.resolveTableLeftBorder( tableStyle, rowStyle, columnStyle, cellContentStyle, cellAreaStyle ); } else { // TODO fix row span conflict bcr.resolveCellLeftBorder( preColumnStyle, columnStyle, leftCellContentStyle, cellContentStyle, cellAreaStyle ); } // resolve right border if ( columnID + colSpan-1 == endCol ) { bcr.resolveTableRightBorder( tableStyle, rowStyle, columnStyle, cellContentStyle, cellAreaStyle ); } } lastCellContent = (ICellContent)cellContent; } /** * get column style * * @param columnID * @return */ private IStyle getColumnStyle( int columnID ) { // current not support column style return null; } protected void verticalAlign( CellArea c ) { CellArea cell; if(c instanceof DummyCell) { cell = ((DummyCell)c).getCell( ); } else { cell = c; } IContent content = cell.getContent( ); if ( content == null ) { return; } CSSValue verticalAlign = content.getComputedStyle( ).getProperty( IStyle.STYLE_VERTICAL_ALIGN ); if ( IStyle.BOTTOM_VALUE.equals( verticalAlign ) || IStyle.MIDDLE_VALUE.equals( verticalAlign ) ) { int totalHeight = 0; Iterator iter = cell.getChildren( ); while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); totalHeight += child.getAllocatedHeight( ); } int offset = cell.getContentHeight( ) - totalHeight; if ( offset > 0 ) { if ( IStyle.BOTTOM_VALUE.equals( verticalAlign ) ) { iter = cell.getChildren( ); while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); child.setAllocatedPosition( child.getAllocatedX( ), child.getAllocatedY( ) + offset ); } } else if ( IStyle.MIDDLE_VALUE.equals( verticalAlign ) ) { iter = cell.getChildren( ); while ( iter.hasNext( ) ) { AbstractArea child = (AbstractArea) iter.next( ); child.setAllocatedPosition( child.getAllocatedX( ), child.getAllocatedY( ) + offset / 2 ); } } } } CSSValue align = content.getComputedStyle( ).getProperty( IStyle.STYLE_TEXT_ALIGN ); // single line if ( ( IStyle.RIGHT_VALUE.equals( align ) || IStyle.CENTER_VALUE .equals( align ) ) ) { Iterator iter = cell.getChildren( ); while ( iter.hasNext( ) ) { AbstractArea area = (AbstractArea) iter.next( ); int spacing = cell.getContentWidth( ) - area.getAllocatedWidth( ) ; if(spacing>0) { if ( IStyle.RIGHT_VALUE.equals( align ) ) { area.setAllocatedPosition( spacing + area.getAllocatedX( ), area.getAllocatedY( ) ); } else if ( IStyle.CENTER_VALUE .equals( align ) ) { area.setAllocatedPosition( spacing / 2 + area.getAllocatedX( ), area.getAllocatedY( ) ); } } } } } public void reset(TableArea table) { firstRow = true; Iterator iter = rows.iterator( ); while(iter.hasNext( )) { Row row = (Row)iter.next( ); if(table.contains( row.getArea( ) )) { iter.remove( ); } } rows.resetCursor( ); } public int resolveDropCells(int dropValue) { /* * 1. scan current row and calculate row height * 2. update the height of drop cells * 3. update the height of row */ assert(dropValue<0); if(rows.size( )==0 || !hasDropCell) { return 0; } Row row = (Row)rows.getCurrent( ); assert(row!=null); int rowHeight = row.getArea( ).getHeight( ); int height = rowHeight; //scan for Max height for drop cells for( int i=startCol; i<=endCol; i++ ) { CellArea cell = row.getCell( i ); if ( cell == null ) continue; if( cell.getRowSpan( )==dropValue ) { if ( cell instanceof DummyCell ) { height = Math.max( height, cell.getHeight() + rowHeight ); } else { height = Math.max( height, cell.getHeight( ) ); } } } int delta = height - rowHeight; HashSet dropCells = new HashSet(); for( int i=startCol; i<=endCol; i++ ) { CellArea cell = row.getCell( i ); if ( cell == null ) continue; if ( cell instanceof DummyCell ) { int remainCellHeight = cell.getHeight( ) - delta; cell.setHeight( remainCellHeight ); if ( cell.getRowSpan( ) == dropValue ) { if (cell.getHeight()<0) { //update the height of drop cell if the remain height in dummy cell is less than 0 CellArea ref = ((DummyCell)cell).getCell( ); if(!dropCells.contains( ref )) { ref.setHeight( ref.getHeight( ) - remainCellHeight ); cell.setHeight( 0 ); verticalAlign( ref ); dropCells.add( ref ); } } cell.setRowSpan( 1 ); } } else if( (cell.getRowSpan() == 1) ) { if ( delta != 0 ) { cell.setHeight( height ); row.getArea().setHeight(height); verticalAlign( cell ); } } } return delta; } /*protected void keepUnresolvedCell(Row lastRow) { unfinishedRow = new UnresolvedRow(lastRow.getContent( )); for(int i=0; i<columnNumber; i++) { CellArea cell = lastRow.getCell( start + i ); if(cell!=null) { int rowSpan = cell.getRowSpan( ); if(rowSpan< 0 || rowSpan>1) { //FIXME resolve conflict? unfinishedRow.addUnresolvedCell( (ICellContent) cell .getContent( ), getLeftRowSpan( lastRow.finished, rowSpan ) ); } else if(rowSpan==1) { if(!lastRow.finished) { unfinishedRow.addUnresolvedCell( (ICellContent) cell .getContent( ), 1 ); } } } } }*/ public int resolveAll() { /* * 1. scan current row and calculate row height * 2. update the height of drop cells * 3. update the height of row */ if(rows.size( )==0 || !hasDropCell) { return 0; } Row row = (Row)rows.getCurrent( ); int rowHeight = row.getArea( ).getHeight( ); int height = rowHeight; boolean hasDropCell = false; //scan for Max height for drop cells for(int i=startCol; i<=endCol; i++) { CellArea cell = row.getCell( i ); if(cell!=null) { if(isDropCell( cell ) || cell.getRowSpan( )>1 ) { if ( cell instanceof DummyCell ) { height = Math.max( height, cell.getHeight() + rowHeight ); } else { height = Math.max( height, cell.getHeight( ) ); } hasDropCell = true; } } } int delta = height - rowHeight; if(hasDropCell) { //unfinishedRow = new UnresolvedRow(row.getContent( )); HashSet dropCells = new HashSet(); if(delta>0) { row.getArea( ).setHeight( height ); } for(int i=startCol; i<=endCol; i++) { CellArea cell = row.getCell( i ); if(cell==null) { continue; } int rowSpan = cell.getRowSpan( ); if(rowSpan< 0 || rowSpan>1) { if(cell instanceof DummyCell) { CellArea ref = ((DummyCell)cell).getCell( ); int cellHeight = cell.getHeight( ); int refHeight = ref.getHeight( ); if(!dropCells.contains( ref )) { ref.setHeight( refHeight - cellHeight + delta ); verticalAlign( ref ); dropCells.add( ref ); } } else { cell.setHeight( height ); verticalAlign( cell ); } //FIXME resolve conflict? /*unfinishedRow.addUnresolvedCell( (ICellContent) cell .getContent( ), getLeftRowSpan( row.finished, rowSpan ) );*/ } else if(rowSpan==1) { if(cell instanceof DummyCell) { CellArea ref = ((DummyCell)cell).getCell( ); if(!dropCells.contains( ref )) { ref.setHeight( ref.getHeight( ) + delta ); if(delta>0) { verticalAlign( ref ); } dropCells.add( ref ); } } else { cell.setHeight( height ); verticalAlign( cell ); } /*if(row!=null && !row.finished) { unfinishedRow.addUnresolvedCell( (ICellContent) cell .getContent( ), 1 ); }*/ } } } if(hasDropCell || (row!=null && !row.finished)) { //this.keepUnresolvedCell( row ); unresolvedRow = row; } return delta; } /*private int getLeftRowSpan(boolean finished, int rowSpan) { if(rowSpan<0) { return rowSpan; } else { if(finished) { return rowSpan - 1; } else { return rowSpan; } } }*/ public int resolveBottomBorder() { if(rows.size()==0) { return 0; } Row row = (Row)rows.getCurrent( ); HashSet cells = new HashSet(); int result = 0; for(int i=startCol; i<=endCol; i++) { CellArea cell = row.getCell( i ); if(cell!=null) { if(cell instanceof DummyCell) { CellArea ref = ((DummyCell)cell).getCell( ); if(!cells.contains( ref )) { int width = resolveBottomBorder( ref, row.finished ); if ( width > result ) result = width; cells.add( ref ); } } else { if(!cells.contains( cell )) { int width = resolveBottomBorder( cell, row.finished ); if ( width > result ) result = width; cells.add( cell ); } } } } //update cell height if(result>0) { if(cells.size( )>0) { Iterator iter = cells.iterator( ); while (iter.hasNext( )) { CellArea cell = (CellArea)iter.next( ); cell.setHeight( cell.getHeight( ) + result ); } row.getArea( ).setHeight( row.getArea( ).getHeight( ) + result ); } } return result; } public void addRow(RowArea rowArea, boolean finished, boolean repeated) { if(!repeated) { firstRow = false; } /* * 1. create row wrapper, and add it to rows */ hasDropCell = !finished; Row lastRow = (Row)rows.getCurrent( ); Row row = new Row(rowArea, startCol, endCol, finished, repeated ); int rowHeight = rowArea.getHeight( ); HashSet dropCells = new HashSet(); for(int i=startCol; i<=endCol; i++) { CellArea lastCell = null; if(lastRow!=null) { lastCell = lastRow.getCell( i ); } CellArea cell = row.getCell( i ); if(cell!=null && (cell.getRowSpan( )>1 || isDropCell( cell ))) { hasDropCell = true; } if(lastCell!=null &&(lastCell.getRowSpan( )>1 || isDropCell( lastCell ))) { if(cell==null) { DummyCell dummyCell = null; if(lastCell instanceof DummyCell) { DummyCell refDummy = ((DummyCell)lastCell); dummyCell = new DummyCell(refDummy.getCell( )); if(lastCell.getRowSpan()>0) { dummyCell.setRowSpan( lastCell.getRowSpan( )-1 ); } else { dummyCell.setRowSpan( lastCell.getRowSpan( ) ); } dummyCell.setHeight( refDummy.getHeight( ) - rowHeight ); } else { dummyCell = new DummyCell(lastCell); if(lastCell.getRowSpan()>0) { dummyCell.setRowSpan( lastCell.getRowSpan( )-1 ); } else { dummyCell.setRowSpan( lastCell.getRowSpan( ) ); } dummyCell.setHeight( lastCell.getHeight( ) - lastRow.getArea( ).getHeight( ) - rowHeight); } row.addArea( dummyCell ); //update drop cell height and vertial alignment if(dummyCell.getRowSpan( )==1) { if(dummyCell.getHeight( )<0) { CellArea cArea = dummyCell.getCell( ); if(!dropCells.contains( cArea )) { cArea.setHeight( cArea.getHeight( ) - dummyCell.getHeight( ) ); verticalAlign( cArea ); dropCells.add( cArea ); } } } else { hasDropCell = true; } i = i + dummyCell.getColSpan( ) -1; } } } rows.add( row ); } public void skipRow(RowArea area) { } protected boolean existDropCells() { if(unresolvedRow!=null) { for(int i=startCol; i<=endCol; i++) { CellArea cell = unresolvedRow.getCell( i ); if(cell!=null && (isDropCell( cell ) || cell.getRowSpan()>1)) { return true; } } } return false; } public void updateRow(RowArea rowArea, int specifiedHeight, boolean finished) { /* * 1. resolve drop conflict, formailize current row. * 2. resolve row height * */ hasDropCell = !finished; Row lastRow = getPreviousRow(); if(lastRow==null && existDropCells() &&(!LayoutUtil.isRepeatableRow( (IRowContent)rowArea.getContent( )))) { lastRow = unresolvedRow; } Row row = new Row(rowArea, startCol, endCol, finished ); int height = specifiedHeight; //ArrayList dropCells = new ArrayList(); for(int i=startCol; i<=endCol; i++) { CellArea lastCell = null; if(lastRow!=null) { lastCell = lastRow.getCell( i ); } CellArea cell = row.getCell( i ); - if(lastCell!=null - &&(lastCell.getRowSpan( )>1 || isDropCell( lastCell ))) + if ( lastCell != null + && ( ( lastCell.getRowSpan( ) > 1 ) || isDropCell( lastCell ) ) ) { //should remove conflict area. - if(cell!=null) + if(cell!=null && ( lastCell instanceof DummyCell )) { row.remove( i ); } if(lastCell.getRowSpan( )==2) { if(lastCell instanceof DummyCell) { height = Math.max( height, lastCell.getHeight( ) ); } else { height = Math.max( height, lastCell.getHeight( ) - lastRow.getArea( ).getHeight( ) ); } } i = i + lastCell.getColSpan( ) -1; } else { if(cell!=null) { // if( cell.getChildrenCount() == 0 ) // { // height = Math.max( height, 0 ); // } // else if( cell.getRowSpan( )==1 ) { height = Math.max( height, cell.getHeight( ) ); } } if(cell==null) { ICellContent cellContent = null; if(unresolvedRow!=null) { CellArea ca= unresolvedRow.getCell( i ); if(ca!=null) { ICellContent cc = (ICellContent)ca.getContent( ); cellContent = new ClonedCellContent(cc, getRowSpan( (IRowContent) rowArea.getContent(), ca, unresolvedRow.row)); } } if(cellContent==null) { //create a empty cell cellContent = tableContent.getReportContent( ) .createCellContent( ); cellContent.setColumn( i ); cellContent.setColSpan( 1 ); cellContent.setRowSpan( 1 ); cellContent.setParent( rowArea.getContent( ) ); } int startColumn = cellContent.getColumn( ); int endColumn = cellContent.getColSpan( ) + startColumn; CellArea emptyCell = AreaFactory .createCellArea( cellContent ); resolveBorderConflict( emptyCell, false ); IStyle areaStyle = emptyCell.getStyle( ); /*areaStyle.setProperty( IStyle.STYLE_BORDER_TOP_WIDTH, IStyle.NUMBER_0 );*/ areaStyle.setProperty( IStyle.STYLE_PADDING_TOP, IStyle.NUMBER_0 ); areaStyle.setProperty( IStyle.STYLE_MARGIN_TOP, IStyle.NUMBER_0 ); emptyCell.setWidth( getCellWidth( startColumn, endColumn ) ); emptyCell.setPosition( layoutInfo.getXPosition( i ), 0 ); rowArea.addChild( emptyCell ); i = i + emptyCell.getColSpan( ) -1; } } } if ( specifiedHeight == 0 && isEmptyRow( row ) ) { height = Math.max( height, getHeightOfEmptyRow( row )); } //update row height if(height >= 0) { Iterator iter = rowArea.getChildren( ); while(iter.hasNext( )) { CellArea cell = (CellArea)iter.next( ); if(cell.getRowSpan( )==1) { cell.setHeight( height ); verticalAlign( cell ); } } rowArea.setHeight( height ); } if(firstRow && existDropCells()&&(!LayoutUtil.isRepeatableRow( (IRowContent)rowArea.getContent( )))) { mergeDropCell(rowArea); } } private int getHeightOfEmptyRow( Row row ) { int heightOfEmptyRow = 0; for(int i=startCol; i<=endCol; i++) { CellArea cell = row.getCell( i ); if ( cell == null ) continue; IStyle style = cell.getStyle( ); int bottomBorderWidth = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_BORDER_BOTTOM_WIDTH ) ); int topBorderWidth = PropertyUtil.getDimensionValue( style .getProperty( StyleConstants.STYLE_BORDER_TOP_WIDTH ) ); int heightOfEmptyCell = topBorderWidth + bottomBorderWidth; heightOfEmptyRow = Math.max( heightOfEmptyCell, heightOfEmptyRow ); } return heightOfEmptyRow; } private boolean isEmptyRow( Row row ) { for(int i=startCol; i<=endCol; i++) { CellArea cell = row.getCell( i ); // if ( isDropCell (cell) ) // { // return false; // } if ( cell != null && !isDropCell( cell ) && cell.getChildrenCount( ) > 0 ) { return false; } } return true; } private boolean isDropCell( CellArea cell ) { return cell != null && cell.getRowSpan( ) < 0; } protected void mergeDropCell(RowArea row) { if(unresolvedRow==null ) { return; } CellArea[] cells = new CellArea[endCol-startCol+1]; Iterator iter = row.getChildren( ); while(iter.hasNext( )) { CellArea cell = (CellArea)iter.next( ); int colId = cell.getColumnID( ); if(colId>=startCol && colId<=endCol) { cells[colId-startCol] = cell; } } for(int i=startCol; i<=endCol; i++) { if(cells[i-startCol]==null) { ICellContent cellContent = null; CellArea ca= unresolvedRow.getCell( i ); if(ca!=null) { ICellContent cc = (ICellContent)ca.getContent( ); cellContent = new ClonedCellContent(cc, getRowSpan( (IRowContent) row.getContent(), ca, unresolvedRow.row)); //FIXME resolve column span conflict //FIXME resolve content hierarchy int startColumn = cellContent.getColumn( ); int endColumn = cellContent.getColSpan( ) + startColumn; CellArea emptyCell = AreaFactory .createCellArea( cellContent ); emptyCell.setRowSpan( cellContent.getRowSpan( ) ); resolveBorderConflict( emptyCell, true ); emptyCell.setWidth( getCellWidth( startColumn, endColumn ) ); emptyCell.setPosition( layoutInfo.getXPosition( i ), 0 ); emptyCell.setHeight( row.getHeight( ) ); row.addChild( emptyCell ); } } } } protected int getRowSpan(IRowContent row, CellArea cell, RowArea rowArea) { int rowSpan = cell.getRowSpan(); IContent rowContent = rowArea.getContent(); InstanceID id = row.getInstanceID( ); InstanceID contentId = rowContent.getInstanceID( ); if(id!=null && contentId!=null) { if ( rowSpan > 1 && ( !id.toUniqueString( ).equals( contentId.toUniqueString( ) ) ) ) { return rowSpan - 1; } return rowSpan; } else //FIX 203576 { if(row!=rowContent && rowSpan > 1) { return rowSpan-1; } else { return rowSpan; } } } protected CellArea getReference() { return null; } public int getCellWidth( int startColumn, int endColumn ) { if ( layoutInfo != null ) { return layoutInfo.getCellWidth( startColumn, endColumn ); } return 0; } private static class UnresolvedRow { IContent rowContent; public UnresolvedRow(IContent row) { rowContent = row; } protected HashMap map = new HashMap(); public void addUnresolvedCell(ICellContent cell, int rowSpan) { int start = cell.getColumn( ); int end = start + cell.getColSpan( ); for(int i=start; i<end; i++) { map.put( new Integer(start), new ClonedCellContent(cell, rowSpan) ); } } public boolean isEmpty() { return map.isEmpty( ); } public ICellContent getDropCellContent(int colId, IContent row) { ClonedCellContent dropCellContent = (ClonedCellContent)map.get( new Integer(colId) ); if(dropCellContent!=null) { if(row!=rowContent && dropCellContent.getRowSpan( )>0 ) { return new ClonedCellContent(dropCellContent.getCellContent( ), dropCellContent.rowSpan - 1); } return new ClonedCellContent(dropCellContent.getCellContent( ), dropCellContent.rowSpan); } return null; } } public Row getLastRow() { Row row = (Row)rows.getCurrent( ); return row; } protected Row getPreviousRow() { //FIXME use current cursor int size = rows.size( ); for(int i=size-1; i>=0; i--) { Row row = (Row)rows.get( i ); if(row!=null && !row.repeated) { return row; } } return null; } public static class Row { protected int start; protected int length; protected int end; protected RowArea row; protected CellArea[] cells; protected boolean finished = true; protected boolean repeated = false; Row(RowArea row, int start, int end, boolean finished) { this(row, start, end); this.finished = finished; } Row(RowArea row, int start, int end, boolean finished, boolean repeated) { this(row, start, end, finished); this.repeated = repeated; } Row(RowArea row, int start, int end) { this.row = row; this.start = start; this.end = end; this.length = end - start + 1; cells = new CellArea[length]; Iterator iter = row.getChildren( ); while(iter.hasNext( )) { CellArea cell = (CellArea)iter.next( ); int colId = cell.getColumnID( ); int colSpan = cell.getColSpan( ); if((colId>=start) && (colId+colSpan-1<=end)) { int loopEnd = Math.min(colSpan, end-colId+1); for(int j=0; j<loopEnd; j++) { cells[colId - start + j] = cell; } } } } public IContent getContent() { return row.getContent( ); } public void remove(int colId) { //FIXME row.removeChild( getCell(colId)); } public void remove(IArea area) { if(area!=null) { if(!(area instanceof DummyCell)) { row.removeChild( area ); } CellArea cell = (CellArea)area; int colId = cell.getColumnID( ); int colSpan = cell.getColSpan( ); if((colId>=start) && (colId+colSpan-1<=end)) { int loopEnd = Math.min(colSpan, end-colId+1); for(int j=0; j<loopEnd; j++) { cells[colId - start + j] = null; } } } } public CellArea getCell(int colId) { if(colId<start || colId>end) { assert(false); return null; } return cells[colId-start]; } public void addArea(IArea area) { if(!(area instanceof DummyCell)) { row.addChild( area ); } CellArea cell = (CellArea)area; int colId = cell.getColumnID( ); int colSpan = cell.getColSpan( ); if((colId>=start) && (colId+colSpan-1<=end)) { int loopEnd = Math.min(colSpan, end-colId+1); for(int j=0; j<loopEnd; j++) { cells[colId - start + j] = cell; } } } /** * row content */ public RowArea getArea() { return row; } } }
false
true
public void updateRow(RowArea rowArea, int specifiedHeight, boolean finished) { /* * 1. resolve drop conflict, formailize current row. * 2. resolve row height * */ hasDropCell = !finished; Row lastRow = getPreviousRow(); if(lastRow==null && existDropCells() &&(!LayoutUtil.isRepeatableRow( (IRowContent)rowArea.getContent( )))) { lastRow = unresolvedRow; } Row row = new Row(rowArea, startCol, endCol, finished ); int height = specifiedHeight; //ArrayList dropCells = new ArrayList(); for(int i=startCol; i<=endCol; i++) { CellArea lastCell = null; if(lastRow!=null) { lastCell = lastRow.getCell( i ); } CellArea cell = row.getCell( i ); if(lastCell!=null &&(lastCell.getRowSpan( )>1 || isDropCell( lastCell ))) { //should remove conflict area. if(cell!=null) { row.remove( i ); } if(lastCell.getRowSpan( )==2) { if(lastCell instanceof DummyCell) { height = Math.max( height, lastCell.getHeight( ) ); } else { height = Math.max( height, lastCell.getHeight( ) - lastRow.getArea( ).getHeight( ) ); } } i = i + lastCell.getColSpan( ) -1; } else { if(cell!=null) { // if( cell.getChildrenCount() == 0 ) // { // height = Math.max( height, 0 ); // } // else if( cell.getRowSpan( )==1 ) { height = Math.max( height, cell.getHeight( ) ); } } if(cell==null) { ICellContent cellContent = null; if(unresolvedRow!=null) { CellArea ca= unresolvedRow.getCell( i ); if(ca!=null) { ICellContent cc = (ICellContent)ca.getContent( ); cellContent = new ClonedCellContent(cc, getRowSpan( (IRowContent) rowArea.getContent(), ca, unresolvedRow.row)); } } if(cellContent==null) { //create a empty cell cellContent = tableContent.getReportContent( ) .createCellContent( ); cellContent.setColumn( i ); cellContent.setColSpan( 1 ); cellContent.setRowSpan( 1 ); cellContent.setParent( rowArea.getContent( ) ); } int startColumn = cellContent.getColumn( ); int endColumn = cellContent.getColSpan( ) + startColumn; CellArea emptyCell = AreaFactory .createCellArea( cellContent ); resolveBorderConflict( emptyCell, false ); IStyle areaStyle = emptyCell.getStyle( ); /*areaStyle.setProperty( IStyle.STYLE_BORDER_TOP_WIDTH, IStyle.NUMBER_0 );*/ areaStyle.setProperty( IStyle.STYLE_PADDING_TOP, IStyle.NUMBER_0 ); areaStyle.setProperty( IStyle.STYLE_MARGIN_TOP, IStyle.NUMBER_0 ); emptyCell.setWidth( getCellWidth( startColumn, endColumn ) ); emptyCell.setPosition( layoutInfo.getXPosition( i ), 0 ); rowArea.addChild( emptyCell ); i = i + emptyCell.getColSpan( ) -1; } } } if ( specifiedHeight == 0 && isEmptyRow( row ) ) { height = Math.max( height, getHeightOfEmptyRow( row )); } //update row height if(height >= 0) { Iterator iter = rowArea.getChildren( ); while(iter.hasNext( )) { CellArea cell = (CellArea)iter.next( ); if(cell.getRowSpan( )==1) { cell.setHeight( height ); verticalAlign( cell ); } } rowArea.setHeight( height ); } if(firstRow && existDropCells()&&(!LayoutUtil.isRepeatableRow( (IRowContent)rowArea.getContent( )))) { mergeDropCell(rowArea); } }
public void updateRow(RowArea rowArea, int specifiedHeight, boolean finished) { /* * 1. resolve drop conflict, formailize current row. * 2. resolve row height * */ hasDropCell = !finished; Row lastRow = getPreviousRow(); if(lastRow==null && existDropCells() &&(!LayoutUtil.isRepeatableRow( (IRowContent)rowArea.getContent( )))) { lastRow = unresolvedRow; } Row row = new Row(rowArea, startCol, endCol, finished ); int height = specifiedHeight; //ArrayList dropCells = new ArrayList(); for(int i=startCol; i<=endCol; i++) { CellArea lastCell = null; if(lastRow!=null) { lastCell = lastRow.getCell( i ); } CellArea cell = row.getCell( i ); if ( lastCell != null && ( ( lastCell.getRowSpan( ) > 1 ) || isDropCell( lastCell ) ) ) { //should remove conflict area. if(cell!=null && ( lastCell instanceof DummyCell )) { row.remove( i ); } if(lastCell.getRowSpan( )==2) { if(lastCell instanceof DummyCell) { height = Math.max( height, lastCell.getHeight( ) ); } else { height = Math.max( height, lastCell.getHeight( ) - lastRow.getArea( ).getHeight( ) ); } } i = i + lastCell.getColSpan( ) -1; } else { if(cell!=null) { // if( cell.getChildrenCount() == 0 ) // { // height = Math.max( height, 0 ); // } // else if( cell.getRowSpan( )==1 ) { height = Math.max( height, cell.getHeight( ) ); } } if(cell==null) { ICellContent cellContent = null; if(unresolvedRow!=null) { CellArea ca= unresolvedRow.getCell( i ); if(ca!=null) { ICellContent cc = (ICellContent)ca.getContent( ); cellContent = new ClonedCellContent(cc, getRowSpan( (IRowContent) rowArea.getContent(), ca, unresolvedRow.row)); } } if(cellContent==null) { //create a empty cell cellContent = tableContent.getReportContent( ) .createCellContent( ); cellContent.setColumn( i ); cellContent.setColSpan( 1 ); cellContent.setRowSpan( 1 ); cellContent.setParent( rowArea.getContent( ) ); } int startColumn = cellContent.getColumn( ); int endColumn = cellContent.getColSpan( ) + startColumn; CellArea emptyCell = AreaFactory .createCellArea( cellContent ); resolveBorderConflict( emptyCell, false ); IStyle areaStyle = emptyCell.getStyle( ); /*areaStyle.setProperty( IStyle.STYLE_BORDER_TOP_WIDTH, IStyle.NUMBER_0 );*/ areaStyle.setProperty( IStyle.STYLE_PADDING_TOP, IStyle.NUMBER_0 ); areaStyle.setProperty( IStyle.STYLE_MARGIN_TOP, IStyle.NUMBER_0 ); emptyCell.setWidth( getCellWidth( startColumn, endColumn ) ); emptyCell.setPosition( layoutInfo.getXPosition( i ), 0 ); rowArea.addChild( emptyCell ); i = i + emptyCell.getColSpan( ) -1; } } } if ( specifiedHeight == 0 && isEmptyRow( row ) ) { height = Math.max( height, getHeightOfEmptyRow( row )); } //update row height if(height >= 0) { Iterator iter = rowArea.getChildren( ); while(iter.hasNext( )) { CellArea cell = (CellArea)iter.next( ); if(cell.getRowSpan( )==1) { cell.setHeight( height ); verticalAlign( cell ); } } rowArea.setHeight( height ); } if(firstRow && existDropCells()&&(!LayoutUtil.isRepeatableRow( (IRowContent)rowArea.getContent( )))) { mergeDropCell(rowArea); } }
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/misc/GetFaviconForUrlTest.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/misc/GetFaviconForUrlTest.java index 9f6d4d2..ac2dbe2 100644 --- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/misc/GetFaviconForUrlTest.java +++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/misc/GetFaviconForUrlTest.java @@ -1,54 +1,56 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.tests.misc; import java.net.MalformedURLException; import junit.framework.TestCase; import org.eclipse.mylyn.internal.web.ui.WebUiUtil; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; /** * @author Leo Dos Santos */ public class GetFaviconForUrlTest extends TestCase { public void testMalformedUrl() { boolean exceptionThrown = false; try { WebUiUtil.getFaviconForUrl("www.eclipse.org"); } catch (MalformedURLException e) { exceptionThrown = true; } assertTrue(exceptionThrown); } public void testEclipseDotOrg() { Image img = null; try { img = WebUiUtil.getFaviconForUrl("http://www.eclipse.org").createImage(false); } catch (MalformedURLException e) { fail(); } assertNotNull(img); - ImageData data = img.getImageData(); - assertEquals(data.height, 16); - assertEquals(data.width, 16); - img.dispose(); + if (img != null) { + ImageData data = img.getImageData(); + assertEquals(data.height, 16); + assertEquals(data.width, 16); + img.dispose(); + } } public void testNoFavicon() throws MalformedURLException { assertNull(WebUiUtil.getFaviconForUrl("http://help.eclipse.org/help32/index.jsp")); } }
true
true
public void testEclipseDotOrg() { Image img = null; try { img = WebUiUtil.getFaviconForUrl("http://www.eclipse.org").createImage(false); } catch (MalformedURLException e) { fail(); } assertNotNull(img); ImageData data = img.getImageData(); assertEquals(data.height, 16); assertEquals(data.width, 16); img.dispose(); }
public void testEclipseDotOrg() { Image img = null; try { img = WebUiUtil.getFaviconForUrl("http://www.eclipse.org").createImage(false); } catch (MalformedURLException e) { fail(); } assertNotNull(img); if (img != null) { ImageData data = img.getImageData(); assertEquals(data.height, 16); assertEquals(data.width, 16); img.dispose(); } }
diff --git a/eclipse/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/internal/ui/texteditor/coverage/CoverageToggleAction.java b/eclipse/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/internal/ui/texteditor/coverage/CoverageToggleAction.java index e679d0f..61f1f3e 100644 --- a/eclipse/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/internal/ui/texteditor/coverage/CoverageToggleAction.java +++ b/eclipse/org.sonar.ide.eclipse/src/org/sonar/ide/eclipse/internal/ui/texteditor/coverage/CoverageToggleAction.java @@ -1,85 +1,86 @@ /* * Cxdopyright (C) 2010 Evgeny Mandrikov, Jérémie Lagarde * * Sonar-IDE is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar-IDE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar-IDE; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.ide.eclipse.internal.ui.texteditor.coverage; import org.eclipse.jface.action.IAction; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.ISelection; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.IUpdate; /** * Action to toggle the coverage bar's and color information in the editor. When * turned on, sonar ide plugin shows the coverage informations form sonar server * in the editor . * * @author Jérémie Lagarde * @since 0.2.0 */ public class CoverageToggleAction implements IEditorActionDelegate, IUpdate { /** The editor we are working on. */ ITextEditor editor = null; IAction action = null; public void setActiveEditor(IAction action, IEditorPart targetEditor) { if (targetEditor instanceof ITextEditor) { editor = (ITextEditor) targetEditor; this.action = action; + update(); } else { editor = null; } } public void run(IAction action) { if (editor == null) { return; } toggleCoverageRuler(); } public void selectionChanged(IAction action, ISelection selection) { } public void update() { if (action != null) { action.setChecked(isCoverageRulerVisible()); } } /** * Toggles the coverage global preference and shows the sonar coverage ruler * accordingly. */ private void toggleCoverageRuler() { IPreferenceStore store = EditorsUI.getPreferenceStore(); store.setValue(CoverageColumn.SONAR_COVERAGE_RULER, !isCoverageRulerVisible()); } /** * Returns whether the sonar coverage ruler column should be visible according * to the preference store settings. */ private boolean isCoverageRulerVisible() { IPreferenceStore store = EditorsUI.getPreferenceStore(); return store != null ? store.getBoolean(CoverageColumn.SONAR_COVERAGE_RULER) : false; } }
true
true
public void setActiveEditor(IAction action, IEditorPart targetEditor) { if (targetEditor instanceof ITextEditor) { editor = (ITextEditor) targetEditor; this.action = action; } else { editor = null; } }
public void setActiveEditor(IAction action, IEditorPart targetEditor) { if (targetEditor instanceof ITextEditor) { editor = (ITextEditor) targetEditor; this.action = action; update(); } else { editor = null; } }
diff --git a/atlas-web/src/main/java/ae3/dao/NetCDFReader.java b/atlas-web/src/main/java/ae3/dao/NetCDFReader.java index 14518be86..67e1cb793 100644 --- a/atlas-web/src/main/java/ae3/dao/NetCDFReader.java +++ b/atlas-web/src/main/java/ae3/dao/NetCDFReader.java @@ -1,231 +1,232 @@ package ae3.dao; import ae3.model.*; import ae3.service.structuredquery.EfvTree; import ae3.util.AtlasProperties; import ucar.ma2.ArrayChar; import ucar.ma2.IndexIterator; import ucar.ma2.InvalidRangeException; import ucar.nc2.NetcdfFile; import ucar.nc2.Variable; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * NetCDF file reader * @author pashky */ public class NetCDFReader { /** * Default NetCDF path */ final static String DEFAULT_LOCATION = AtlasProperties.getProperty("atlas.netCDFlocation"); /** * Load experimental data using default path * @param experimentId experiment id * @return either constructed object or null, if no data files was found for this id * @throws IOException if i/o error occurs */ public static ExperimentalData loadExperiment(final long experimentId) throws IOException { return loadExperiment(DEFAULT_LOCATION, experimentId); } /** * Load experimental data using default path * @param netCdfLocation * @param experimentId experiment id * @return either constructed object or null, if no data files was found for this id * @throws IOException if i/o error occurs */ public static ExperimentalData loadExperiment(String netCdfLocation, final long experimentId) throws IOException { ExperimentalData experiment = null; for(File file : new File(netCdfLocation).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.matches("^" + experimentId + "_[0-9]+(_ratios)?\\.nc$"); } })) { if(experiment == null) experiment = new ExperimentalData(); loadArrayDesign(file.getAbsolutePath(), experiment); } return experiment; } /** * Load one array design from file * @param filename file name to load from * @param experiment experimental data object, to add data to * @throws IOException if i/o error occurs */ private static void loadArrayDesign(String filename, ExperimentalData experiment) throws IOException { final NetcdfFile ncfile = NetcdfFile.open(filename); final Variable varBDC = ncfile.findVariable("BDC"); final Variable varGN = ncfile.findVariable("GN"); final Variable varEFV = ncfile.findVariable("EFV"); final Variable varEF = ncfile.findVariable("EF"); final Variable varSC = ncfile.findVariable("SC"); final Variable varSCV = ncfile.findVariable("SCV"); final Variable varBS2AS = ncfile.findVariable("BS2AS"); final Variable varBS = ncfile.findVariable("BS"); final String arrayDesignAccession = ncfile.findGlobalAttributeIgnoreCase("ADaccession").getStringValue(); final ArrayDesign arrayDesign = new ArrayDesign(arrayDesignAccession); final int numSamples = varBS.getDimension(0).getLength(); final int numAssays = varEFV.getDimension(1).getLength(); final Map<String,List<String>> efvs = new HashMap<String,List<String>>(); final ArrayChar efData = (ArrayChar) varEF.read(); ArrayChar.StringIterator efvi = ((ArrayChar)varEFV.read()).getStringIterator(); for(ArrayChar.StringIterator i = efData.getStringIterator(); i.hasNext(); ) { String efStr = i.next(); String ef = efStr.startsWith("ba_") ? efStr.substring("ba_".length()) : efStr; List<String> efvList = new ArrayList<String>(numAssays); efvs.put(ef, efvList); for(int j = 0; j < numAssays; ++j) { efvi.hasNext(); efvList.add(efvi.next()); } } final Map<String,List<String>> scvs = new HashMap<String,List<String>>(); if(varSCV != null && varSC != null) { ArrayChar.StringIterator scvi = ((ArrayChar)varSCV.read()).getStringIterator(); for(ArrayChar.StringIterator i = ((ArrayChar)varSC.read()).getStringIterator(); i.hasNext(); ) { - String sc = i.next().substring("bs_".length()); + String scStr = i.next(); + String sc = scStr.startsWith("bs_") ? i.next().substring("bs_".length()) : scStr; List<String> scvList = new ArrayList<String>(numSamples); scvs.put(sc, scvList); for(int j = 0; j < numSamples; ++j) { scvi.hasNext(); scvList.add(scvi.next()); } } } Sample[] samples = new Sample[numSamples]; int[] sampleIds = (int[])varBS.read().get1DJavaArray(Integer.class); for(int i = 0; i < numSamples; ++i) { Map<String,String> scvMap = new HashMap<String,String>(); for(String sc : scvs.keySet()) scvMap.put(sc, scvs.get(sc).get(i)); samples[i] = experiment.addSample(scvMap, sampleIds[i]); } Assay[] assays = new Assay[numAssays]; for(int i = 0; i < numAssays; ++i) { Map<String,String> efvMap = new HashMap<String,String>(); for(String ef : efvs.keySet()) efvMap.put(ef, efvs.get(ef).get(i)); assays[i] = experiment.addAssay(arrayDesign, efvMap, i); } /* * Lazy loading of data, matrix is read only for required elements */ experiment.setExpressionMatrix(arrayDesign, new ExpressionMatrix() { int lastDesignElement = -1; double [] lastData = null; public double getExpression(int designElementId, int assayId) { if(lastData != null && designElementId == lastDesignElement) return lastData[assayId]; int[] shapeBDC = varBDC.getShape(); int[] originBDC = new int[varBDC.getRank()]; originBDC[0] = designElementId; shapeBDC[0] = 1; try { lastData = (double[])varBDC.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class); } catch(IOException e) { throw new RuntimeException("Exception during matrix load", e); } catch (InvalidRangeException e) { throw new RuntimeException("Exception during matrix load", e); } lastDesignElement = designElementId; return lastData[assayId]; } }); final Variable varUEFV = ncfile.findVariable("uEFV"); final Variable varUEFVNUM = ncfile.findVariable("uEFVnum"); final Variable varPVAL = ncfile.findVariable("PVAL"); final Variable varTSTAT = ncfile.findVariable("TSTAT"); /* * Lazy loading of data, matrix is read only for required elements */ if(varUEFV != null && varUEFVNUM != null && varPVAL != null && varTSTAT != null) experiment.setExpressionStats(arrayDesign, new ExpressionStats() { private final EfvTree<Integer> efvTree = new EfvTree<Integer>(); private EfvTree<Stat> lastData; int lastDesignElement = -1; { int k = 0; ArrayChar.StringIterator efvi = ((ArrayChar)varUEFV.read()).getStringIterator(); IndexIterator efvNumi = varUEFVNUM.read().getIndexIteratorFast(); for(ArrayChar.StringIterator efi = efData.getStringIterator(); efi.hasNext() && efvNumi.hasNext(); ) { String efStr = efi.next(); String ef = efStr.startsWith("ba_") ? efStr.substring("ba_".length()) : efStr; int efvNum = efvNumi.getIntNext(); for(; efvNum > 0 && efvi.hasNext(); --efvNum) { String efv = efvi.next(); efvTree.put(ef, efv, k++); } } } public EfvTree<Stat> getExpressionStats(int designElementId) { if(lastData != null && designElementId == lastDesignElement) return lastData; try { int[] shapeBDC = varPVAL.getShape(); int[] originBDC = new int[varPVAL.getRank()]; originBDC[0] = designElementId; shapeBDC[0] = 1; double[] pvals = (double[])varPVAL.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class); double[] tstats = (double[])varTSTAT.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class); EfvTree<Stat> result = new EfvTree<Stat>(); for(EfvTree.EfEfv<Integer> efefv : efvTree.getNameSortedList()) { double pvalue = pvals[efefv.getPayload()]; double tstat = tstats[efefv.getPayload()]; if(tstat > 1e-8 || tstat < -1e-8) result.put(efefv.getEf(), efefv.getEfv(), new Stat(tstat, pvalue)); } lastDesignElement = designElementId; lastData = result; return result; } catch(IOException e) { throw new RuntimeException("Exception during pvalue/tstat load", e); } catch (InvalidRangeException e) { throw new RuntimeException("Exception during pvalue/tstat load", e); } } }); IndexIterator mappingI = varBS2AS.read().getIndexIteratorFast(); for(int sampleI = 0; sampleI < numSamples; ++sampleI) for(int assayI = 0; assayI < numAssays; ++assayI) if(mappingI.hasNext() && mappingI.getIntNext() > 0) experiment.addSampleAssayMapping(samples[sampleI], assays[assayI]); final int[] geneIds = (int[])varGN.read().get1DJavaArray(int.class); experiment.setGeneIds(arrayDesign, geneIds); } }
true
true
private static void loadArrayDesign(String filename, ExperimentalData experiment) throws IOException { final NetcdfFile ncfile = NetcdfFile.open(filename); final Variable varBDC = ncfile.findVariable("BDC"); final Variable varGN = ncfile.findVariable("GN"); final Variable varEFV = ncfile.findVariable("EFV"); final Variable varEF = ncfile.findVariable("EF"); final Variable varSC = ncfile.findVariable("SC"); final Variable varSCV = ncfile.findVariable("SCV"); final Variable varBS2AS = ncfile.findVariable("BS2AS"); final Variable varBS = ncfile.findVariable("BS"); final String arrayDesignAccession = ncfile.findGlobalAttributeIgnoreCase("ADaccession").getStringValue(); final ArrayDesign arrayDesign = new ArrayDesign(arrayDesignAccession); final int numSamples = varBS.getDimension(0).getLength(); final int numAssays = varEFV.getDimension(1).getLength(); final Map<String,List<String>> efvs = new HashMap<String,List<String>>(); final ArrayChar efData = (ArrayChar) varEF.read(); ArrayChar.StringIterator efvi = ((ArrayChar)varEFV.read()).getStringIterator(); for(ArrayChar.StringIterator i = efData.getStringIterator(); i.hasNext(); ) { String efStr = i.next(); String ef = efStr.startsWith("ba_") ? efStr.substring("ba_".length()) : efStr; List<String> efvList = new ArrayList<String>(numAssays); efvs.put(ef, efvList); for(int j = 0; j < numAssays; ++j) { efvi.hasNext(); efvList.add(efvi.next()); } } final Map<String,List<String>> scvs = new HashMap<String,List<String>>(); if(varSCV != null && varSC != null) { ArrayChar.StringIterator scvi = ((ArrayChar)varSCV.read()).getStringIterator(); for(ArrayChar.StringIterator i = ((ArrayChar)varSC.read()).getStringIterator(); i.hasNext(); ) { String sc = i.next().substring("bs_".length()); List<String> scvList = new ArrayList<String>(numSamples); scvs.put(sc, scvList); for(int j = 0; j < numSamples; ++j) { scvi.hasNext(); scvList.add(scvi.next()); } } } Sample[] samples = new Sample[numSamples]; int[] sampleIds = (int[])varBS.read().get1DJavaArray(Integer.class); for(int i = 0; i < numSamples; ++i) { Map<String,String> scvMap = new HashMap<String,String>(); for(String sc : scvs.keySet()) scvMap.put(sc, scvs.get(sc).get(i)); samples[i] = experiment.addSample(scvMap, sampleIds[i]); } Assay[] assays = new Assay[numAssays]; for(int i = 0; i < numAssays; ++i) { Map<String,String> efvMap = new HashMap<String,String>(); for(String ef : efvs.keySet()) efvMap.put(ef, efvs.get(ef).get(i)); assays[i] = experiment.addAssay(arrayDesign, efvMap, i); } /* * Lazy loading of data, matrix is read only for required elements */ experiment.setExpressionMatrix(arrayDesign, new ExpressionMatrix() { int lastDesignElement = -1; double [] lastData = null; public double getExpression(int designElementId, int assayId) { if(lastData != null && designElementId == lastDesignElement) return lastData[assayId]; int[] shapeBDC = varBDC.getShape(); int[] originBDC = new int[varBDC.getRank()]; originBDC[0] = designElementId; shapeBDC[0] = 1; try { lastData = (double[])varBDC.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class); } catch(IOException e) { throw new RuntimeException("Exception during matrix load", e); } catch (InvalidRangeException e) { throw new RuntimeException("Exception during matrix load", e); } lastDesignElement = designElementId; return lastData[assayId]; } }); final Variable varUEFV = ncfile.findVariable("uEFV"); final Variable varUEFVNUM = ncfile.findVariable("uEFVnum"); final Variable varPVAL = ncfile.findVariable("PVAL"); final Variable varTSTAT = ncfile.findVariable("TSTAT"); /* * Lazy loading of data, matrix is read only for required elements */ if(varUEFV != null && varUEFVNUM != null && varPVAL != null && varTSTAT != null) experiment.setExpressionStats(arrayDesign, new ExpressionStats() { private final EfvTree<Integer> efvTree = new EfvTree<Integer>(); private EfvTree<Stat> lastData; int lastDesignElement = -1; { int k = 0; ArrayChar.StringIterator efvi = ((ArrayChar)varUEFV.read()).getStringIterator(); IndexIterator efvNumi = varUEFVNUM.read().getIndexIteratorFast(); for(ArrayChar.StringIterator efi = efData.getStringIterator(); efi.hasNext() && efvNumi.hasNext(); ) { String efStr = efi.next(); String ef = efStr.startsWith("ba_") ? efStr.substring("ba_".length()) : efStr; int efvNum = efvNumi.getIntNext(); for(; efvNum > 0 && efvi.hasNext(); --efvNum) { String efv = efvi.next(); efvTree.put(ef, efv, k++); } } } public EfvTree<Stat> getExpressionStats(int designElementId) { if(lastData != null && designElementId == lastDesignElement) return lastData; try { int[] shapeBDC = varPVAL.getShape(); int[] originBDC = new int[varPVAL.getRank()]; originBDC[0] = designElementId; shapeBDC[0] = 1; double[] pvals = (double[])varPVAL.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class); double[] tstats = (double[])varTSTAT.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class); EfvTree<Stat> result = new EfvTree<Stat>(); for(EfvTree.EfEfv<Integer> efefv : efvTree.getNameSortedList()) { double pvalue = pvals[efefv.getPayload()]; double tstat = tstats[efefv.getPayload()]; if(tstat > 1e-8 || tstat < -1e-8) result.put(efefv.getEf(), efefv.getEfv(), new Stat(tstat, pvalue)); } lastDesignElement = designElementId; lastData = result; return result; } catch(IOException e) { throw new RuntimeException("Exception during pvalue/tstat load", e); } catch (InvalidRangeException e) { throw new RuntimeException("Exception during pvalue/tstat load", e); } } }); IndexIterator mappingI = varBS2AS.read().getIndexIteratorFast(); for(int sampleI = 0; sampleI < numSamples; ++sampleI) for(int assayI = 0; assayI < numAssays; ++assayI) if(mappingI.hasNext() && mappingI.getIntNext() > 0) experiment.addSampleAssayMapping(samples[sampleI], assays[assayI]); final int[] geneIds = (int[])varGN.read().get1DJavaArray(int.class); experiment.setGeneIds(arrayDesign, geneIds); }
private static void loadArrayDesign(String filename, ExperimentalData experiment) throws IOException { final NetcdfFile ncfile = NetcdfFile.open(filename); final Variable varBDC = ncfile.findVariable("BDC"); final Variable varGN = ncfile.findVariable("GN"); final Variable varEFV = ncfile.findVariable("EFV"); final Variable varEF = ncfile.findVariable("EF"); final Variable varSC = ncfile.findVariable("SC"); final Variable varSCV = ncfile.findVariable("SCV"); final Variable varBS2AS = ncfile.findVariable("BS2AS"); final Variable varBS = ncfile.findVariable("BS"); final String arrayDesignAccession = ncfile.findGlobalAttributeIgnoreCase("ADaccession").getStringValue(); final ArrayDesign arrayDesign = new ArrayDesign(arrayDesignAccession); final int numSamples = varBS.getDimension(0).getLength(); final int numAssays = varEFV.getDimension(1).getLength(); final Map<String,List<String>> efvs = new HashMap<String,List<String>>(); final ArrayChar efData = (ArrayChar) varEF.read(); ArrayChar.StringIterator efvi = ((ArrayChar)varEFV.read()).getStringIterator(); for(ArrayChar.StringIterator i = efData.getStringIterator(); i.hasNext(); ) { String efStr = i.next(); String ef = efStr.startsWith("ba_") ? efStr.substring("ba_".length()) : efStr; List<String> efvList = new ArrayList<String>(numAssays); efvs.put(ef, efvList); for(int j = 0; j < numAssays; ++j) { efvi.hasNext(); efvList.add(efvi.next()); } } final Map<String,List<String>> scvs = new HashMap<String,List<String>>(); if(varSCV != null && varSC != null) { ArrayChar.StringIterator scvi = ((ArrayChar)varSCV.read()).getStringIterator(); for(ArrayChar.StringIterator i = ((ArrayChar)varSC.read()).getStringIterator(); i.hasNext(); ) { String scStr = i.next(); String sc = scStr.startsWith("bs_") ? i.next().substring("bs_".length()) : scStr; List<String> scvList = new ArrayList<String>(numSamples); scvs.put(sc, scvList); for(int j = 0; j < numSamples; ++j) { scvi.hasNext(); scvList.add(scvi.next()); } } } Sample[] samples = new Sample[numSamples]; int[] sampleIds = (int[])varBS.read().get1DJavaArray(Integer.class); for(int i = 0; i < numSamples; ++i) { Map<String,String> scvMap = new HashMap<String,String>(); for(String sc : scvs.keySet()) scvMap.put(sc, scvs.get(sc).get(i)); samples[i] = experiment.addSample(scvMap, sampleIds[i]); } Assay[] assays = new Assay[numAssays]; for(int i = 0; i < numAssays; ++i) { Map<String,String> efvMap = new HashMap<String,String>(); for(String ef : efvs.keySet()) efvMap.put(ef, efvs.get(ef).get(i)); assays[i] = experiment.addAssay(arrayDesign, efvMap, i); } /* * Lazy loading of data, matrix is read only for required elements */ experiment.setExpressionMatrix(arrayDesign, new ExpressionMatrix() { int lastDesignElement = -1; double [] lastData = null; public double getExpression(int designElementId, int assayId) { if(lastData != null && designElementId == lastDesignElement) return lastData[assayId]; int[] shapeBDC = varBDC.getShape(); int[] originBDC = new int[varBDC.getRank()]; originBDC[0] = designElementId; shapeBDC[0] = 1; try { lastData = (double[])varBDC.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class); } catch(IOException e) { throw new RuntimeException("Exception during matrix load", e); } catch (InvalidRangeException e) { throw new RuntimeException("Exception during matrix load", e); } lastDesignElement = designElementId; return lastData[assayId]; } }); final Variable varUEFV = ncfile.findVariable("uEFV"); final Variable varUEFVNUM = ncfile.findVariable("uEFVnum"); final Variable varPVAL = ncfile.findVariable("PVAL"); final Variable varTSTAT = ncfile.findVariable("TSTAT"); /* * Lazy loading of data, matrix is read only for required elements */ if(varUEFV != null && varUEFVNUM != null && varPVAL != null && varTSTAT != null) experiment.setExpressionStats(arrayDesign, new ExpressionStats() { private final EfvTree<Integer> efvTree = new EfvTree<Integer>(); private EfvTree<Stat> lastData; int lastDesignElement = -1; { int k = 0; ArrayChar.StringIterator efvi = ((ArrayChar)varUEFV.read()).getStringIterator(); IndexIterator efvNumi = varUEFVNUM.read().getIndexIteratorFast(); for(ArrayChar.StringIterator efi = efData.getStringIterator(); efi.hasNext() && efvNumi.hasNext(); ) { String efStr = efi.next(); String ef = efStr.startsWith("ba_") ? efStr.substring("ba_".length()) : efStr; int efvNum = efvNumi.getIntNext(); for(; efvNum > 0 && efvi.hasNext(); --efvNum) { String efv = efvi.next(); efvTree.put(ef, efv, k++); } } } public EfvTree<Stat> getExpressionStats(int designElementId) { if(lastData != null && designElementId == lastDesignElement) return lastData; try { int[] shapeBDC = varPVAL.getShape(); int[] originBDC = new int[varPVAL.getRank()]; originBDC[0] = designElementId; shapeBDC[0] = 1; double[] pvals = (double[])varPVAL.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class); double[] tstats = (double[])varTSTAT.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class); EfvTree<Stat> result = new EfvTree<Stat>(); for(EfvTree.EfEfv<Integer> efefv : efvTree.getNameSortedList()) { double pvalue = pvals[efefv.getPayload()]; double tstat = tstats[efefv.getPayload()]; if(tstat > 1e-8 || tstat < -1e-8) result.put(efefv.getEf(), efefv.getEfv(), new Stat(tstat, pvalue)); } lastDesignElement = designElementId; lastData = result; return result; } catch(IOException e) { throw new RuntimeException("Exception during pvalue/tstat load", e); } catch (InvalidRangeException e) { throw new RuntimeException("Exception during pvalue/tstat load", e); } } }); IndexIterator mappingI = varBS2AS.read().getIndexIteratorFast(); for(int sampleI = 0; sampleI < numSamples; ++sampleI) for(int assayI = 0; assayI < numAssays; ++assayI) if(mappingI.hasNext() && mappingI.getIntNext() > 0) experiment.addSampleAssayMapping(samples[sampleI], assays[assayI]); final int[] geneIds = (int[])varGN.read().get1DJavaArray(int.class); experiment.setGeneIds(arrayDesign, geneIds); }
diff --git a/tests/frontend/org/voltdb/regressionsuites/RegressionSuiteUtil.java b/tests/frontend/org/voltdb/regressionsuites/RegressionSuiteUtil.java index 19b3b5e36..04757c5c6 100644 --- a/tests/frontend/org/voltdb/regressionsuites/RegressionSuiteUtil.java +++ b/tests/frontend/org/voltdb/regressionsuites/RegressionSuiteUtil.java @@ -1,189 +1,189 @@ package org.voltdb.regressionsuites; import java.io.IOException; import java.util.Random; import junit.framework.TestCase; import org.voltdb.CatalogContext; import org.voltdb.SysProcSelector; import org.voltdb.VoltSystemProcedure; import org.voltdb.VoltTable; import org.voltdb.VoltType; import org.voltdb.benchmark.tpcc.TPCCConstants; import org.voltdb.benchmark.tpcc.TPCCLoader; import org.voltdb.benchmark.tpcc.TPCCSimulation; import org.voltdb.catalog.Column; import org.voltdb.catalog.Table; import org.voltdb.client.Client; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcCallException; import org.voltdb.sysprocs.LoadMultipartitionTable; import org.voltdb.sysprocs.SetConfiguration; import org.voltdb.sysprocs.Statistics; import org.voltdb.types.TimestampType; import org.voltdb.utils.VoltTypeUtil; import edu.brown.benchmark.tm1.TM1Loader; import edu.brown.catalog.CatalogUtil; import edu.brown.hstore.Hstoreservice.Status; import edu.brown.hstore.conf.HStoreConf; import edu.brown.rand.DefaultRandomGenerator; public abstract class RegressionSuiteUtil { static final double SCALEFACTOR = 0.0001; private static final DefaultRandomGenerator rng = new DefaultRandomGenerator(0); public static ClientResponse setHStoreConf(Client client, String paramName, Object paramValue) throws Exception { assert(HStoreConf.isConfParameter(paramName)) : "Invalid HStoreConf parameter '" + paramName + "'"; String procName = VoltSystemProcedure.procCallName(SetConfiguration.class); String confParams[] = {paramName}; String confValues[] = {paramValue.toString()}; ClientResponse cresponse = client.callProcedure(procName, confParams, confValues); assert(cresponse.getStatus() == Status.OK) : cresponse.toString(); return (cresponse); } public static ClientResponse getStats(Client client, SysProcSelector statsType) throws Exception { String procName = VoltSystemProcedure.procCallName(Statistics.class); Object params[] = { statsType.name(), 0 }; ClientResponse cresponse = client.callProcedure(procName, params); assert(cresponse.getStatus() == Status.OK) : cresponse.toString(); return (cresponse); } public static long getRowCount(Client client, String tableName) throws Exception { ClientResponse cresponse = getStats(client, SysProcSelector.TABLE); VoltTable result = cresponse.getResults()[0]; long count = 0; boolean found = false; while (result.advanceRow()) { if (tableName.equalsIgnoreCase(result.getString("TABLE_NAME"))) { found = true; count += result.getLong("TUPLE_COUNT"); } } // WHILE if (found == false) { throw new IllegalArgumentException("Invalid table '" + tableName + "'"); } return (count); } /** * Populate the given table with a bunch of random tuples * @param client * @param catalog_tbl * @param rand * @param num_tuples * @throws IOException * @throws ProcCallException */ public static void loadRandomData(Client client, Table catalog_tbl, Random rand, int num_tuples) throws IOException, ProcCallException { VoltTable vt = CatalogUtil.getVoltTable(catalog_tbl); int num_cols = catalog_tbl.getColumns().size(); VoltType types[] = new VoltType[num_cols]; int maxSizes[] = new int[num_cols]; for (Column catalog_col : catalog_tbl.getColumns()) { int idx = catalog_col.getIndex(); types[idx] = VoltType.get(catalog_col.getType()); if (types[idx] == VoltType.STRING) { maxSizes[idx] = catalog_col.getSize(); } } // FOR for (int i = 0; i < num_tuples; i++) { Object row[] = new Object[num_cols]; for (int col = 0; col < num_cols; col++) { row[col] = VoltTypeUtil.getRandomValue(types[col], rand); if (types[col] == VoltType.STRING) { if (row[col].toString().length() >= maxSizes[col]) { row[col] = row[col].toString().substring(0, maxSizes[col]-1); } } } // FOR (col) vt.addRow(row); } // FOR (row) // System.err.printf("Loading %d rows for %s\n%s\n\n", vt.getRowCount(), catalog_tbl, vt.toString()); String procName = VoltSystemProcedure.procCallName(LoadMultipartitionTable.class); ClientResponse cr = client.callProcedure(procName, catalog_tbl.getName(), vt); TestCase.assertEquals(Status.OK, cr.getStatus()); } public static final void initializeTPCCDatabase(final CatalogContext catalogContext, final Client client) throws Exception { String args[] = { "NOCONNECTIONS=true", "BENCHMARK.WAREHOUSE_PER_PARTITION=true", "BENCHMARK.NUM_LOADTHREADS=1", "BENCHMARK.SCALE_ITEMS=true", }; TPCCLoader loader = new TPCCLoader(args) { { this.setCatalogContext(catalogContext); this.setClientHandle(client); } @Override public CatalogContext getCatalogContext() { return (catalogContext); } }; loader.load(); } public static final void initializeTM1Database(final CatalogContext catalogContext, final Client client) throws Exception { String args[] = { "NOCONNECTIONS=true", }; TM1Loader loader = new TM1Loader(args) { { this.setCatalogContext(catalogContext); this.setClientHandle(client); } @Override public CatalogContext getCatalogContext() { return (catalogContext); } }; loader.load(); } protected static Object[] generateNewOrder(int num_warehouses, boolean dtxn, int w_id, int d_id) throws Exception { short supply_w_id; if (dtxn) { int start = TPCCConstants.STARTING_WAREHOUSE; int stop = TPCCConstants.STARTING_WAREHOUSE + num_warehouses; supply_w_id = TPCCSimulation.generatePairedWarehouse(w_id, start, stop); assert(supply_w_id != w_id); } else { supply_w_id = (short)w_id; } // ORDER_LINE ITEMS int num_items = rng.number(TPCCConstants.MIN_OL_CNT, TPCCConstants.MAX_OL_CNT); int item_ids[] = new int[num_items]; short supwares[] = new short[num_items]; int quantities[] = new int[num_items]; for (int i = 0; i < num_items; i++) { - item_ids[i] = rng.nextInt((int)(TPCCConstants.NUM_ITEMS)); + item_ids[i] = rng.nextInt(100); supwares[i] = (i == 1 && dtxn ? supply_w_id : (short)w_id); quantities[i] = 1; } // FOR Object params[] = { (short)w_id, // W_ID (byte)d_id, // D_ID 1, // C_ID new TimestampType(),// TIMESTAMP item_ids, // ITEM_IDS supwares, // SUPPLY W_IDS quantities // QUANTITIES }; return (params); } protected static Object[] generateNewOrder(int num_warehouses, boolean dtxn, short w_id) throws Exception { int d_id = rng.number(1, TPCCConstants.DISTRICTS_PER_WAREHOUSE); return generateNewOrder(num_warehouses, dtxn, w_id, d_id); } }
true
true
protected static Object[] generateNewOrder(int num_warehouses, boolean dtxn, int w_id, int d_id) throws Exception { short supply_w_id; if (dtxn) { int start = TPCCConstants.STARTING_WAREHOUSE; int stop = TPCCConstants.STARTING_WAREHOUSE + num_warehouses; supply_w_id = TPCCSimulation.generatePairedWarehouse(w_id, start, stop); assert(supply_w_id != w_id); } else { supply_w_id = (short)w_id; } // ORDER_LINE ITEMS int num_items = rng.number(TPCCConstants.MIN_OL_CNT, TPCCConstants.MAX_OL_CNT); int item_ids[] = new int[num_items]; short supwares[] = new short[num_items]; int quantities[] = new int[num_items]; for (int i = 0; i < num_items; i++) { item_ids[i] = rng.nextInt((int)(TPCCConstants.NUM_ITEMS)); supwares[i] = (i == 1 && dtxn ? supply_w_id : (short)w_id); quantities[i] = 1; } // FOR Object params[] = { (short)w_id, // W_ID (byte)d_id, // D_ID 1, // C_ID new TimestampType(),// TIMESTAMP item_ids, // ITEM_IDS supwares, // SUPPLY W_IDS quantities // QUANTITIES }; return (params); }
protected static Object[] generateNewOrder(int num_warehouses, boolean dtxn, int w_id, int d_id) throws Exception { short supply_w_id; if (dtxn) { int start = TPCCConstants.STARTING_WAREHOUSE; int stop = TPCCConstants.STARTING_WAREHOUSE + num_warehouses; supply_w_id = TPCCSimulation.generatePairedWarehouse(w_id, start, stop); assert(supply_w_id != w_id); } else { supply_w_id = (short)w_id; } // ORDER_LINE ITEMS int num_items = rng.number(TPCCConstants.MIN_OL_CNT, TPCCConstants.MAX_OL_CNT); int item_ids[] = new int[num_items]; short supwares[] = new short[num_items]; int quantities[] = new int[num_items]; for (int i = 0; i < num_items; i++) { item_ids[i] = rng.nextInt(100); supwares[i] = (i == 1 && dtxn ? supply_w_id : (short)w_id); quantities[i] = 1; } // FOR Object params[] = { (short)w_id, // W_ID (byte)d_id, // D_ID 1, // C_ID new TimestampType(),// TIMESTAMP item_ids, // ITEM_IDS supwares, // SUPPLY W_IDS quantities // QUANTITIES }; return (params); }
diff --git a/src/com/joulespersecond/seattlebusbot/MyStopListFragmentBase.java b/src/com/joulespersecond/seattlebusbot/MyStopListFragmentBase.java index 9bf05ff6..908b97cf 100644 --- a/src/com/joulespersecond/seattlebusbot/MyStopListFragmentBase.java +++ b/src/com/joulespersecond/seattlebusbot/MyStopListFragmentBase.java @@ -1,158 +1,159 @@ /* * Copyright (C) 2010-2012 Paul Watts ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.joulespersecond.seattlebusbot; import com.joulespersecond.oba.provider.ObaContract; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.v4.widget.SimpleCursorAdapter; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import android.widget.TextView; abstract class MyStopListFragmentBase extends MyListFragmentBase implements QueryUtils.StopList.Columns { //private static final String TAG = "MyStopListActivity"; @Override protected SimpleCursorAdapter newAdapter() { return QueryUtils.StopList.newAdapter(getActivity()); } @Override protected Uri getContentUri() { return ObaContract.Stops.CONTENT_URI; } @Override public void onListItemClick(ListView l, View v, int position, long id) { StopData stopData = getStopData(l, position); if (isShortcutMode()) { final Intent shortcut = UIHelp.makeShortcut(getActivity(), stopData.getUiName(), ArrivalsListActivity.makeIntent(getActivity(), stopData.getId(), stopData.getName(), stopData.getDir())); Activity activity = getActivity(); activity.setResult(Activity.RESULT_OK, shortcut); activity.finish(); } else { ArrivalsListActivity.start(getActivity(), stopData.id, stopData.name, stopData.dir); } } protected StopData getStopData(ListView l, int position) { // Get the cursor and fetch the stop ID from that. SimpleCursorAdapter cursorAdapter = (SimpleCursorAdapter)l.getAdapter(); return new StopData(cursorAdapter.getCursor(), position - l.getHeaderViewsCount()); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo)menuInfo; final TextView text = (TextView)info.targetView.findViewById(R.id.stop_name); menu.setHeaderTitle(text.getText()); if (isShortcutMode()) { menu.add(0, CONTEXT_MENU_DEFAULT, 0, R.string.my_context_create_shortcut); } else { menu.add(0, CONTEXT_MENU_DEFAULT, 0, R.string.my_context_get_stop_info); } menu.add(0, CONTEXT_MENU_SHOW_ON_MAP, 0, R.string.my_context_showonmap); if (!isShortcutMode()){ menu.add(0, CONTEXT_MENU_CREATE_SHORTCUT, 0, R.string.my_context_create_shortcut); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); switch (item.getItemId()) { case CONTEXT_MENU_DEFAULT: // Fake a click onListItemClick(getListView(), info.targetView, info.position, info.id); return true; case CONTEXT_MENU_SHOW_ON_MAP: showOnMap(getListView(), info.position); return true; case CONTEXT_MENU_CREATE_SHORTCUT: StopData stopData = getStopData(getListView(), info.position); final Intent shortcutIntent = UIHelp.makeShortcut(getActivity(), stopData.uiName, ArrivalsListActivity.makeIntent(getActivity(), stopData.id, stopData.name, stopData.dir)); shortcutIntent.setAction(MyListConstants.INSTALL_SHORTCUT); + shortcutIntent.setFlags(0); getActivity().sendBroadcast(shortcutIntent); return true; default: return super.onContextItemSelected(item); } } private void showOnMap(ListView l, int position) { // Get the cursor and fetch the stop ID from that. SimpleCursorAdapter cursorAdapter = (SimpleCursorAdapter)l.getAdapter(); Cursor c = cursorAdapter.getCursor(); c.moveToPosition(position - l.getHeaderViewsCount()); final String stopId = c.getString(COL_ID); final double lat = c.getDouble(COL_LATITUDE); final double lon = c.getDouble(COL_LONGITUDE); HomeActivity.start(getActivity(), stopId, lat, lon); } protected class StopData { private final String id; private final String name; private final String dir; private final String uiName; public StopData(Cursor c, int row){ c.moveToPosition(row); id = c.getString(COL_ID); name = c.getString(COL_NAME); dir = c.getString(COL_DIRECTION); uiName = c.getString(COL_UI_NAME); } public String getId() { return id; } public String getName() { return name; } public String getDir() { return dir; } public String getUiName() { return uiName; } } }
true
true
public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); switch (item.getItemId()) { case CONTEXT_MENU_DEFAULT: // Fake a click onListItemClick(getListView(), info.targetView, info.position, info.id); return true; case CONTEXT_MENU_SHOW_ON_MAP: showOnMap(getListView(), info.position); return true; case CONTEXT_MENU_CREATE_SHORTCUT: StopData stopData = getStopData(getListView(), info.position); final Intent shortcutIntent = UIHelp.makeShortcut(getActivity(), stopData.uiName, ArrivalsListActivity.makeIntent(getActivity(), stopData.id, stopData.name, stopData.dir)); shortcutIntent.setAction(MyListConstants.INSTALL_SHORTCUT); getActivity().sendBroadcast(shortcutIntent); return true; default: return super.onContextItemSelected(item); } }
public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); switch (item.getItemId()) { case CONTEXT_MENU_DEFAULT: // Fake a click onListItemClick(getListView(), info.targetView, info.position, info.id); return true; case CONTEXT_MENU_SHOW_ON_MAP: showOnMap(getListView(), info.position); return true; case CONTEXT_MENU_CREATE_SHORTCUT: StopData stopData = getStopData(getListView(), info.position); final Intent shortcutIntent = UIHelp.makeShortcut(getActivity(), stopData.uiName, ArrivalsListActivity.makeIntent(getActivity(), stopData.id, stopData.name, stopData.dir)); shortcutIntent.setAction(MyListConstants.INSTALL_SHORTCUT); shortcutIntent.setFlags(0); getActivity().sendBroadcast(shortcutIntent); return true; default: return super.onContextItemSelected(item); } }
diff --git a/dbproject/test/my/triviagame/xmcd/XmcdDiscTest.java b/dbproject/test/my/triviagame/xmcd/XmcdDiscTest.java index 23af6e8..166836d 100644 --- a/dbproject/test/my/triviagame/xmcd/XmcdDiscTest.java +++ b/dbproject/test/my/triviagame/xmcd/XmcdDiscTest.java @@ -1,117 +1,119 @@ package my.triviagame.xmcd; import junit.framework.Assert; import my.triviagame.dal.AlbumRow; import my.triviagame.dal.TrackRow; import org.junit.Test; /** * Tests {@link XmcdDisc}. */ public class XmcdDiscTest { /** * Tests that generating a disc from an empty xmcd file fails. */ @Test public void testConstructionFromEmptyFileFails() throws Throwable { try { XmcdDisc.fromXmcdFile("", FreedbGenre.BLUES); // Expecting an exception Assert.fail(); } catch (XmcdException e) { } } /** * Tests that generating a disc from a badly formatted xmcd file fails. */ @Test public void testConstructionFromBadFileFails() throws Throwable { try { XmcdDisc.fromXmcdFile("blah!\nSome more text\n\n\nmore blah!", FreedbGenre.CLASSICAL); // Expecting an exception Assert.fail(); } catch (XmcdException e) { } } /** * Tests that generating a disc from a sample good xmcd file works. */ @Test public void testConstructionFromSampleFile1() throws Throwable { String xmcd0a0d7d14 = TestUtilities.get_0a0d7d14(); XmcdDisc disc = XmcdDisc.fromXmcdFile(xmcd0a0d7d14, FreedbGenre.REGGAE); // Set expectations for the album part AlbumRow expectedAlbumRow = new AlbumRow(); expectedAlbumRow.freedbGenre = (byte)FreedbGenre.REGGAE.ordinal(); expectedAlbumRow.revision = 0; expectedAlbumRow.freedbId = 0x0a0d7d14; expectedAlbumRow.artistName = "Kinks, The"; expectedAlbumRow.title = "Face To Face: Deluxe Edition"; expectedAlbumRow.year = 1966; expectedAlbumRow.freeTextGenre = "Pop"; Assert.assertEquals(expectedAlbumRow, disc.albumRow); // Set expectations for some of the tracks TrackRow expectedTrackRow0 = new TrackRow(); expectedTrackRow0.trackNum = 0; expectedTrackRow0.title = "Party Line (Mono)"; expectedTrackRow0.artistName = "Kinks, The"; expectedTrackRow0.lenInSec = 2 * 60 + 38; + expectedTrackRow0.albumRow = expectedAlbumRow; Assert.assertEquals(expectedTrackRow0, disc.trackRows.get(0)); TrackRow expectedTrackRow19 = new TrackRow(); expectedTrackRow19.trackNum = 19; expectedTrackRow19.title = "Dead End Street (Alternative Version)"; expectedTrackRow19.artistName = "Kinks, The"; expectedTrackRow19.lenInSec = 2 * 60 + 56; + expectedTrackRow19.albumRow = expectedAlbumRow; Assert.assertEquals(expectedTrackRow19, disc.trackRows.get(19)); } /** * Tests another sample xmcd file. * This test doesn't bother verifying fields, it just checks that nothing blows up. */ @Test public void testConstructionFromSampleFile2() throws Throwable { String xmcda10be40d = TestUtilities.get_a10be40d(); XmcdDisc disc = XmcdDisc.fromXmcdFile(xmcda10be40d, FreedbGenre.NEWAGE); } /** * Tests another sample xmcd file. * This test doesn't bother verifying fields, it just checks that nothing blows up. */ @Test public void testConstructionFromSampleFile3() throws Throwable { String xmcd9209840d = TestUtilities.get_9209840d(); XmcdDisc disc = XmcdDisc.fromXmcdFile(xmcd9209840d, FreedbGenre.ROCK); } /** * Parse a fabricated xmcd file which tests some edge cases. */ @Test public void testParsingUnderStress() throws Throwable { String xmcdStress = TestUtilities.getStressFile(); XmcdDisc disc = XmcdDisc.fromXmcdFile(xmcdStress, FreedbGenre.ROCK); System.out.println(disc); // Tests handling of discs titled after the artist Assert.assertEquals("The Artist", disc.albumRow.artistName); Assert.assertEquals("The Artist", disc.albumRow.title); // Tests handling of missing year Assert.assertEquals(XmcdDisc.INVALID_YEAR, disc.albumRow.year); // Tests handling of missing genre (guessing from FreeDB genre) Assert.assertEquals("Rock", disc.albumRow.freeTextGenre); // Tests splitting of track title Assert.assertEquals("The Artist", disc.trackRows.get(9).artistName); Assert.assertEquals("Fancy Shmancy", disc.trackRows.get(9).title); Assert.assertEquals(9, disc.trackRows.get(9).trackNum); // Tests one track with a different artist Assert.assertEquals("The Guys", disc.trackRows.get(13).artistName); Assert.assertEquals("I'll Remember (Mono)", disc.trackRows.get(13).title); } }
false
true
public void testConstructionFromSampleFile1() throws Throwable { String xmcd0a0d7d14 = TestUtilities.get_0a0d7d14(); XmcdDisc disc = XmcdDisc.fromXmcdFile(xmcd0a0d7d14, FreedbGenre.REGGAE); // Set expectations for the album part AlbumRow expectedAlbumRow = new AlbumRow(); expectedAlbumRow.freedbGenre = (byte)FreedbGenre.REGGAE.ordinal(); expectedAlbumRow.revision = 0; expectedAlbumRow.freedbId = 0x0a0d7d14; expectedAlbumRow.artistName = "Kinks, The"; expectedAlbumRow.title = "Face To Face: Deluxe Edition"; expectedAlbumRow.year = 1966; expectedAlbumRow.freeTextGenre = "Pop"; Assert.assertEquals(expectedAlbumRow, disc.albumRow); // Set expectations for some of the tracks TrackRow expectedTrackRow0 = new TrackRow(); expectedTrackRow0.trackNum = 0; expectedTrackRow0.title = "Party Line (Mono)"; expectedTrackRow0.artistName = "Kinks, The"; expectedTrackRow0.lenInSec = 2 * 60 + 38; Assert.assertEquals(expectedTrackRow0, disc.trackRows.get(0)); TrackRow expectedTrackRow19 = new TrackRow(); expectedTrackRow19.trackNum = 19; expectedTrackRow19.title = "Dead End Street (Alternative Version)"; expectedTrackRow19.artistName = "Kinks, The"; expectedTrackRow19.lenInSec = 2 * 60 + 56; Assert.assertEquals(expectedTrackRow19, disc.trackRows.get(19)); }
public void testConstructionFromSampleFile1() throws Throwable { String xmcd0a0d7d14 = TestUtilities.get_0a0d7d14(); XmcdDisc disc = XmcdDisc.fromXmcdFile(xmcd0a0d7d14, FreedbGenre.REGGAE); // Set expectations for the album part AlbumRow expectedAlbumRow = new AlbumRow(); expectedAlbumRow.freedbGenre = (byte)FreedbGenre.REGGAE.ordinal(); expectedAlbumRow.revision = 0; expectedAlbumRow.freedbId = 0x0a0d7d14; expectedAlbumRow.artistName = "Kinks, The"; expectedAlbumRow.title = "Face To Face: Deluxe Edition"; expectedAlbumRow.year = 1966; expectedAlbumRow.freeTextGenre = "Pop"; Assert.assertEquals(expectedAlbumRow, disc.albumRow); // Set expectations for some of the tracks TrackRow expectedTrackRow0 = new TrackRow(); expectedTrackRow0.trackNum = 0; expectedTrackRow0.title = "Party Line (Mono)"; expectedTrackRow0.artistName = "Kinks, The"; expectedTrackRow0.lenInSec = 2 * 60 + 38; expectedTrackRow0.albumRow = expectedAlbumRow; Assert.assertEquals(expectedTrackRow0, disc.trackRows.get(0)); TrackRow expectedTrackRow19 = new TrackRow(); expectedTrackRow19.trackNum = 19; expectedTrackRow19.title = "Dead End Street (Alternative Version)"; expectedTrackRow19.artistName = "Kinks, The"; expectedTrackRow19.lenInSec = 2 * 60 + 56; expectedTrackRow19.albumRow = expectedAlbumRow; Assert.assertEquals(expectedTrackRow19, disc.trackRows.get(19)); }
diff --git a/src/com/android/gallery3d/app/AbstractGalleryActivity.java b/src/com/android/gallery3d/app/AbstractGalleryActivity.java index d25f60e..9500fff 100644 --- a/src/com/android/gallery3d/app/AbstractGalleryActivity.java +++ b/src/com/android/gallery3d/app/AbstractGalleryActivity.java @@ -1,206 +1,206 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gallery3d.app; import com.android.gallery3d.R; import com.android.gallery3d.data.DataManager; import com.android.gallery3d.data.ImageCacheService; import com.android.gallery3d.ui.GLRoot; import com.android.gallery3d.ui.GLRootView; import com.android.gallery3d.ui.PositionRepository; import com.android.gallery3d.util.ThreadPool; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Configuration; import android.os.Bundle; public class AbstractGalleryActivity extends Activity implements GalleryActivity { @SuppressWarnings("unused") private static final String TAG = "AbstractGalleryActivity"; private GLRootView mGLRootView; private StateManager mStateManager; private PositionRepository mPositionRepository = new PositionRepository(); private AlertDialog mAlertDialog = null; private BroadcastReceiver mMountReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (getExternalCacheDir() != null) onStorageReady(); } }; private IntentFilter mMountFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED); @Override protected void onSaveInstanceState(Bundle outState) { mGLRootView.lockRenderThread(); try { super.onSaveInstanceState(outState); getStateManager().saveState(outState); } finally { mGLRootView.unlockRenderThread(); } } @Override public void onConfigurationChanged(Configuration config) { super.onConfigurationChanged(config); mStateManager.onConfigurationChange(config); invalidateOptionsMenu(); } public Context getAndroidContext() { return this; } public ImageCacheService getImageCacheService() { return ((GalleryApp) getApplication()).getImageCacheService(); } public DataManager getDataManager() { return ((GalleryApp) getApplication()).getDataManager(); } public ThreadPool getThreadPool() { return ((GalleryApp) getApplication()).getThreadPool(); } public GalleryApp getGalleryApplication() { return (GalleryApp) getApplication(); } public synchronized StateManager getStateManager() { if (mStateManager == null) { mStateManager = new StateManager(this); } return mStateManager; } public GLRoot getGLRoot() { return mGLRootView; } public PositionRepository getPositionRepository() { return mPositionRepository; } @Override public void setContentView(int resId) { super.setContentView(resId); mGLRootView = (GLRootView) findViewById(R.id.gl_root_view); } public int getActionBarHeight() { ActionBar actionBar = getActionBar(); return actionBar != null ? actionBar.getHeight() : 0; } protected void onStorageReady() { if (mAlertDialog != null) { mAlertDialog.dismiss(); mAlertDialog = null; unregisterReceiver(mMountReceiver); } } @Override protected void onStart() { super.onStart(); if (getExternalCacheDir() == null) { OnCancelListener onCancel = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }; OnClickListener onClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }; mAlertDialog = new AlertDialog.Builder(this) - .setIcon(android.R.drawable.ic_dialog_alert) + .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("No Storage") .setMessage("No external storage available.") .setNegativeButton(android.R.string.cancel, onClick) .setOnCancelListener(onCancel) .show(); registerReceiver(mMountReceiver, mMountFilter); } } @Override protected void onStop() { super.onStop(); if (mAlertDialog != null) { unregisterReceiver(mMountReceiver); mAlertDialog.dismiss(); mAlertDialog = null; } } @Override protected void onResume() { super.onResume(); mGLRootView.lockRenderThread(); try { getStateManager().resume(); getDataManager().resume(); } finally { mGLRootView.unlockRenderThread(); } mGLRootView.onResume(); } @Override protected void onPause() { super.onPause(); mGLRootView.onPause(); mGLRootView.lockRenderThread(); try { getStateManager().pause(); getDataManager().pause(); } finally { mGLRootView.unlockRenderThread(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { mGLRootView.lockRenderThread(); try { getStateManager().notifyActivityResult( requestCode, resultCode, data); } finally { mGLRootView.unlockRenderThread(); } } @Override public GalleryActionBar getGalleryActionBar() { return null; } }
true
true
protected void onStart() { super.onStart(); if (getExternalCacheDir() == null) { OnCancelListener onCancel = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }; OnClickListener onClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }; mAlertDialog = new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("No Storage") .setMessage("No external storage available.") .setNegativeButton(android.R.string.cancel, onClick) .setOnCancelListener(onCancel) .show(); registerReceiver(mMountReceiver, mMountFilter); } }
protected void onStart() { super.onStart(); if (getExternalCacheDir() == null) { OnCancelListener onCancel = new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }; OnClickListener onClick = new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }; mAlertDialog = new AlertDialog.Builder(this) .setIconAttribute(android.R.attr.alertDialogIcon) .setTitle("No Storage") .setMessage("No external storage available.") .setNegativeButton(android.R.string.cancel, onClick) .setOnCancelListener(onCancel) .show(); registerReceiver(mMountReceiver, mMountFilter); } }
diff --git a/src/no/ntnu/ai/ui/UserInterface.java b/src/no/ntnu/ai/ui/UserInterface.java index 4790dd4..cdee35b 100644 --- a/src/no/ntnu/ai/ui/UserInterface.java +++ b/src/no/ntnu/ai/ui/UserInterface.java @@ -1,165 +1,165 @@ package no.ntnu.ai.ui; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import no.ntnu.ai.boost.AdaBoost; import no.ntnu.ai.data.DataElement; import no.ntnu.ai.file.parser.Parser; import no.ntnu.ai.hypothesis.Generator; import no.ntnu.ai.hypothesis.Hypothesis; public class UserInterface { private final static String FILE_STRING = "file"; private final static String CLASSIFIER_STRING = "classifier"; private final static String GLOBAL_OPTIONS = "global"; public static List<Generator<?,?>> parseClassifier(List<String> options){ try { int numberOf = Integer.parseInt(options.get(2)); List<Generator<?, ?>> result = new ArrayList<Generator<?,?>>(numberOf); for(int i = 0; i < numberOf; i++){ Generator<?,?> g = (Generator<?, ?>) Class.forName(options.get(1)).newInstance(); g.initialize(options.subList(3, options.size())); result.add(g); } return result; } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { System.err.println("Could not find the specified class: " + options.get(1)); System.exit(-1); } return null; } public static Parser<?, ?> parseFilename(List<String> options){ try { Parser<?, ?> p = (Parser<?, ?>) Class.forName(options.get(1)).newInstance(); p.initialize(options.get(2)); return p; } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { System.err.println("Could not find the specified class: " + options.get(1)); System.exit(-1); } return null; } public static List<List<String>> parseCommandLine(String[] args){ List<List<String>> result = new ArrayList<List<String>>(); int i = -1; for(int j = 0; j < args.length; j++){ String s = args[j]; if(s.equalsIgnoreCase("--" + CLASSIFIER_STRING) || s.equalsIgnoreCase("-c")){ result.add(new ArrayList<String>()); i++; result.get(i).add(CLASSIFIER_STRING); }else if(s.equalsIgnoreCase("--" + FILE_STRING) || s.equalsIgnoreCase("-f")){ result.add(new ArrayList<String>()); i++; result.get(i).add(FILE_STRING); }else if(s.equalsIgnoreCase("--" + GLOBAL_OPTIONS) || s.equalsIgnoreCase("-g")){ result.add(new ArrayList<String>()); i++; result.get(i).add(GLOBAL_OPTIONS); }else{ result.get(i).add(s); } } return result; } /** * @param args */ @SuppressWarnings({ "unchecked" }) public static void main(String[] args) { if(args.length > 1 && !args[0].equalsIgnoreCase("--help")){ List<List<String>> options = parseCommandLine(args); List<List<Generator<?,?>>> classifierGenerators = new ArrayList<List<Generator<?,?>>>(); Parser<?, ?> dataParser = null; double percentage = 0.25; int randomValue = 42; for(List<String> option : options){ if(option.get(0).equalsIgnoreCase(CLASSIFIER_STRING)){ classifierGenerators.add(parseClassifier(option)); }else if(option.get(0).equalsIgnoreCase(FILE_STRING)){ dataParser = parseFilename(option); }else if(option.get(0).equalsIgnoreCase(GLOBAL_OPTIONS)){ percentage = Double.parseDouble(option.get(1)); randomValue = Integer.parseInt(option.get(2)); }else{ System.err.println("Did not recoqnize the option: '" + option.get(0) + "'"); } } //Shuffle data List<?> data = dataParser.getData(); Collections.shuffle(data, new Random(randomValue)); List<DataElement<?, ?>> training = (List<DataElement<?, ?>>) data.subList(0, (int)(data.size() - data.size()*percentage)); List<DataElement<?, ?>> test = (List<DataElement<?, ?>>) data.subList((int)(data.size() - data.size()*percentage), data.size()); //Use adaboost to obtain result: for(List<Generator<?, ?>> l : classifierGenerators){ AdaBoost<?, ?> boost = new AdaBoost(l, training); List<?> hypos = boost.runBooster(); int error = 0; for(DataElement dat : test){ Map<Object, Double> classStrength = new HashMap<Object, Double>(); for(Object o : hypos){ Hypothesis h = (Hypothesis) o; Object classi = h.classify(dat.cloneList()); if(!classStrength.containsKey(classi)){ classStrength.put(classi, 0.0); } classStrength.put(classi, classStrength.get(classi) + h.getWeight()); } Object max = null; double maxVal = -1; for(Object o : classStrength.keySet()){ if(classStrength.get(o) > maxVal){ max = o; maxVal = classStrength.get(o); } } if(!dat.getClassification().equals(max)){ error ++; } } System.out.println(hypos.get(0).getClass().getName() + ":"); System.out.println("Training avg: " + boost.getAvg() + ", std dev: " + boost.getStdDev()); - System.out.println("Test error: " + error); + System.out.println("Test error: " + error + " of " + test.size()); } }else{ String classy = "--" + CLASSIFIER_STRING + " classname " + "numberOfClassifiers [options]"; System.out.println("Usage:"); System.out.println("java " + UserInterface.class.getName() + " --" + GLOBAL_OPTIONS + " percentageOfTestData randomKey" + " --" + FILE_STRING + " filereader name " + classy + " [" + classy + "]"); } } }
true
true
public static void main(String[] args) { if(args.length > 1 && !args[0].equalsIgnoreCase("--help")){ List<List<String>> options = parseCommandLine(args); List<List<Generator<?,?>>> classifierGenerators = new ArrayList<List<Generator<?,?>>>(); Parser<?, ?> dataParser = null; double percentage = 0.25; int randomValue = 42; for(List<String> option : options){ if(option.get(0).equalsIgnoreCase(CLASSIFIER_STRING)){ classifierGenerators.add(parseClassifier(option)); }else if(option.get(0).equalsIgnoreCase(FILE_STRING)){ dataParser = parseFilename(option); }else if(option.get(0).equalsIgnoreCase(GLOBAL_OPTIONS)){ percentage = Double.parseDouble(option.get(1)); randomValue = Integer.parseInt(option.get(2)); }else{ System.err.println("Did not recoqnize the option: '" + option.get(0) + "'"); } } //Shuffle data List<?> data = dataParser.getData(); Collections.shuffle(data, new Random(randomValue)); List<DataElement<?, ?>> training = (List<DataElement<?, ?>>) data.subList(0, (int)(data.size() - data.size()*percentage)); List<DataElement<?, ?>> test = (List<DataElement<?, ?>>) data.subList((int)(data.size() - data.size()*percentage), data.size()); //Use adaboost to obtain result: for(List<Generator<?, ?>> l : classifierGenerators){ AdaBoost<?, ?> boost = new AdaBoost(l, training); List<?> hypos = boost.runBooster(); int error = 0; for(DataElement dat : test){ Map<Object, Double> classStrength = new HashMap<Object, Double>(); for(Object o : hypos){ Hypothesis h = (Hypothesis) o; Object classi = h.classify(dat.cloneList()); if(!classStrength.containsKey(classi)){ classStrength.put(classi, 0.0); } classStrength.put(classi, classStrength.get(classi) + h.getWeight()); } Object max = null; double maxVal = -1; for(Object o : classStrength.keySet()){ if(classStrength.get(o) > maxVal){ max = o; maxVal = classStrength.get(o); } } if(!dat.getClassification().equals(max)){ error ++; } } System.out.println(hypos.get(0).getClass().getName() + ":"); System.out.println("Training avg: " + boost.getAvg() + ", std dev: " + boost.getStdDev()); System.out.println("Test error: " + error); } }else{ String classy = "--" + CLASSIFIER_STRING + " classname " + "numberOfClassifiers [options]"; System.out.println("Usage:"); System.out.println("java " + UserInterface.class.getName() + " --" + GLOBAL_OPTIONS + " percentageOfTestData randomKey" + " --" + FILE_STRING + " filereader name " + classy + " [" + classy + "]"); } }
public static void main(String[] args) { if(args.length > 1 && !args[0].equalsIgnoreCase("--help")){ List<List<String>> options = parseCommandLine(args); List<List<Generator<?,?>>> classifierGenerators = new ArrayList<List<Generator<?,?>>>(); Parser<?, ?> dataParser = null; double percentage = 0.25; int randomValue = 42; for(List<String> option : options){ if(option.get(0).equalsIgnoreCase(CLASSIFIER_STRING)){ classifierGenerators.add(parseClassifier(option)); }else if(option.get(0).equalsIgnoreCase(FILE_STRING)){ dataParser = parseFilename(option); }else if(option.get(0).equalsIgnoreCase(GLOBAL_OPTIONS)){ percentage = Double.parseDouble(option.get(1)); randomValue = Integer.parseInt(option.get(2)); }else{ System.err.println("Did not recoqnize the option: '" + option.get(0) + "'"); } } //Shuffle data List<?> data = dataParser.getData(); Collections.shuffle(data, new Random(randomValue)); List<DataElement<?, ?>> training = (List<DataElement<?, ?>>) data.subList(0, (int)(data.size() - data.size()*percentage)); List<DataElement<?, ?>> test = (List<DataElement<?, ?>>) data.subList((int)(data.size() - data.size()*percentage), data.size()); //Use adaboost to obtain result: for(List<Generator<?, ?>> l : classifierGenerators){ AdaBoost<?, ?> boost = new AdaBoost(l, training); List<?> hypos = boost.runBooster(); int error = 0; for(DataElement dat : test){ Map<Object, Double> classStrength = new HashMap<Object, Double>(); for(Object o : hypos){ Hypothesis h = (Hypothesis) o; Object classi = h.classify(dat.cloneList()); if(!classStrength.containsKey(classi)){ classStrength.put(classi, 0.0); } classStrength.put(classi, classStrength.get(classi) + h.getWeight()); } Object max = null; double maxVal = -1; for(Object o : classStrength.keySet()){ if(classStrength.get(o) > maxVal){ max = o; maxVal = classStrength.get(o); } } if(!dat.getClassification().equals(max)){ error ++; } } System.out.println(hypos.get(0).getClass().getName() + ":"); System.out.println("Training avg: " + boost.getAvg() + ", std dev: " + boost.getStdDev()); System.out.println("Test error: " + error + " of " + test.size()); } }else{ String classy = "--" + CLASSIFIER_STRING + " classname " + "numberOfClassifiers [options]"; System.out.println("Usage:"); System.out.println("java " + UserInterface.class.getName() + " --" + GLOBAL_OPTIONS + " percentageOfTestData randomKey" + " --" + FILE_STRING + " filereader name " + classy + " [" + classy + "]"); } }
diff --git a/src/java/fedora/client/batch/BatchXforms.java b/src/java/fedora/client/batch/BatchXforms.java index 94df0f8f2..81eb2505d 100755 --- a/src/java/fedora/client/batch/BatchXforms.java +++ b/src/java/fedora/client/batch/BatchXforms.java @@ -1,259 +1,259 @@ package fedora.client.batch; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.File; //import java.util.Hashtable; import java.util.Properties; import java.util.Enumeration; import java.util.Calendar; import java.util.GregorianCalendar; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerConfigurationException; //import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactory; // RunXSLT works with this //import javax.xml.transform.sax.SAXTransformerFactory; // was with error import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import java.io.InputStream; import java.io.IOException; import java.io.FileInputStream; import java.io.OutputStream; import java.io.Reader; import java.io.BufferedReader; import java.util.Vector; /** * * <p><b>Title:</b> BatchXforms.java</p> * <p><b>Description:</b> </p> * * ----------------------------------------------------------------------------- * * <p><b>License and Copyright: </b>The contents of this file are subject to the * Mozilla Public License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License * at <a href="http://www.mozilla.org/MPL">http://www.mozilla.org/MPL/.</a></p> * * <p>Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License.</p> * * <p>The entire file consists of original code. Copyright &copy; 2002, 2003 by The * Rector and Visitors of the University of Virginia and Cornell University. * All rights reserved.</p> * * ----------------------------------------------------------------------------- * * @author [email protected] * @version 1.0 */ class BatchXforms { /** Constants used for JAXP 1.2 */ private static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; private static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema"; private static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource"; private String additionsPath = null; private String objectsPath = null; private String xformPath = null; private String modelPath = null; private Transformer transformer = null; BatchXforms(Properties optValues) throws Exception { xformPath = System.getProperty("fedora.home") + "/client/lib/merge.xsl"; additionsPath = optValues.getProperty(BatchTool.ADDITIONSPATH); objectsPath = optValues.getProperty(BatchTool.OBJECTSPATH); modelPath = optValues.getProperty(BatchTool.CMODEL); if (! BatchTool.argOK(additionsPath)) { System.err.println("additionsPath required"); throw new Exception(); } if (! BatchTool.argOK(objectsPath)) { System.err.println("objectsPath required"); throw new Exception(); } if (! BatchTool.argOK(xformPath)) { System.err.println("xformPath required"); throw new Exception(); } } private static final String[] padding = {"", "0", "00", "000"}; private static final String leftPadded (int i, int n) throws Exception { if ((n > 3) || (n < 0) || (i < 0) || (i > 999)) { throw new Exception(); } int m = (i > 99) ? 3 : (i > 9) ? 2 : 1; int p = n - m; return padding[p] + Integer.toString(i); } private boolean good2go = false; final void prep() throws Exception { good2go = true; } private Vector keys = null; /* package */ Vector getKeys() { return keys; } final void process() throws TransformerConfigurationException, Exception { //System.err.println("before TransformerFactory.newInstance()"); //<<== //System.err.println("xformPath=[" + xformPath + "]"); //<<== //SAXTransformerFactory tfactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerFactory tfactory = TransformerFactory.newInstance(); //try this from RunXSLT //System.err.println("after TransformerFactory.newInstance(); tf is null?=" + (tfactory == null)); //<<== keys = new Vector(); if (good2go) { int count = 0; File file4catch = null; int files4catch = 0; int badFileCount = 0; int succeededBuildCount = 0; int failedBuildCount = 0; try { File[] files = null; { // System.err.println("additions path " + additionsPath); File additionsDirectory = new File(additionsPath); files = additionsDirectory.listFiles(); } //int badFileCount = 0; files4catch = files.length; for (int i = 0; i < files.length; i++) { //System.err.println("another it"); file4catch = files[i]; if (! files[i].isFile()) { badFileCount++; System.err.println("additions directory contains unexpected directory or file: " + files[i].getName()); } else { //System.err.println("before tfactory.newTransformer()"); //<<== File f = new File(xformPath); //System.err.println("File " + xformPath + " exists=[" + (f.exists()) + "]"); StreamSource ss = new StreamSource(f); //System.err.println("ss null=[" + (ss == null) + "]"); /* Reader r = ss.getReader(); System.err.println("r null=[" + (r == null) + "]"); BufferedReader br = new BufferedReader(r); System.err.println("br null=[" + (br == null) + "]"); String st = br.readLine(); System.err.println("st null=[" + (st == null) + "]"); System.err.println("first line[" + st + "]"); System.err.println("after dummy SS"); //<<== System.err.println("support?=[" + tfactory.getFeature(StreamSource.FEATURE) + "]"); //<<== */ transformer = tfactory.newTransformer(ss); //xformPath //System.err.println("after tfactory.newTransformer(); is transformer null? " + (transformer == null)); GregorianCalendar calendar = new GregorianCalendar(); String year = Integer.toString(calendar.get(Calendar.YEAR)); String month = leftPadded(1+ calendar.get(Calendar.MONTH),2); String dayOfMonth = leftPadded(calendar.get(Calendar.DAY_OF_MONTH),2); String hourOfDay = leftPadded(calendar.get(Calendar.HOUR_OF_DAY),2); String minute = leftPadded(calendar.get(Calendar.MINUTE),2); String second = leftPadded(calendar.get(Calendar.SECOND),2); transformer.setParameter("date", year + "-" + month + "-" + dayOfMonth + "T" + hourOfDay + ":" + minute + ":" + second); //"2002-05-20T06:32:00" //System.err.println("about to xform " + count++); //System.err.println(">>>>>>>>>>>>" + files[i].getPath()); //System.err.println("objectsPath [" + objectsPath + "]"); /* for (int bb=0; bb<objectsPath.length(); bb++) { char c = objectsPath.charAt(bb); int n = Character.getNumericValue(c); boolean t = Character.isISOControl(c); System.err.print("["+c+"("+n+")"+t+"]"); } */ //System.err.println("File.separator " + File.separator); //System.err.println("files[i].getName() " + files[i].getName()); //System.err.println("before calling xform"); - String temp = "file:///" + files[i].getPath(); //(files[i].getPath()).replaceFirst("C:", "file:///C:"); + String temp = "file://" + files[i].getPath(); //(files[i].getPath()).replaceFirst("C:", "file:///C:"); //System.err.println("path is [" + temp); //files[i].getPath()); transformer.setParameter("subfilepath",temp); //files[i].getPath()); //System.out.println("fis"); FileInputStream fis = new FileInputStream(modelPath); //System.out.println("fos"); FileOutputStream fos = new FileOutputStream(objectsPath + File.separator + files[i].getName()); //System.out.println("fos"); try { //transform(new FileInputStream(files[i]), new FileOutputStream (objectsPath + File.separator + files[i].getName())); transform(fis, fos); //System.out.println("Fedora METS XML created at " + files[i].getName()); succeededBuildCount++; //System.out.println("before keys.add()"); keys.add(files[i].getName()); //System.out.println("after keys.add()"); } catch (Exception e) { //for now, follow processing as-is and throw out rest of batch throw e; } finally { // so that files are available to outside editor during batchtool client use //System.out.println("before fis.close"); fis.close(); //System.out.println("before fos.close"); fos.close(); //System.out.println("after fos.close()"); } } } } catch (Exception e) { System.err.println("Fedora METS XML failed for " + file4catch.getName()); System.err.println("exception: " + e.getMessage() + " , class is " + e.getClass()); failedBuildCount++; } finally { } System.err.println("\n" + "Batch Build Summary"); System.err.println("\n" + (succeededBuildCount + failedBuildCount + badFileCount) + " files processed in this batch"); System.err.println("\t" + succeededBuildCount + " Fedora METS XML documents successfully created"); System.err.println("\t" + failedBuildCount + " Fedora METS XML documents failed"); System.err.println("\t" + badFileCount + " unexpected files in directory"); System.err.println("\t" + (files4catch - (succeededBuildCount + failedBuildCount + badFileCount)) + " files ignored after error"); } } public static final void main(String[] args) { try { Properties miscProperties = new Properties(); miscProperties.load(new FileInputStream("c:\\batchdemo\\batchtool.properties")); BatchXforms batchXforms = new BatchXforms(miscProperties); batchXforms.prep(); batchXforms.process(); } catch (Exception e) { } } public void transform(InputStream sourceStream, OutputStream destStream) throws TransformerException, TransformerConfigurationException { //System.err.println("before transformer.transform()"); transformer.transform(new StreamSource(sourceStream), new StreamResult(destStream)); //System.err.println("after transformer.transform()"); } }
true
true
final void process() throws TransformerConfigurationException, Exception { //System.err.println("before TransformerFactory.newInstance()"); //<<== //System.err.println("xformPath=[" + xformPath + "]"); //<<== //SAXTransformerFactory tfactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerFactory tfactory = TransformerFactory.newInstance(); //try this from RunXSLT //System.err.println("after TransformerFactory.newInstance(); tf is null?=" + (tfactory == null)); //<<== keys = new Vector(); if (good2go) { int count = 0; File file4catch = null; int files4catch = 0; int badFileCount = 0; int succeededBuildCount = 0; int failedBuildCount = 0; try { File[] files = null; { // System.err.println("additions path " + additionsPath); File additionsDirectory = new File(additionsPath); files = additionsDirectory.listFiles(); } //int badFileCount = 0; files4catch = files.length; for (int i = 0; i < files.length; i++) { //System.err.println("another it"); file4catch = files[i]; if (! files[i].isFile()) { badFileCount++; System.err.println("additions directory contains unexpected directory or file: " + files[i].getName()); } else { //System.err.println("before tfactory.newTransformer()"); //<<== File f = new File(xformPath); //System.err.println("File " + xformPath + " exists=[" + (f.exists()) + "]"); StreamSource ss = new StreamSource(f); //System.err.println("ss null=[" + (ss == null) + "]"); /* Reader r = ss.getReader(); System.err.println("r null=[" + (r == null) + "]"); BufferedReader br = new BufferedReader(r); System.err.println("br null=[" + (br == null) + "]"); String st = br.readLine(); System.err.println("st null=[" + (st == null) + "]"); System.err.println("first line[" + st + "]"); System.err.println("after dummy SS"); //<<== System.err.println("support?=[" + tfactory.getFeature(StreamSource.FEATURE) + "]"); //<<== */ transformer = tfactory.newTransformer(ss); //xformPath //System.err.println("after tfactory.newTransformer(); is transformer null? " + (transformer == null)); GregorianCalendar calendar = new GregorianCalendar(); String year = Integer.toString(calendar.get(Calendar.YEAR)); String month = leftPadded(1+ calendar.get(Calendar.MONTH),2); String dayOfMonth = leftPadded(calendar.get(Calendar.DAY_OF_MONTH),2); String hourOfDay = leftPadded(calendar.get(Calendar.HOUR_OF_DAY),2); String minute = leftPadded(calendar.get(Calendar.MINUTE),2); String second = leftPadded(calendar.get(Calendar.SECOND),2); transformer.setParameter("date", year + "-" + month + "-" + dayOfMonth + "T" + hourOfDay + ":" + minute + ":" + second); //"2002-05-20T06:32:00" //System.err.println("about to xform " + count++); //System.err.println(">>>>>>>>>>>>" + files[i].getPath()); //System.err.println("objectsPath [" + objectsPath + "]"); /* for (int bb=0; bb<objectsPath.length(); bb++) { char c = objectsPath.charAt(bb); int n = Character.getNumericValue(c); boolean t = Character.isISOControl(c); System.err.print("["+c+"("+n+")"+t+"]"); } */ //System.err.println("File.separator " + File.separator); //System.err.println("files[i].getName() " + files[i].getName()); //System.err.println("before calling xform"); String temp = "file:///" + files[i].getPath(); //(files[i].getPath()).replaceFirst("C:", "file:///C:"); //System.err.println("path is [" + temp); //files[i].getPath()); transformer.setParameter("subfilepath",temp); //files[i].getPath()); //System.out.println("fis"); FileInputStream fis = new FileInputStream(modelPath); //System.out.println("fos"); FileOutputStream fos = new FileOutputStream(objectsPath + File.separator + files[i].getName()); //System.out.println("fos"); try { //transform(new FileInputStream(files[i]), new FileOutputStream (objectsPath + File.separator + files[i].getName())); transform(fis, fos); //System.out.println("Fedora METS XML created at " + files[i].getName()); succeededBuildCount++; //System.out.println("before keys.add()"); keys.add(files[i].getName()); //System.out.println("after keys.add()"); } catch (Exception e) { //for now, follow processing as-is and throw out rest of batch throw e; } finally { // so that files are available to outside editor during batchtool client use //System.out.println("before fis.close"); fis.close(); //System.out.println("before fos.close"); fos.close(); //System.out.println("after fos.close()"); } } } } catch (Exception e) { System.err.println("Fedora METS XML failed for " + file4catch.getName()); System.err.println("exception: " + e.getMessage() + " , class is " + e.getClass()); failedBuildCount++; } finally { } System.err.println("\n" + "Batch Build Summary"); System.err.println("\n" + (succeededBuildCount + failedBuildCount + badFileCount) + " files processed in this batch"); System.err.println("\t" + succeededBuildCount + " Fedora METS XML documents successfully created"); System.err.println("\t" + failedBuildCount + " Fedora METS XML documents failed"); System.err.println("\t" + badFileCount + " unexpected files in directory"); System.err.println("\t" + (files4catch - (succeededBuildCount + failedBuildCount + badFileCount)) + " files ignored after error"); } }
final void process() throws TransformerConfigurationException, Exception { //System.err.println("before TransformerFactory.newInstance()"); //<<== //System.err.println("xformPath=[" + xformPath + "]"); //<<== //SAXTransformerFactory tfactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerFactory tfactory = TransformerFactory.newInstance(); //try this from RunXSLT //System.err.println("after TransformerFactory.newInstance(); tf is null?=" + (tfactory == null)); //<<== keys = new Vector(); if (good2go) { int count = 0; File file4catch = null; int files4catch = 0; int badFileCount = 0; int succeededBuildCount = 0; int failedBuildCount = 0; try { File[] files = null; { // System.err.println("additions path " + additionsPath); File additionsDirectory = new File(additionsPath); files = additionsDirectory.listFiles(); } //int badFileCount = 0; files4catch = files.length; for (int i = 0; i < files.length; i++) { //System.err.println("another it"); file4catch = files[i]; if (! files[i].isFile()) { badFileCount++; System.err.println("additions directory contains unexpected directory or file: " + files[i].getName()); } else { //System.err.println("before tfactory.newTransformer()"); //<<== File f = new File(xformPath); //System.err.println("File " + xformPath + " exists=[" + (f.exists()) + "]"); StreamSource ss = new StreamSource(f); //System.err.println("ss null=[" + (ss == null) + "]"); /* Reader r = ss.getReader(); System.err.println("r null=[" + (r == null) + "]"); BufferedReader br = new BufferedReader(r); System.err.println("br null=[" + (br == null) + "]"); String st = br.readLine(); System.err.println("st null=[" + (st == null) + "]"); System.err.println("first line[" + st + "]"); System.err.println("after dummy SS"); //<<== System.err.println("support?=[" + tfactory.getFeature(StreamSource.FEATURE) + "]"); //<<== */ transformer = tfactory.newTransformer(ss); //xformPath //System.err.println("after tfactory.newTransformer(); is transformer null? " + (transformer == null)); GregorianCalendar calendar = new GregorianCalendar(); String year = Integer.toString(calendar.get(Calendar.YEAR)); String month = leftPadded(1+ calendar.get(Calendar.MONTH),2); String dayOfMonth = leftPadded(calendar.get(Calendar.DAY_OF_MONTH),2); String hourOfDay = leftPadded(calendar.get(Calendar.HOUR_OF_DAY),2); String minute = leftPadded(calendar.get(Calendar.MINUTE),2); String second = leftPadded(calendar.get(Calendar.SECOND),2); transformer.setParameter("date", year + "-" + month + "-" + dayOfMonth + "T" + hourOfDay + ":" + minute + ":" + second); //"2002-05-20T06:32:00" //System.err.println("about to xform " + count++); //System.err.println(">>>>>>>>>>>>" + files[i].getPath()); //System.err.println("objectsPath [" + objectsPath + "]"); /* for (int bb=0; bb<objectsPath.length(); bb++) { char c = objectsPath.charAt(bb); int n = Character.getNumericValue(c); boolean t = Character.isISOControl(c); System.err.print("["+c+"("+n+")"+t+"]"); } */ //System.err.println("File.separator " + File.separator); //System.err.println("files[i].getName() " + files[i].getName()); //System.err.println("before calling xform"); String temp = "file://" + files[i].getPath(); //(files[i].getPath()).replaceFirst("C:", "file:///C:"); //System.err.println("path is [" + temp); //files[i].getPath()); transformer.setParameter("subfilepath",temp); //files[i].getPath()); //System.out.println("fis"); FileInputStream fis = new FileInputStream(modelPath); //System.out.println("fos"); FileOutputStream fos = new FileOutputStream(objectsPath + File.separator + files[i].getName()); //System.out.println("fos"); try { //transform(new FileInputStream(files[i]), new FileOutputStream (objectsPath + File.separator + files[i].getName())); transform(fis, fos); //System.out.println("Fedora METS XML created at " + files[i].getName()); succeededBuildCount++; //System.out.println("before keys.add()"); keys.add(files[i].getName()); //System.out.println("after keys.add()"); } catch (Exception e) { //for now, follow processing as-is and throw out rest of batch throw e; } finally { // so that files are available to outside editor during batchtool client use //System.out.println("before fis.close"); fis.close(); //System.out.println("before fos.close"); fos.close(); //System.out.println("after fos.close()"); } } } } catch (Exception e) { System.err.println("Fedora METS XML failed for " + file4catch.getName()); System.err.println("exception: " + e.getMessage() + " , class is " + e.getClass()); failedBuildCount++; } finally { } System.err.println("\n" + "Batch Build Summary"); System.err.println("\n" + (succeededBuildCount + failedBuildCount + badFileCount) + " files processed in this batch"); System.err.println("\t" + succeededBuildCount + " Fedora METS XML documents successfully created"); System.err.println("\t" + failedBuildCount + " Fedora METS XML documents failed"); System.err.println("\t" + badFileCount + " unexpected files in directory"); System.err.println("\t" + (files4catch - (succeededBuildCount + failedBuildCount + badFileCount)) + " files ignored after error"); } }
diff --git a/main/src/main/java/com/chinarewards/qqgbvpn/main/protocol/socket/mina/codec/ProtocolMessageDecoder.java b/main/src/main/java/com/chinarewards/qqgbvpn/main/protocol/socket/mina/codec/ProtocolMessageDecoder.java index 0da30e78..e5840c2b 100644 --- a/main/src/main/java/com/chinarewards/qqgbvpn/main/protocol/socket/mina/codec/ProtocolMessageDecoder.java +++ b/main/src/main/java/com/chinarewards/qqgbvpn/main/protocol/socket/mina/codec/ProtocolMessageDecoder.java @@ -1,332 +1,333 @@ /** * */ package com.chinarewards.qqgbvpn.main.protocol.socket.mina.codec; import java.nio.charset.Charset; import org.apache.mina.core.buffer.IoBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.chinarewards.qqgbvpn.common.Tools; import com.chinarewards.qqgbvpn.main.exception.PackageException; import com.chinarewards.qqgbvpn.main.protocol.CmdCodecFactory; import com.chinarewards.qqgbvpn.main.protocol.cmd.CmdConstant; import com.chinarewards.qqgbvpn.main.protocol.cmd.ErrorBodyMessage; import com.chinarewards.qqgbvpn.main.protocol.cmd.HeadMessage; import com.chinarewards.qqgbvpn.main.protocol.cmd.ICommand; import com.chinarewards.qqgbvpn.main.protocol.cmd.Message; import com.chinarewards.qqgbvpn.main.protocol.socket.ProtocolLengths; import com.chinarewards.qqgbvpn.main.session.CodecException; import com.chinarewards.qqgbvpn.main.session.ISessionKey; import com.chinarewards.qqgbvpn.main.session.SessionKeyCodec; /** * * * @author cyril * @since 0.1.0 */ public class ProtocolMessageDecoder { private static final Logger log = LoggerFactory .getLogger(ProtocolMessageDecoder.class); SessionKeyCodec sessionKeyCodec = new SessionKeyCodec(); /** * Stores the result of message decoding. * * @author cyril * @since 0.1.0 */ public static class Result { private final boolean moreDataRequired; private final long oweLength; private final Object message; private final HeadMessage header; /** * * @param moreDataRequired * @param oweLength * @param headMessage * @param message */ public Result(boolean moreDataRequired, long oweLength, HeadMessage headMessage, Object message) { this.moreDataRequired = moreDataRequired; this.oweLength = oweLength; this.message = message; this.header = headMessage; } /** * Returns parsed header, if parsed, no matter the header is correct * or not. * * @return */ public HeadMessage getHeader() { return header; } /** * Returns whether more data is required in order to parse the raw * stream. * * @return <code>true</code> if more input is required, * <code>false</code> otherwise. */ public boolean isMoreDataRequired() { return moreDataRequired; } /** * Returns the expected length. The value is valid only if * {@link #isMoreDataRequired()} returns <code>true</code>. * * @return the expectedLength */ public long getOweLength() { return oweLength; } /** * The parsed message. This method will return a value if and only if * {@link #isMoreDataRequired()} returns <code>true</code>. Otherwise * this method will return <code>false</code>. * * @return the message */ public Object getMessage() { return message; } } private CmdCodecFactory cmdCodecFactory; /** * Creates an instance of <code>ProtocolMessageDecoder</code>. * * @param cmdCodecFactory */ public ProtocolMessageDecoder(CmdCodecFactory cmdCodecFactory) { this.cmdCodecFactory = cmdCodecFactory; } /** * * @param in * @param charset */ public Result decode(IoBuffer in, Charset charset) { log.trace("IoBuffer remaining bytes: {}, current position: {}", in.remaining(), in.position()); // check length, it must greater than header length if (in.remaining() >= ProtocolLengths.HEAD) { boolean sessionKeyDecoded = false; long cmdBodySize = 0; int start = in.position(); // parse message header log.trace("Parsing message header ({} bytes)..", ProtocolLengths.HEAD); PackageHeadCodec headCodec = new PackageHeadCodec(); HeadMessage header = headCodec.decode(in); // parse log.trace("- message header: {}", header); log.trace("- IoBuffer remaining (for body): {}", in.remaining()); // the pure command size // if msg size is 100, header is 16, then cmdBodySize = 84. cmdBodySize = header.getMessageSize() - ProtocolLengths.HEAD; /***** field extension *****/ // act according to the flag.. must be in proper order!!! // flag: session key if ((header.getFlags() & HeadMessage.FLAG_SESSION_ID) != 0) { log.debug("flag FLAG_SESSION_ID is set in header"); log.debug("in.remaining() = {}", in.remaining()); // make sure we have enough data to decode if (in.remaining() >= 4) { // 1 byte of header short sessionKeyVersion = in.getUnsigned(); // 1 byte: reserved. in.getUnsigned(); // 2 byte of length int sessionKeyLength = in.getUnsignedShort(); log.debug("sessionKeyVersion={}", sessionKeyVersion); log.debug("sessionKeyLength={}", sessionKeyLength); // update the command body size // if cmdBodySize = 84, session key length = 10, then // cmdBodySize = 84 - 1 - 2 - 10 = 71 - cmdBodySize -= sessionKeyLength - 4; + cmdBodySize -= (sessionKeyLength + 4); if (sessionKeyVersion == 0 && sessionKeyLength == 0) { // special - it means the client recognize the // session ID bit. - // the three bytes are consumed. + // the 4 bytes are consumed. + log.debug("version 0 session key detected, client can process session ID!"); } else if (in.remaining() < sessionKeyLength) { // not enough data. reset to original position. long owe = header.getMessageSize() - ProtocolLengths.HEAD - 4 - in.remaining(); in.position(start); // restore the original position. return new Result(true, owe, header, null); } else { // enough data to decode session key! // decode the session key. // FIXME distinguish between different exception. try { log.debug( "decoding session key (version: {}, key length: {})", sessionKeyVersion, sessionKeyLength); in.position(start + 3); // decode the session key. ISessionKey sessionKey = sessionKeyCodec.decode(in); header.setSessionKey(sessionKey); log.debug("session key decoded: {}", sessionKey); // session key successfully decoded. sessionKeyDecoded = true; } catch (CodecException e) { log.warn( "error when decoding session key (version: {}, key length: {})", new Object[] { sessionKeyVersion, sessionKeyLength }, e); } } } else { // we don't have enough information to decode header. long owe = header.getMessageSize() - ProtocolLengths.HEAD - in.remaining(); in.position(start); // restore the original position. return new Result(true, owe, header, null); } } /***** field extension *****/ log.debug("before parsing body: cmdBodySize={}, in.remaining={}", cmdBodySize, in.remaining()); // make sure we have enough data to feed. if (in.remaining() < cmdBodySize) { // more data is required. long owe = cmdBodySize - in.remaining(); log.trace("More bytes are required to parse the complete message (still need {} bytes)", owe); in.position(start); // restore the original position. return new Result(true, owe, header, null); } // // validate the checksum. // // byteTmp: raw bytes int calculatedChecksum = 0; { // reset to original position; in.position(start); byte[] byteTmp = new byte[(int)header.getMessageSize()]; // XXX possible truncation // important! just consume the required number of bytes in.get(byteTmp); // CodecUtil.debugRaw(log, byteTmp); // some debug output Tools.putUnsignedShort(byteTmp, 0, 10); // calculate the checksum calculatedChecksum = Tools.checkSum(byteTmp, byteTmp.length); } // validate the checksum. if not correct, return an error response. if (calculatedChecksum != header.getChecksum()) { ErrorBodyMessage bodyMessage = new ErrorBodyMessage(); bodyMessage.setErrorCode(CmdConstant.ERROR_CHECKSUM_CODE); Message message = new Message(header, bodyMessage); log.trace( "Received message has invalid checksum (calc: 0x{}, actual: 0x{})", Integer.toHexString(calculatedChecksum), Integer.toHexString(header.getChecksum())); return new Result(false, 0, header, message); } // really decode the command message. in.position(start + ProtocolLengths.HEAD); ICommand bodyMessage = null; try { bodyMessage = this.decodeMessageBody(in, charset, header); // a message is completely decoded. Message message = new Message(header, bodyMessage); return new Result(false, 0, header, message); } catch (Throwable e) { log.trace("Unexpected error when decoding message", e); ErrorBodyMessage errorBodyMessage = new ErrorBodyMessage(); errorBodyMessage.setErrorCode(CmdConstant.ERROR_MESSAGE_CODE); Message message = new Message(header, errorBodyMessage); return new Result(false, 0, header, message); } } else { long owe = ProtocolLengths.HEAD - in.remaining(); log.trace("More bytes are required to parse the header message (still need {} bytes)", owe); return new Result(true, owe, null, null); } } protected ICommand decodeMessageBody(IoBuffer in, Charset charset, HeadMessage header) throws PackageException { // get cmdId and process it int position = in.position(); long cmdId = in.getUnsignedInt(); in.position(position); log.debug("cmdId: {}", cmdId); // get the message codec for this command ID. ICommandCodec bodyMessageCoder = cmdCodecFactory.getCodec(cmdId); log.trace("Command codec for command ID {}: {}", cmdId, bodyMessageCoder); if (bodyMessageCoder != null) { // codec is found, decode it return bodyMessageCoder.decode(in, charset); } else { // no codec is found: // 1. consume all bytes in the buffer. long toConsume = header.getMessageSize() - ProtocolLengths.HEAD; if (toConsume > 0 && in.remaining() > 0) { long actualConsume = toConsume > in.remaining() ? in.remaining() : toConsume; in.skip((int)actualConsume); // XXX potential problem } // 2. report invalid command ID. ErrorBodyMessage bodyMessage = new ErrorBodyMessage(); bodyMessage.setErrorCode(CmdConstant.ERROR_INVALID_CMD_ID); return bodyMessage; } } }
false
true
public Result decode(IoBuffer in, Charset charset) { log.trace("IoBuffer remaining bytes: {}, current position: {}", in.remaining(), in.position()); // check length, it must greater than header length if (in.remaining() >= ProtocolLengths.HEAD) { boolean sessionKeyDecoded = false; long cmdBodySize = 0; int start = in.position(); // parse message header log.trace("Parsing message header ({} bytes)..", ProtocolLengths.HEAD); PackageHeadCodec headCodec = new PackageHeadCodec(); HeadMessage header = headCodec.decode(in); // parse log.trace("- message header: {}", header); log.trace("- IoBuffer remaining (for body): {}", in.remaining()); // the pure command size // if msg size is 100, header is 16, then cmdBodySize = 84. cmdBodySize = header.getMessageSize() - ProtocolLengths.HEAD; /***** field extension *****/ // act according to the flag.. must be in proper order!!! // flag: session key if ((header.getFlags() & HeadMessage.FLAG_SESSION_ID) != 0) { log.debug("flag FLAG_SESSION_ID is set in header"); log.debug("in.remaining() = {}", in.remaining()); // make sure we have enough data to decode if (in.remaining() >= 4) { // 1 byte of header short sessionKeyVersion = in.getUnsigned(); // 1 byte: reserved. in.getUnsigned(); // 2 byte of length int sessionKeyLength = in.getUnsignedShort(); log.debug("sessionKeyVersion={}", sessionKeyVersion); log.debug("sessionKeyLength={}", sessionKeyLength); // update the command body size // if cmdBodySize = 84, session key length = 10, then // cmdBodySize = 84 - 1 - 2 - 10 = 71 cmdBodySize -= sessionKeyLength - 4; if (sessionKeyVersion == 0 && sessionKeyLength == 0) { // special - it means the client recognize the // session ID bit. // the three bytes are consumed. } else if (in.remaining() < sessionKeyLength) { // not enough data. reset to original position. long owe = header.getMessageSize() - ProtocolLengths.HEAD - 4 - in.remaining(); in.position(start); // restore the original position. return new Result(true, owe, header, null); } else { // enough data to decode session key! // decode the session key. // FIXME distinguish between different exception. try { log.debug( "decoding session key (version: {}, key length: {})", sessionKeyVersion, sessionKeyLength); in.position(start + 3); // decode the session key. ISessionKey sessionKey = sessionKeyCodec.decode(in); header.setSessionKey(sessionKey); log.debug("session key decoded: {}", sessionKey); // session key successfully decoded. sessionKeyDecoded = true; } catch (CodecException e) { log.warn( "error when decoding session key (version: {}, key length: {})", new Object[] { sessionKeyVersion, sessionKeyLength }, e); } } } else { // we don't have enough information to decode header. long owe = header.getMessageSize() - ProtocolLengths.HEAD - in.remaining(); in.position(start); // restore the original position. return new Result(true, owe, header, null); } } /***** field extension *****/ log.debug("before parsing body: cmdBodySize={}, in.remaining={}", cmdBodySize, in.remaining()); // make sure we have enough data to feed. if (in.remaining() < cmdBodySize) { // more data is required. long owe = cmdBodySize - in.remaining(); log.trace("More bytes are required to parse the complete message (still need {} bytes)", owe); in.position(start); // restore the original position. return new Result(true, owe, header, null); } // // validate the checksum. // // byteTmp: raw bytes int calculatedChecksum = 0; { // reset to original position; in.position(start); byte[] byteTmp = new byte[(int)header.getMessageSize()]; // XXX possible truncation // important! just consume the required number of bytes in.get(byteTmp); // CodecUtil.debugRaw(log, byteTmp); // some debug output Tools.putUnsignedShort(byteTmp, 0, 10); // calculate the checksum calculatedChecksum = Tools.checkSum(byteTmp, byteTmp.length); } // validate the checksum. if not correct, return an error response. if (calculatedChecksum != header.getChecksum()) { ErrorBodyMessage bodyMessage = new ErrorBodyMessage(); bodyMessage.setErrorCode(CmdConstant.ERROR_CHECKSUM_CODE); Message message = new Message(header, bodyMessage); log.trace( "Received message has invalid checksum (calc: 0x{}, actual: 0x{})", Integer.toHexString(calculatedChecksum), Integer.toHexString(header.getChecksum())); return new Result(false, 0, header, message); } // really decode the command message. in.position(start + ProtocolLengths.HEAD); ICommand bodyMessage = null; try { bodyMessage = this.decodeMessageBody(in, charset, header); // a message is completely decoded. Message message = new Message(header, bodyMessage); return new Result(false, 0, header, message); } catch (Throwable e) { log.trace("Unexpected error when decoding message", e); ErrorBodyMessage errorBodyMessage = new ErrorBodyMessage(); errorBodyMessage.setErrorCode(CmdConstant.ERROR_MESSAGE_CODE); Message message = new Message(header, errorBodyMessage); return new Result(false, 0, header, message); } } else { long owe = ProtocolLengths.HEAD - in.remaining(); log.trace("More bytes are required to parse the header message (still need {} bytes)", owe); return new Result(true, owe, null, null); } }
public Result decode(IoBuffer in, Charset charset) { log.trace("IoBuffer remaining bytes: {}, current position: {}", in.remaining(), in.position()); // check length, it must greater than header length if (in.remaining() >= ProtocolLengths.HEAD) { boolean sessionKeyDecoded = false; long cmdBodySize = 0; int start = in.position(); // parse message header log.trace("Parsing message header ({} bytes)..", ProtocolLengths.HEAD); PackageHeadCodec headCodec = new PackageHeadCodec(); HeadMessage header = headCodec.decode(in); // parse log.trace("- message header: {}", header); log.trace("- IoBuffer remaining (for body): {}", in.remaining()); // the pure command size // if msg size is 100, header is 16, then cmdBodySize = 84. cmdBodySize = header.getMessageSize() - ProtocolLengths.HEAD; /***** field extension *****/ // act according to the flag.. must be in proper order!!! // flag: session key if ((header.getFlags() & HeadMessage.FLAG_SESSION_ID) != 0) { log.debug("flag FLAG_SESSION_ID is set in header"); log.debug("in.remaining() = {}", in.remaining()); // make sure we have enough data to decode if (in.remaining() >= 4) { // 1 byte of header short sessionKeyVersion = in.getUnsigned(); // 1 byte: reserved. in.getUnsigned(); // 2 byte of length int sessionKeyLength = in.getUnsignedShort(); log.debug("sessionKeyVersion={}", sessionKeyVersion); log.debug("sessionKeyLength={}", sessionKeyLength); // update the command body size // if cmdBodySize = 84, session key length = 10, then // cmdBodySize = 84 - 1 - 2 - 10 = 71 cmdBodySize -= (sessionKeyLength + 4); if (sessionKeyVersion == 0 && sessionKeyLength == 0) { // special - it means the client recognize the // session ID bit. // the 4 bytes are consumed. log.debug("version 0 session key detected, client can process session ID!"); } else if (in.remaining() < sessionKeyLength) { // not enough data. reset to original position. long owe = header.getMessageSize() - ProtocolLengths.HEAD - 4 - in.remaining(); in.position(start); // restore the original position. return new Result(true, owe, header, null); } else { // enough data to decode session key! // decode the session key. // FIXME distinguish between different exception. try { log.debug( "decoding session key (version: {}, key length: {})", sessionKeyVersion, sessionKeyLength); in.position(start + 3); // decode the session key. ISessionKey sessionKey = sessionKeyCodec.decode(in); header.setSessionKey(sessionKey); log.debug("session key decoded: {}", sessionKey); // session key successfully decoded. sessionKeyDecoded = true; } catch (CodecException e) { log.warn( "error when decoding session key (version: {}, key length: {})", new Object[] { sessionKeyVersion, sessionKeyLength }, e); } } } else { // we don't have enough information to decode header. long owe = header.getMessageSize() - ProtocolLengths.HEAD - in.remaining(); in.position(start); // restore the original position. return new Result(true, owe, header, null); } } /***** field extension *****/ log.debug("before parsing body: cmdBodySize={}, in.remaining={}", cmdBodySize, in.remaining()); // make sure we have enough data to feed. if (in.remaining() < cmdBodySize) { // more data is required. long owe = cmdBodySize - in.remaining(); log.trace("More bytes are required to parse the complete message (still need {} bytes)", owe); in.position(start); // restore the original position. return new Result(true, owe, header, null); } // // validate the checksum. // // byteTmp: raw bytes int calculatedChecksum = 0; { // reset to original position; in.position(start); byte[] byteTmp = new byte[(int)header.getMessageSize()]; // XXX possible truncation // important! just consume the required number of bytes in.get(byteTmp); // CodecUtil.debugRaw(log, byteTmp); // some debug output Tools.putUnsignedShort(byteTmp, 0, 10); // calculate the checksum calculatedChecksum = Tools.checkSum(byteTmp, byteTmp.length); } // validate the checksum. if not correct, return an error response. if (calculatedChecksum != header.getChecksum()) { ErrorBodyMessage bodyMessage = new ErrorBodyMessage(); bodyMessage.setErrorCode(CmdConstant.ERROR_CHECKSUM_CODE); Message message = new Message(header, bodyMessage); log.trace( "Received message has invalid checksum (calc: 0x{}, actual: 0x{})", Integer.toHexString(calculatedChecksum), Integer.toHexString(header.getChecksum())); return new Result(false, 0, header, message); } // really decode the command message. in.position(start + ProtocolLengths.HEAD); ICommand bodyMessage = null; try { bodyMessage = this.decodeMessageBody(in, charset, header); // a message is completely decoded. Message message = new Message(header, bodyMessage); return new Result(false, 0, header, message); } catch (Throwable e) { log.trace("Unexpected error when decoding message", e); ErrorBodyMessage errorBodyMessage = new ErrorBodyMessage(); errorBodyMessage.setErrorCode(CmdConstant.ERROR_MESSAGE_CODE); Message message = new Message(header, errorBodyMessage); return new Result(false, 0, header, message); } } else { long owe = ProtocolLengths.HEAD - in.remaining(); log.trace("More bytes are required to parse the header message (still need {} bytes)", owe); return new Result(true, owe, null, null); } }
diff --git a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/FeatureParser.java b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/FeatureParser.java index e8475efc4..5cbe1a34e 100644 --- a/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/FeatureParser.java +++ b/bundles/org.eclipse.equinox.p2.metadata.generator/src/org/eclipse/equinox/internal/p2/metadata/generator/features/FeatureParser.java @@ -1,370 +1,370 @@ /******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.internal.p2.metadata.generator.features; import java.io.*; import java.net.URL; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import javax.xml.parsers.*; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.equinox.internal.p2.core.helpers.LogHelper; import org.eclipse.equinox.internal.p2.metadata.generator.Activator; import org.eclipse.equinox.internal.p2.metadata.generator.LocalizationHelper; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.Feature; import org.eclipse.equinox.internal.provisional.p2.metadata.generator.FeatureEntry; import org.eclipse.osgi.util.NLS; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; /** * Default feature parser. * Parses the feature manifest file as defined by the platform. * * @since 3.0 */ public class FeatureParser extends DefaultHandler { private final static SAXParserFactory parserFactory = SAXParserFactory.newInstance(); private SAXParser parser; protected Feature result; private URL url; private StringBuffer characters = null; private Properties messages = null; private List messageKeys = null; public FeatureParser() { this(true); } protected FeatureParser(boolean createParser) { super(); if (!createParser) return; try { parserFactory.setNamespaceAware(true); this.parser = parserFactory.newSAXParser(); } catch (ParserConfigurationException e) { System.out.println(e); } catch (SAXException e) { System.out.println(e); } } public void characters(char[] ch, int start, int length) throws SAXException { if (characters == null) return; characters.append(ch, start, length); } protected Feature createFeature(String id, String version) { return new Feature(id, version); } public void endElement(String uri, String localName, String qName) throws SAXException { if (characters == null) return; if ("description".equals(localName)) { //$NON-NLS-1$ result.setDescription(localize(characters.toString().trim())); } else if ("license".equals(localName)) { //$NON-NLS-1$ result.setLicense(localize(characters.toString().trim())); } else if ("copyright".equals(localName)) { //$NON-NLS-1$ result.setCopyright(localize(characters.toString().trim())); } characters = null; } public Feature getResult() { return result; } private void loadProperties(File directory, Properties properties) { //skip directories that don't contain a feature.properties file File file = new File(directory, "feature.properties"); //$NON-NLS-1$ if (!file.exists()) return; try { InputStream input = new BufferedInputStream(new FileInputStream(file)); try { properties.load(input); } finally { if (input != null) input.close(); } } catch (IOException e) { e.printStackTrace(); } } private void loadProperties(JarFile jar, Properties properties) { JarEntry entry = jar.getJarEntry("feature.properties"); //$NON-NLS-1$ if (entry == null) return; try { InputStream input = new BufferedInputStream(jar.getInputStream(entry)); try { properties.load(input); } finally { if (input != null) input.close(); } } catch (IOException e) { e.printStackTrace(); } } private String localize(String value) { if (messages == null || value == null) return value; if (!value.startsWith("%")) //$NON-NLS-1$ return value; String key = value.substring(1); messageKeys.add(key); return value; } /** * Parses the specified location and constructs a feature. The given location * should be either the location of the feature JAR or the directory containing * the feature. * * @param location the location of the feature to parse. */ public Feature parse(File location) { if (!location.exists()) return null; Feature feature = null; Properties properties = new Properties(); if (location.isDirectory()) { //skip directories that don't contain a feature.xml file File file = new File(location, "feature.xml"); //$NON-NLS-1$ if (!file.exists()) return null; loadProperties(location, properties); try { InputStream input = new BufferedInputStream(new FileInputStream(file)); feature = parse(input, properties); if (feature != null) { String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); feature.setLocalizations(LocalizationHelper.getDirPropertyLocalizations(location, "feature", null, keyStrings)); //$NON-NLS-1$ } } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (location.getName().endsWith(".jar")) { //$NON-NLS-1$ JarFile jar = null; try { jar = new JarFile(location); loadProperties(jar, properties); JarEntry entry = jar.getJarEntry("feature.xml"); //$NON-NLS-1$ if (entry == null) return null; InputStream input = new BufferedInputStream(jar.getInputStream(entry)); feature = parse(input, properties); if (feature != null) { String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); - feature.setLocalizations(LocalizationHelper.getDirPropertyLocalizations(location, "feature", null, keyStrings)); //$NON-NLS-1$ + feature.setLocalizations(LocalizationHelper.getJarPropertyLocalizations(location, "feature", null, keyStrings)); //$NON-NLS-1$ } } catch (IOException e) { e.printStackTrace(); } catch (SecurityException e) { LogHelper.log(new Status(IStatus.WARNING, Activator.ID, "Exception parsing feature: " + location.getAbsolutePath(), e)); //$NON-NLS-1$ } finally { try { if (jar != null) jar.close(); } catch (IOException e) { // } } } return feature; } /** * Parse the given input stream and return a feature object * or null. This method closes the input stream. */ public Feature parse(InputStream in, Properties messages) { this.messages = messages; this.messageKeys = new ArrayList(messages.size()); result = null; try { parser.parse(new InputSource(in), this); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e1) { // Utils.log(e1.getLocalizedMessage()); } } return result; } private void processCopyright(Attributes attributes) { result.setCopyrightURL(attributes.getValue("url")); //$NON-NLS-1$ characters = new StringBuffer(); } private void processDescription(Attributes attributes) { result.setDescriptionURL(attributes.getValue("url")); //$NON-NLS-1$ characters = new StringBuffer(); } private void processDiscoverySite(Attributes attributes) { //ignore discovery sites of type 'web' if ("web".equals(attributes.getValue("type"))) //$NON-NLS-1$ //$NON-NLS-2$ return; result.addDiscoverySite(attributes.getValue("label"), attributes.getValue("url")); //$NON-NLS-1$ //$NON-NLS-2$ } protected void processFeature(Attributes attributes) { String id = attributes.getValue("id"); //$NON-NLS-1$ String ver = attributes.getValue("version"); //$NON-NLS-1$ if (id == null || id.trim().equals("") //$NON-NLS-1$ || ver == null || ver.trim().equals("")) { //$NON-NLS-1$ // System.out.println(NLS.bind(Messages.FeatureParser_IdOrVersionInvalid, (new String[] { id, ver}))); } else { result = createFeature(id, ver); String os = attributes.getValue("os"); //$NON-NLS-1$ String ws = attributes.getValue("ws"); //$NON-NLS-1$ String nl = attributes.getValue("nl"); //$NON-NLS-1$ String arch = attributes.getValue("arch"); //$NON-NLS-1$ result.setEnvironment(os, ws, arch, nl); //TODO rootURLs if (url != null && "file".equals(url.getProtocol())) { //$NON-NLS-1$ File f = new File(url.getFile().replace('/', File.separatorChar)); result.setURL("features" + "/" + f.getParentFile().getName() + "/");// + f.getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { // externalized URLs might be in relative form, ensure they are absolute // feature.setURL(Utils.makeAbsolute(Utils.getInstallURL(), url).toExternalForm()); } result.setProviderName(localize(attributes.getValue("provider-name"))); //$NON-NLS-1$ result.setLabel(localize(attributes.getValue("label"))); //$NON-NLS-1$ result.setImage(attributes.getValue("image")); //$NON-NLS-1$ // Utils.debug("End process DefaultFeature tag: id:" +id + " ver:" +ver + " url:" + feature.getURL()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } private void processImport(Attributes attributes) { String id = attributes.getValue("feature"); //$NON-NLS-1$ FeatureEntry entry = null; if (id != null) { if ("true".equalsIgnoreCase(attributes.getValue("patch"))) { //$NON-NLS-1$ //$NON-NLS-2$ entry = FeatureEntry.createRequires(id, attributes.getValue("version"), "perfect", attributes.getValue("filter"), false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ entry.setPatch(true); } else { entry = FeatureEntry.createRequires(id, attributes.getValue("version"), attributes.getValue("match"), attributes.getValue("filter"), false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } else { id = attributes.getValue("plugin"); //$NON-NLS-1$ entry = FeatureEntry.createRequires(id, attributes.getValue("version"), attributes.getValue("match"), attributes.getValue("filter"), true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } result.addEntry(entry); } private void processIncludes(Attributes attributes) { FeatureEntry entry = new FeatureEntry(attributes.getValue("id"), attributes.getValue("version"), false); //$NON-NLS-1$ //$NON-NLS-2$ String flag = attributes.getValue("optional"); //$NON-NLS-1$ if (flag != null) entry.setOptional(Boolean.valueOf(flag).booleanValue()); setEnvironment(attributes, entry); result.addEntry(entry); } private void processInstallHandler(Attributes attributes) { result.setInstallHandler(attributes.getValue("handler")); //$NON-NLS-1$ result.setInstallHandlerLibrary(attributes.getValue("library")); //$NON-NLS-1$ result.setInstallHandlerURL(attributes.getValue("url")); //$NON-NLS-1$ } private void processLicense(Attributes attributes) { result.setLicenseURL(attributes.getValue("url")); //$NON-NLS-1$ characters = new StringBuffer(); } private void processPlugin(Attributes attributes) { String id = attributes.getValue("id"); //$NON-NLS-1$ String version = attributes.getValue("version"); //$NON-NLS-1$ if (id == null || id.trim().equals("") || version == null || version.trim().equals("")) { //$NON-NLS-1$ //$NON-NLS-2$ System.out.println(NLS.bind("FeatureParser#processPlugin, ID {0} or version {1} invalid", (new String[] {id, version}))); //$NON-NLS-1$ } else { FeatureEntry plugin = new FeatureEntry(id, version, true); setEnvironment(attributes, plugin); String unpack = attributes.getValue("unpack"); //$NON-NLS-1$ if (unpack != null) plugin.setUnpack(Boolean.valueOf(unpack).booleanValue()); String fragment = attributes.getValue("fragment"); //$NON-NLS-1$ if (fragment != null) plugin.setFragment(Boolean.valueOf(fragment).booleanValue()); String filter = attributes.getValue("filter"); //$NON-NLS-1$ if (filter != null) plugin.setFilter(filter); result.addEntry(plugin); // Utils.debug("End process DefaultFeature tag: id:" + id + " ver:" + ver + " url:" + feature.getURL()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } private void processUpdateSite(Attributes attributes) { result.setUpdateSiteLabel(attributes.getValue("label")); //$NON-NLS-1$ result.setUpdateSiteURL(attributes.getValue("url")); //$NON-NLS-1$ } private void setEnvironment(Attributes attributes, FeatureEntry entry) { String os = attributes.getValue("os"); //$NON-NLS-1$ String ws = attributes.getValue("ws"); //$NON-NLS-1$ String nl = attributes.getValue("nl"); //$NON-NLS-1$ String arch = attributes.getValue("arch"); //$NON-NLS-1$ entry.setEnvironment(os, ws, arch, nl); } public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // Utils.debug("Start Element: uri:" + uri + " local Name:" + localName + " qName:" + qName); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if ("plugin".equals(localName)) { //$NON-NLS-1$ processPlugin(attributes); } else if ("description".equals(localName)) { //$NON-NLS-1$ processDescription(attributes); } else if ("license".equals(localName)) { //$NON-NLS-1$ processLicense(attributes); } else if ("copyright".equals(localName)) { //$NON-NLS-1$ processCopyright(attributes); } else if ("feature".equals(localName)) { //$NON-NLS-1$ processFeature(attributes); } else if ("import".equals(localName)) { //$NON-NLS-1$ processImport(attributes); } else if ("includes".equals(localName)) { //$NON-NLS-1$ processIncludes(attributes); } else if ("install-handler".equals(localName)) { //$NON-NLS-1$ processInstallHandler(attributes); } else if ("update".equals(localName)) { //$NON-NLS-1$ processUpdateSite(attributes); } else if ("discovery".equals(localName)) { //$NON-NLS-1$ processDiscoverySite(attributes); } } }
true
true
public Feature parse(File location) { if (!location.exists()) return null; Feature feature = null; Properties properties = new Properties(); if (location.isDirectory()) { //skip directories that don't contain a feature.xml file File file = new File(location, "feature.xml"); //$NON-NLS-1$ if (!file.exists()) return null; loadProperties(location, properties); try { InputStream input = new BufferedInputStream(new FileInputStream(file)); feature = parse(input, properties); if (feature != null) { String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); feature.setLocalizations(LocalizationHelper.getDirPropertyLocalizations(location, "feature", null, keyStrings)); //$NON-NLS-1$ } } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (location.getName().endsWith(".jar")) { //$NON-NLS-1$ JarFile jar = null; try { jar = new JarFile(location); loadProperties(jar, properties); JarEntry entry = jar.getJarEntry("feature.xml"); //$NON-NLS-1$ if (entry == null) return null; InputStream input = new BufferedInputStream(jar.getInputStream(entry)); feature = parse(input, properties); if (feature != null) { String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); feature.setLocalizations(LocalizationHelper.getDirPropertyLocalizations(location, "feature", null, keyStrings)); //$NON-NLS-1$ } } catch (IOException e) { e.printStackTrace(); } catch (SecurityException e) { LogHelper.log(new Status(IStatus.WARNING, Activator.ID, "Exception parsing feature: " + location.getAbsolutePath(), e)); //$NON-NLS-1$ } finally { try { if (jar != null) jar.close(); } catch (IOException e) { // } } } return feature; }
public Feature parse(File location) { if (!location.exists()) return null; Feature feature = null; Properties properties = new Properties(); if (location.isDirectory()) { //skip directories that don't contain a feature.xml file File file = new File(location, "feature.xml"); //$NON-NLS-1$ if (!file.exists()) return null; loadProperties(location, properties); try { InputStream input = new BufferedInputStream(new FileInputStream(file)); feature = parse(input, properties); if (feature != null) { String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); feature.setLocalizations(LocalizationHelper.getDirPropertyLocalizations(location, "feature", null, keyStrings)); //$NON-NLS-1$ } } catch (FileNotFoundException e) { e.printStackTrace(); } } else if (location.getName().endsWith(".jar")) { //$NON-NLS-1$ JarFile jar = null; try { jar = new JarFile(location); loadProperties(jar, properties); JarEntry entry = jar.getJarEntry("feature.xml"); //$NON-NLS-1$ if (entry == null) return null; InputStream input = new BufferedInputStream(jar.getInputStream(entry)); feature = parse(input, properties); if (feature != null) { String[] keyStrings = (String[]) messageKeys.toArray(new String[messageKeys.size()]); feature.setLocalizations(LocalizationHelper.getJarPropertyLocalizations(location, "feature", null, keyStrings)); //$NON-NLS-1$ } } catch (IOException e) { e.printStackTrace(); } catch (SecurityException e) { LogHelper.log(new Status(IStatus.WARNING, Activator.ID, "Exception parsing feature: " + location.getAbsolutePath(), e)); //$NON-NLS-1$ } finally { try { if (jar != null) jar.close(); } catch (IOException e) { // } } } return feature; }
diff --git a/GraphRealisation/src/UndirectedGraph.java b/GraphRealisation/src/UndirectedGraph.java index 90249e3..bfa0368 100644 --- a/GraphRealisation/src/UndirectedGraph.java +++ b/GraphRealisation/src/UndirectedGraph.java @@ -1,204 +1,204 @@ import java.util.ArrayList; import java.util.Scanner; /** * Created with IntelliJ IDEA. * User: rlokc * Date: 27.10.12 * Time: 11:53 * Реализация ненаправленого графа. Граф хранится в матрице смежности, где на пересечениях указан их вес. * To change this template use File | Settings | File Templates. */ public class UndirectedGraph { private ArrayList<ArrayList<Integer>> weightList; private Integer nodeAmount; private ArrayList<Node> nodes; // private Scanner tempScanner = new Scanner(System.in); private Scanner scanner = new Scanner(System.in); /** * Nodes list getter * * @return List of nodes */ public ArrayList<Node> getNodesList() { return nodes; } /** * Node amount getter * * @return Node amount */ public Integer getNodeAmount() { return nodeAmount; } /** * Node amount setter * * @param nodeAmount Node amount to set */ public void setNodeAmount(Integer nodeAmount) { this.nodeAmount = nodeAmount; } /** * Weight list setter * * @param weightList Weight list to set */ public void setWeightList(ArrayList<ArrayList<Integer>> weightList) { this.weightList = weightList; } /** * Node generator */ /** * Don't know * * @return ??? */ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // GraphGenerator //TODO: Make it possible to read all from some file if desired, punching the numbers is quite annoying //TODO: Make exceptions for tempScanner if file does not exist //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public UndirectedGraph generateGraph() { /* System.out.println("Write the file of matrix, if you want to use stdin, write 0"); //TODO: FIX IT! String source = tempScanner.next(); if (source == "0"){ scanner = tempScanner; } else { scanner = new Scanner(source); } */ System.out.println("Write ammount of nodes in graph:"); int nodeAmount = scanner.nextInt(); UndirectedGraph graph = new UndirectedGraph(); System.out.println("Write matrix:"); ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>(nodeAmount); for (int i = 0; i < nodeAmount; i++) { ArrayList<Integer> tmp = new ArrayList<Integer>(nodeAmount); tmp.clear(); for (int j = 0; j < nodeAmount; j++) { tmp.add(scanner.nextInt()); } matrix.add(tmp); } graph.setWeightList(matrix); graph.setNodeAmount(nodeAmount); graph.nodeGenerator(); // scanner.close(); //Seems to close the whole input, so I'll probably delete it return graph; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Method for Generating nodes. Part of a GraphGenerator //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void nodeGenerator() { nodes = new ArrayList<Node>(nodeAmount); System.out.println("Write addresses of all networks"); for (int i = 0; i < nodeAmount; i++) { //Making nodeAmount of nodes Node tmpNode = new Node(scanner.next()); nodes.add(tmpNode); } for (int i = 0; i < nodeAmount; i++) { //Looking through rows (the nodes) Node tmpNode1 = nodes.get(i); for (int j = 0; j < nodeAmount; j++) { //Looking through links with tmpNodes Node comparableNode = nodes.get(j); if (tmpNode1 != comparableNode) { //Checking if not comparing to itself, we don't need this int tmpWeigth = weightList.get(i).get(j); if (tmpWeigth != 0) { Edge tmpEdge = new Edge(tmpNode1, comparableNode, tmpWeigth); //Adding edges to both nodes tmpNode1.addAdjacency(tmpEdge); } } } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Fuck Stas's searcher, let's do our own! //Dijkstra's Algorithm realisation //TODO: Currently it doesn't work with "segmented" graphs (some nodes are separated), but who cares really :3 //TODO: Good idea to check if it actually works, but i don't have any graphs here right now //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void dijkstraSearch(Node startNode, Node targetNode) { startNode.setMark(0); startNode.isPassed = true; Node currentNode = startNode; Node nextNode = null; //Next node we are going to visit boolean isFinished = false; boolean isReachedTarget = false; while (!isFinished) { int nextNodeMark = Integer.MAX_VALUE; for (Edge tmpEdge : currentNode.getAdjacencies()) { //Looking through each connection in the node Node endNode = tmpEdge.getEndNode(); //Ending node of current edge if (!endNode.isPassed) { //If this node wasn't passed early int comparableMark = currentNode.getMark()+tmpEdge.getWeight(); //currentNode mark + edge weigth if (endNode == targetNode) { isReachedTarget = true; } if (comparableMark<endNode.getMark()){ //Comparing endNode mark to comparableMark endNode.setMark(comparableMark); //Replacing if new mark is less } if (comparableMark < nextNodeMark) { nextNode = endNode; nextNodeMark = comparableMark; } } } - currentNode.isPassed = true; //Our node is now "red", we don't need to visit it + currentNode.isPassed = true; //Our node is now "out", we don't need to visit it later currentNode = nextNode; isFinished = true; //Checking if all nodes are out for (Node checkNote : this.getNodesList()) { if (!checkNote.isPassed) { isFinished = false; if (isReachedTarget) { currentNode = checkNote; //If we reached the "end" of graph, do the search for all the other unvisited nodes } break; } } } //Debug System.out.println("YOUR BUNNY WROTE: "); System.out.print(targetNode.getMark()); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Master for running desired algorithms //TODO:Make it array-based, would be more extendable this way //TODO:Use the bloody nodenames you have! (Though it'll make it all a lil bit slower) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void algorithmMaster(){ System.out.println("Write a number of a desired algorithm:"); System.out.println("0 for Dijkstra's"); int choice = scanner.nextInt(); switch(choice){ case 0:{ //Dijkstra System.out.println("Write indexes of starting and target nodes:"); Node startNode = this.getNodesList().get(scanner.nextInt()); Node endNode = this.getNodesList().get(scanner.nextInt()); this.dijkstraSearch(startNode,endNode); break; } default:break; } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //SCANNER CLOSING //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public void closeScanner(){ scanner.close(); } }
true
true
void dijkstraSearch(Node startNode, Node targetNode) { startNode.setMark(0); startNode.isPassed = true; Node currentNode = startNode; Node nextNode = null; //Next node we are going to visit boolean isFinished = false; boolean isReachedTarget = false; while (!isFinished) { int nextNodeMark = Integer.MAX_VALUE; for (Edge tmpEdge : currentNode.getAdjacencies()) { //Looking through each connection in the node Node endNode = tmpEdge.getEndNode(); //Ending node of current edge if (!endNode.isPassed) { //If this node wasn't passed early int comparableMark = currentNode.getMark()+tmpEdge.getWeight(); //currentNode mark + edge weigth if (endNode == targetNode) { isReachedTarget = true; } if (comparableMark<endNode.getMark()){ //Comparing endNode mark to comparableMark endNode.setMark(comparableMark); //Replacing if new mark is less } if (comparableMark < nextNodeMark) { nextNode = endNode; nextNodeMark = comparableMark; } } } currentNode.isPassed = true; //Our node is now "red", we don't need to visit it currentNode = nextNode; isFinished = true; //Checking if all nodes are out for (Node checkNote : this.getNodesList()) { if (!checkNote.isPassed) { isFinished = false; if (isReachedTarget) { currentNode = checkNote; //If we reached the "end" of graph, do the search for all the other unvisited nodes } break; } } } //Debug System.out.println("YOUR BUNNY WROTE: "); System.out.print(targetNode.getMark()); }
void dijkstraSearch(Node startNode, Node targetNode) { startNode.setMark(0); startNode.isPassed = true; Node currentNode = startNode; Node nextNode = null; //Next node we are going to visit boolean isFinished = false; boolean isReachedTarget = false; while (!isFinished) { int nextNodeMark = Integer.MAX_VALUE; for (Edge tmpEdge : currentNode.getAdjacencies()) { //Looking through each connection in the node Node endNode = tmpEdge.getEndNode(); //Ending node of current edge if (!endNode.isPassed) { //If this node wasn't passed early int comparableMark = currentNode.getMark()+tmpEdge.getWeight(); //currentNode mark + edge weigth if (endNode == targetNode) { isReachedTarget = true; } if (comparableMark<endNode.getMark()){ //Comparing endNode mark to comparableMark endNode.setMark(comparableMark); //Replacing if new mark is less } if (comparableMark < nextNodeMark) { nextNode = endNode; nextNodeMark = comparableMark; } } } currentNode.isPassed = true; //Our node is now "out", we don't need to visit it later currentNode = nextNode; isFinished = true; //Checking if all nodes are out for (Node checkNote : this.getNodesList()) { if (!checkNote.isPassed) { isFinished = false; if (isReachedTarget) { currentNode = checkNote; //If we reached the "end" of graph, do the search for all the other unvisited nodes } break; } } } //Debug System.out.println("YOUR BUNNY WROTE: "); System.out.print(targetNode.getMark()); }
diff --git a/Chat/src/Communications/TCPReceiverThread.java b/Chat/src/Communications/TCPReceiverThread.java index e6caf63..46b7922 100644 --- a/Chat/src/Communications/TCPReceiverThread.java +++ b/Chat/src/Communications/TCPReceiverThread.java @@ -1,61 +1,62 @@ package Communications; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.net.SocketTimeoutException; import java.util.concurrent.ConcurrentLinkedQueue; public class TCPReceiverThread implements Runnable { ConcurrentLinkedQueue<Byte> queue=null; Socket socket=null; InputStream is=null; boolean running=true; public TCPReceiverThread(ConcurrentLinkedQueue<Byte> _queue){ queue=_queue; } public int setSocket(Socket _socket){ socket=_socket; try { socket.setSoTimeout(500); is=socket.getInputStream(); } catch (IOException e) { return -1; } return 0; } public String getIP(){ return socket.getInetAddress().getHostAddress(); } public void run() { byte[] packet=null; while(running){ packet=new byte[5000]; try{ int size=is.read(packet); for(int i=0;i<size;i++){ queue.add(packet[i]); } System.out.println("Got it"); + System.out.println(size); } catch(SocketTimeoutException e){ } catch (IOException e) { System.out.println("\rTCP socket receive error"); running=false; } } try { is.close(); socket.close(); } catch (IOException e) { } try { socket.close(); } catch (IOException e) {} } public void stop(){ running=false; } }
true
true
public void run() { byte[] packet=null; while(running){ packet=new byte[5000]; try{ int size=is.read(packet); for(int i=0;i<size;i++){ queue.add(packet[i]); } System.out.println("Got it"); } catch(SocketTimeoutException e){ } catch (IOException e) { System.out.println("\rTCP socket receive error"); running=false; } } try { is.close(); socket.close(); } catch (IOException e) { } try { socket.close(); } catch (IOException e) {} }
public void run() { byte[] packet=null; while(running){ packet=new byte[5000]; try{ int size=is.read(packet); for(int i=0;i<size;i++){ queue.add(packet[i]); } System.out.println("Got it"); System.out.println(size); } catch(SocketTimeoutException e){ } catch (IOException e) { System.out.println("\rTCP socket receive error"); running=false; } } try { is.close(); socket.close(); } catch (IOException e) { } try { socket.close(); } catch (IOException e) {} }
diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/handlers/VCloudDirectorErrorHandler.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/handlers/VCloudDirectorErrorHandler.java index eb04ca48c0..5d209865c7 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/handlers/VCloudDirectorErrorHandler.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/handlers/VCloudDirectorErrorHandler.java @@ -1,77 +1,77 @@ /** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. jclouds licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jclouds.vcloud.director.v1_5.handlers; import static org.jclouds.http.HttpUtils.closeClientButKeepContentStream; import javax.inject.Singleton; import javax.xml.bind.JAXB; import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; import org.jclouds.io.InputSuppliers; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.vcloud.director.v1_5.VCloudDirectorException; import org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType; import org.jclouds.vcloud.director.v1_5.domain.Error; import com.google.common.base.Throwables; /** * This will parse and set an appropriate exception on the command object. * * @author Adrian Cole */ @Singleton public class VCloudDirectorErrorHandler implements HttpErrorHandler { @Override public void handleError(HttpCommand command, HttpResponse response) { // it is important to always read fully and close streams byte[] data = closeClientButKeepContentStream(response); // Create default exception String message = data != null ? new String(data) : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); - Exception exception = new HttpResponseException(command, response, response.getPayload().getContentMetadata().getContentType()); + Exception exception = new HttpResponseException(command, response, message); // Try to create a VCloudDirectorException from XML payload if (response.getPayload().getContentMetadata().getContentType().startsWith(VCloudDirectorMediaType.ERROR)) { try { Error error = JAXB.unmarshal(InputSuppliers.of(data).getInput(), Error.class); exception = new VCloudDirectorException(error); } catch (Exception e) { Throwables.propagate(e); } } // Create custom exception for error codes we know about if (response.getStatusCode() == 401) { exception = new AuthorizationException(message, exception); } else if (response.getStatusCode() == 403 || response.getStatusCode() == 404) { exception = new ResourceNotFoundException(message, exception); } command.setException(exception); } }
true
true
public void handleError(HttpCommand command, HttpResponse response) { // it is important to always read fully and close streams byte[] data = closeClientButKeepContentStream(response); // Create default exception String message = data != null ? new String(data) : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); Exception exception = new HttpResponseException(command, response, response.getPayload().getContentMetadata().getContentType()); // Try to create a VCloudDirectorException from XML payload if (response.getPayload().getContentMetadata().getContentType().startsWith(VCloudDirectorMediaType.ERROR)) { try { Error error = JAXB.unmarshal(InputSuppliers.of(data).getInput(), Error.class); exception = new VCloudDirectorException(error); } catch (Exception e) { Throwables.propagate(e); } } // Create custom exception for error codes we know about if (response.getStatusCode() == 401) { exception = new AuthorizationException(message, exception); } else if (response.getStatusCode() == 403 || response.getStatusCode() == 404) { exception = new ResourceNotFoundException(message, exception); } command.setException(exception); }
public void handleError(HttpCommand command, HttpResponse response) { // it is important to always read fully and close streams byte[] data = closeClientButKeepContentStream(response); // Create default exception String message = data != null ? new String(data) : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); Exception exception = new HttpResponseException(command, response, message); // Try to create a VCloudDirectorException from XML payload if (response.getPayload().getContentMetadata().getContentType().startsWith(VCloudDirectorMediaType.ERROR)) { try { Error error = JAXB.unmarshal(InputSuppliers.of(data).getInput(), Error.class); exception = new VCloudDirectorException(error); } catch (Exception e) { Throwables.propagate(e); } } // Create custom exception for error codes we know about if (response.getStatusCode() == 401) { exception = new AuthorizationException(message, exception); } else if (response.getStatusCode() == 403 || response.getStatusCode() == 404) { exception = new ResourceNotFoundException(message, exception); } command.setException(exception); }
diff --git a/org.oobium.build/src/org/oobium/build/workspace/Exporter.java b/org.oobium.build/src/org/oobium/build/workspace/Exporter.java index 7c9b3908..38026f34 100644 --- a/org.oobium.build/src/org/oobium/build/workspace/Exporter.java +++ b/org.oobium.build/src/org/oobium/build/workspace/Exporter.java @@ -1,473 +1,473 @@ /******************************************************************************* * Copyright (c) 2010 Oobium, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Jeremy Dowdall <[email protected]> - initial API and implementation ******************************************************************************/ package org.oobium.build.workspace; import static org.oobium.utils.FileUtils.EXECUTABLE; import static org.oobium.utils.FileUtils.copy; import static org.oobium.utils.FileUtils.createFolder; import static org.oobium.utils.FileUtils.deleteContents; import static org.oobium.utils.FileUtils.writeFile; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.oobium.build.BuildBundle; import org.oobium.logging.Logger; import org.oobium.utils.FileUtils; import org.oobium.utils.Config.Mode; import org.oobium.utils.Config.OsgiRuntime; public class Exporter { /** * Bundles that are Applications only */ public static final int APP = 1 << 0; /** * Bundles that are either Applications or Modules (application extends module) */ public static final int MODULE = 1 << 1; /** * Bundles that are Migrations */ public static final int MIGRATION = 1 << 2; /** * Bundles that export a Service */ public static final int SERVICE = 1 << 3; private static final String START_SCRIPT = "#!/bin/bash\n" + "pidfile=running.pid\n" + "if [ -e $pidfile ]; then\n" + " echo \"Already running\"\n" + " exit 1\n" + "else\n" + " java -jar bin/felix.jar &\n" + " echo $! > $pidfile\n" + "fi"; private static final String STOP_SCRIPT = "#!/bin/bash\n" + "pidfile=running.pid\n" + "if [ -e $pidfile ]; then\n" + " kill `cat $pidfile`\n" + " rm $pidfile\n" + " echo \"Process stopped\"\n" + "else\n" + " echo \"Cannot find $pidfile file - is process actually running?\"\n" + " exit 1\n" + "fi"; private final Logger logger; private final Workspace workspace; private final Set<Application> applications; private final Set<Bundle> start; private final Set<Bundle> includes; private final File exportDir; private final File binDir; private final File bundleDir; private boolean clean; private boolean cleanCache; private Mode mode; private Set<Bundle> exportedBundles; private Set<Bundle> exportedStart; private int startTypes; public Exporter(Workspace workspace) { this(workspace, workspace.getApplications()); } public Exporter(Workspace workspace, Application...applications) { this(workspace, Arrays.asList(applications)); } public Exporter(Workspace workspace, Collection<Application> applications) { this.logger = Logger.getLogger(BuildBundle.class); this.workspace = workspace; this.applications = new LinkedHashSet<Application>(applications); this.start = new LinkedHashSet<Bundle>(); this.includes = new LinkedHashSet<Bundle>(); this.exportDir = new File(workspace.getWorkingDirectory(), "export"); this.binDir = new File(exportDir, "bin"); this.bundleDir = new File(exportDir, "bundles"); this.mode = Mode.DEV; this.exportedBundles = new LinkedHashSet<Bundle>(); this.exportedStart = new LinkedHashSet<Bundle>(); setStartTypes(MODULE | SERVICE); } public void setStartTypes(int startTypes) { this.startTypes = startTypes; } public void clearServices() { includes.clear(); } public void clearStartBundles() { start.clear(); } public void add(Bundle...bundles) { add(Arrays.asList(bundles)); } public void add(Collection<? extends Bundle> bundles) { includes.addAll(bundles); } public void addStart(Bundle...bundles) { add(bundles); addStart(Arrays.asList(bundles)); } public void addStart(Collection<? extends Bundle> bundles) { add(bundles); start.addAll(bundles); } /** * Only good for Apache Felix - will need to modify if supporting * additional runtimes in the future... */ private void createConfig() { File configDir = createFolder(exportDir, "conf"); File system = new File(configDir, "system.properties"); StringBuilder sb = new StringBuilder(); sb.append(Mode.SYSTEM_PROPERTY).append("=").append(mode).append('\n'); switch(mode) { case DEV: sb.append(Logger.SYS_PROP_CONSOLE).append('=').append(Logger.DEBUG).append('\n'); sb.append(Logger.SYS_PROP_EMAIL).append('=').append(Logger.NEVER).append('\n'); sb.append(Logger.SYS_PROP_FILE).append('=').append(Logger.DEBUG); break; case TEST: sb.append(Logger.SYS_PROP_CONSOLE).append('=').append(Logger.DEBUG).append('\n'); sb.append(Logger.SYS_PROP_EMAIL).append('=').append(Logger.NEVER).append('\n'); sb.append(Logger.SYS_PROP_FILE).append('=').append(Logger.INFO); break; case PROD: sb.append(Logger.SYS_PROP_CONSOLE).append('=').append(Logger.TRACE).append('\n'); sb.append(Logger.SYS_PROP_EMAIL).append('=').append(Logger.NEVER).append('\n'); sb.append(Logger.SYS_PROP_FILE).append('=').append(Logger.INFO); break; } writeFile(system, sb.toString()); File config = new File(configDir, "config.properties"); List<Bundle> installed = new ArrayList<Bundle>(); List<Bundle> started1 = new ArrayList<Bundle>(); List<Bundle> started2 = new ArrayList<Bundle>(); for(Bundle bundle : exportedBundles) { if(!bundle.isFramework()) { - if(bundle.name.equals("org.oobium.logging")) { + if(bundle.name.equals("org.oobium.logging") || bundle.name.equals("org.apache.felix.log")) { started1.add(bundle); } else if(exportedStart.contains(bundle)) { started2.add(bundle); } else { installed.add(bundle); } } } sb = new StringBuilder(); sb.append("felix.auto.install.1="); for(Bundle bundle : installed) { sb.append(" \\\n file:bundles/").append(bundle.file.getName()); } sb.append("\n\nfelix.auto.start.1="); for(Bundle bundle : started1) { sb.append(" \\\n file:bundles/").append(bundle.file.getName()); } sb.append("\n\nfelix.auto.start.2="); for(Bundle bundle : started2) { sb.append(" \\\n file:bundles/").append(bundle.file.getName()); } sb.append("\n\norg.osgi.framework.startlevel.beginning=2"); writeFile(config, sb.toString()); } private void createScripts() { File startScript = new File(exportDir, "start.sh"); if(startScript.exists()) { logger.info("skipping start script"); } else { logger.info("writing start script"); writeFile(startScript, START_SCRIPT, EXECUTABLE); } File stopScript = new File(exportDir, "stop.sh"); if(stopScript.exists()) { logger.info("skipping stop script"); } else { logger.info("writing stop script"); writeFile(stopScript, STOP_SCRIPT, EXECUTABLE); } } private Bundle doExport(Bundle bundle) throws IOException { File jar; if(bundle.isJar) { jar = "felix.jar".equals(bundle.file.getName()) ? new File(binDir, bundle.file.getName()) : new File(bundleDir, bundle.file.getName()); if(jar.exists()) { logger.info(" skipping " + bundle); } else { logger.info(" copying " + bundle); copy(bundle.file, jar); } } else { Date date = new Date(FileUtils.getLastModified(bundle.bin)); Version version = bundle.version.resolve(date); jar = new File(bundleDir, bundle.name + "_" + version + ".jar"); if(jar.exists()) { logger.info(" skipping " + bundle); } else { logger.info(" creating " + bundle); bundle.createJar(jar, version); } } Bundle exportedBundle = Bundle.create(jar); if(start.contains(bundle)) { exportedStart.add(exportedBundle); } else { if((startTypes & APP) != 0 && exportedBundle.isApplication()) { exportedStart.add(exportedBundle); } if((startTypes & MODULE) != 0 && exportedBundle.isModule()) { exportedStart.add(exportedBundle); } if((startTypes & SERVICE) != 0 && exportedBundle.isService()) { exportedStart.add(exportedBundle); } if((startTypes & MIGRATION) != 0 && exportedBundle.isMigration()) { exportedStart.add(exportedBundle); } } exportedBundles.add(exportedBundle); return exportedBundle; } /** * Export the application, configured for the given mode. * @return a File object for the folder where the application was exported. * @throws IOException */ public File export() throws IOException { if(exportDir.exists()) { if(clean) { FileUtils.deleteContents(exportDir); } else if(cleanCache) { File felixCache = new File(exportDir, "felix-cache"); if(felixCache.exists()) { FileUtils.delete(felixCache); } } } else { exportDir.mkdirs(); } logger.info("determining required bundles"); Set<Bundle> bundles = new TreeSet<Bundle>(); for(Application application : applications) { if(!bundles.contains(application)) { bundles.addAll(application.getDependencies(workspace, mode)); bundles.add(application); } } for(Bundle bundle : includes) { if(!bundles.contains(bundle)) { bundles.addAll(bundle.getDependencies(workspace, mode)); bundles.add(bundle); } } workspace.setRuntimeBundle(OsgiRuntime.Felix, bundles); for(Bundle bundle : start) { if(!bundles.contains(bundle)) { throw new IllegalStateException("bundle is in the start list, but is not being exported: " + bundle); } } if(logger.isLoggingInfo()) { for(Bundle bundle : bundles) { logger.info(" " + bundle); } } logger.info("creating and copying bundles"); for(Bundle bundle : bundles) { doExport(bundle); } deleteContents(new File(exportDir, "configuration")); createConfig(); createScripts(); return exportDir; } /** * Export an individual bundle * @param mode * @param bundle * @return the exported Bundle (note that this bundle will not be available to Workspace.getBundle()) * @throws IOException */ public Bundle export(Bundle bundle) throws IOException { if(exportDir.exists()) { if(clean) { FileUtils.deleteContents(exportDir); } else if(cleanCache) { File felixCache = new File(exportDir, "felix-cache"); if(felixCache.exists()) { FileUtils.delete(felixCache); } } } else { exportDir.mkdirs(); } return doExport(bundle); } private void exportMigration(Application application, Mode mode) throws IOException { Migrator migration = workspace.getMigratorFor(application); if(migration != null) { if(!workspace.getWorkingDirectory().exists()) { workspace.getWorkingDirectory().mkdirs(); } // make sure that the schema files have been copied to the bin directory logger.info("determining required bundles"); Set<Bundle> bundles = migration.getDependencies(workspace, mode); bundles.add(migration); workspace.removeRuntimeBundle(bundles); // export only those bundles directly related to the migration bundles.remove(application); bundles.removeAll(application.getDependencies(workspace, mode)); if(logger.isLoggingInfo()) { for(Bundle bundle : bundles) { logger.info(" " + bundle); } } logger.info("creating and copying bundles"); for(Bundle bundle : bundles) { doExport(bundle); } } } /** * Export all migrations for this application and the dependencies * configured for the given mode. * @param mode * @return a list of bundles that have been exported during this operation. Note that these * are only bundles related to the migration; bundles for the application export are not * exported during this operation, nor are they returned with this list. * @throws IOException */ public Set<Bundle> exportMigration(Mode mode) throws IOException { for(Application application : applications) { exportMigration(application, mode); } return exportedBundles; } public boolean getClean() { return clean; } public boolean getCleanCache() { return cleanCache; } public File getExportDir() { return exportDir; } public File getExportedJar(Bundle bundle) { if(!exportDir.exists()) { return null; } if("felix.jar".equals(bundle.file.getName())) { File exported = new File(exportDir + File.separator + "bin" + File.separator + "felix.jar"); return exported.exists() ? exported : null; } else { File bundleDir = new File(exportDir + File.separator + "bundles"); final String bundleName = bundle.file.getName() + "_"; File[] exportedBundles = bundleDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(bundleName) && name.endsWith(".jar"); } }); if(exportedBundles != null && exportedBundles.length > 0) { File exported = exportedBundles[0]; for(int i = 1; i < exportedBundles.length; i++) { if(exported.getName().compareTo(exportedBundles[i].getName()) < 0) { exported = exportedBundles[i]; } } return exported; } return null; } } public Mode getMode() { return mode; } public void setClean(boolean clean) { this.clean = clean; } public void setCleanCache(boolean cleanCache) { this.cleanCache = cleanCache; } public void setMode(Mode mode) { this.mode = mode; } }
true
true
private void createConfig() { File configDir = createFolder(exportDir, "conf"); File system = new File(configDir, "system.properties"); StringBuilder sb = new StringBuilder(); sb.append(Mode.SYSTEM_PROPERTY).append("=").append(mode).append('\n'); switch(mode) { case DEV: sb.append(Logger.SYS_PROP_CONSOLE).append('=').append(Logger.DEBUG).append('\n'); sb.append(Logger.SYS_PROP_EMAIL).append('=').append(Logger.NEVER).append('\n'); sb.append(Logger.SYS_PROP_FILE).append('=').append(Logger.DEBUG); break; case TEST: sb.append(Logger.SYS_PROP_CONSOLE).append('=').append(Logger.DEBUG).append('\n'); sb.append(Logger.SYS_PROP_EMAIL).append('=').append(Logger.NEVER).append('\n'); sb.append(Logger.SYS_PROP_FILE).append('=').append(Logger.INFO); break; case PROD: sb.append(Logger.SYS_PROP_CONSOLE).append('=').append(Logger.TRACE).append('\n'); sb.append(Logger.SYS_PROP_EMAIL).append('=').append(Logger.NEVER).append('\n'); sb.append(Logger.SYS_PROP_FILE).append('=').append(Logger.INFO); break; } writeFile(system, sb.toString()); File config = new File(configDir, "config.properties"); List<Bundle> installed = new ArrayList<Bundle>(); List<Bundle> started1 = new ArrayList<Bundle>(); List<Bundle> started2 = new ArrayList<Bundle>(); for(Bundle bundle : exportedBundles) { if(!bundle.isFramework()) { if(bundle.name.equals("org.oobium.logging")) { started1.add(bundle); } else if(exportedStart.contains(bundle)) { started2.add(bundle); } else { installed.add(bundle); } } } sb = new StringBuilder(); sb.append("felix.auto.install.1="); for(Bundle bundle : installed) { sb.append(" \\\n file:bundles/").append(bundle.file.getName()); } sb.append("\n\nfelix.auto.start.1="); for(Bundle bundle : started1) { sb.append(" \\\n file:bundles/").append(bundle.file.getName()); } sb.append("\n\nfelix.auto.start.2="); for(Bundle bundle : started2) { sb.append(" \\\n file:bundles/").append(bundle.file.getName()); } sb.append("\n\norg.osgi.framework.startlevel.beginning=2"); writeFile(config, sb.toString()); }
private void createConfig() { File configDir = createFolder(exportDir, "conf"); File system = new File(configDir, "system.properties"); StringBuilder sb = new StringBuilder(); sb.append(Mode.SYSTEM_PROPERTY).append("=").append(mode).append('\n'); switch(mode) { case DEV: sb.append(Logger.SYS_PROP_CONSOLE).append('=').append(Logger.DEBUG).append('\n'); sb.append(Logger.SYS_PROP_EMAIL).append('=').append(Logger.NEVER).append('\n'); sb.append(Logger.SYS_PROP_FILE).append('=').append(Logger.DEBUG); break; case TEST: sb.append(Logger.SYS_PROP_CONSOLE).append('=').append(Logger.DEBUG).append('\n'); sb.append(Logger.SYS_PROP_EMAIL).append('=').append(Logger.NEVER).append('\n'); sb.append(Logger.SYS_PROP_FILE).append('=').append(Logger.INFO); break; case PROD: sb.append(Logger.SYS_PROP_CONSOLE).append('=').append(Logger.TRACE).append('\n'); sb.append(Logger.SYS_PROP_EMAIL).append('=').append(Logger.NEVER).append('\n'); sb.append(Logger.SYS_PROP_FILE).append('=').append(Logger.INFO); break; } writeFile(system, sb.toString()); File config = new File(configDir, "config.properties"); List<Bundle> installed = new ArrayList<Bundle>(); List<Bundle> started1 = new ArrayList<Bundle>(); List<Bundle> started2 = new ArrayList<Bundle>(); for(Bundle bundle : exportedBundles) { if(!bundle.isFramework()) { if(bundle.name.equals("org.oobium.logging") || bundle.name.equals("org.apache.felix.log")) { started1.add(bundle); } else if(exportedStart.contains(bundle)) { started2.add(bundle); } else { installed.add(bundle); } } } sb = new StringBuilder(); sb.append("felix.auto.install.1="); for(Bundle bundle : installed) { sb.append(" \\\n file:bundles/").append(bundle.file.getName()); } sb.append("\n\nfelix.auto.start.1="); for(Bundle bundle : started1) { sb.append(" \\\n file:bundles/").append(bundle.file.getName()); } sb.append("\n\nfelix.auto.start.2="); for(Bundle bundle : started2) { sb.append(" \\\n file:bundles/").append(bundle.file.getName()); } sb.append("\n\norg.osgi.framework.startlevel.beginning=2"); writeFile(config, sb.toString()); }
diff --git a/deployables/serviceengines/servicemix-camel/src/main/java/org/apache/servicemix/camel/JbiMessage.java b/deployables/serviceengines/servicemix-camel/src/main/java/org/apache/servicemix/camel/JbiMessage.java index 60f2fc96d..d07074b18 100644 --- a/deployables/serviceengines/servicemix-camel/src/main/java/org/apache/servicemix/camel/JbiMessage.java +++ b/deployables/serviceengines/servicemix-camel/src/main/java/org/apache/servicemix/camel/JbiMessage.java @@ -1,121 +1,122 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicemix.camel; import java.util.Iterator; import java.util.Map; import javax.jbi.messaging.MessagingException; import javax.jbi.messaging.NormalizedMessage; import javax.xml.transform.Source; import org.apache.camel.impl.DefaultMessage; /** * A JBI {@link org.apache.camel.Message} which provides access to the underlying JBI features * such as {@link #getNormalizedMessage()} * * @version $Revision: 563665 $ */ public class JbiMessage extends DefaultMessage { private NormalizedMessage normalizedMessage; public JbiMessage() { } public JbiMessage(NormalizedMessage normalizedMessage) { this.normalizedMessage = normalizedMessage; } @Override public String toString() { if (normalizedMessage != null) { return "JbiMessage: " + normalizedMessage; } else { return "JbiMessage: " + getBody(); } } @Override public JbiExchange getExchange() { return (JbiExchange) super.getExchange(); } /** * Returns the underlying JBI message * * @return the underlying JBI message */ public NormalizedMessage getNormalizedMessage() { return normalizedMessage; } public void setNormalizedMessage(NormalizedMessage normalizedMessage) { this.normalizedMessage = normalizedMessage; } @Override public Object getHeader(String name) { Object answer = null; if (normalizedMessage != null) { answer = normalizedMessage.getProperty(name); } if (answer == null) { answer = super.getHeader(name); } return answer; } @Override public JbiMessage newInstance() { return new JbiMessage(); } @Override protected Object createBody() { if (normalizedMessage != null) { return getExchange().getBinding().extractBodyFromJbi(getExchange(), normalizedMessage); } return null; } @Override protected void populateInitialHeaders(Map<String, Object> map) { if (normalizedMessage != null) { Iterator iter = normalizedMessage.getPropertyNames().iterator(); while (iter.hasNext()) { String name = iter.next().toString(); Object value = normalizedMessage.getProperty(name); map.put(name, value); } } } // @Override public void setBody(Object body) { if (normalizedMessage != null) { if (!(body instanceof Source)) { body = getExchange().getBinding().convertBodyToJbi(getExchange(), body); } try { normalizedMessage.setContent((Source) body); } catch (MessagingException e) { throw new JbiException(e); } } + super.setBody(body); } }
true
true
public void setBody(Object body) { if (normalizedMessage != null) { if (!(body instanceof Source)) { body = getExchange().getBinding().convertBodyToJbi(getExchange(), body); } try { normalizedMessage.setContent((Source) body); } catch (MessagingException e) { throw new JbiException(e); } } }
public void setBody(Object body) { if (normalizedMessage != null) { if (!(body instanceof Source)) { body = getExchange().getBinding().convertBodyToJbi(getExchange(), body); } try { normalizedMessage.setContent((Source) body); } catch (MessagingException e) { throw new JbiException(e); } } super.setBody(body); }
diff --git a/astrid/src/com/todoroo/astrid/widget/TasksWidget.java b/astrid/src/com/todoroo/astrid/widget/TasksWidget.java index c0d274f9a..4c286860f 100644 --- a/astrid/src/com/todoroo/astrid/widget/TasksWidget.java +++ b/astrid/src/com/todoroo/astrid/widget/TasksWidget.java @@ -1,144 +1,146 @@ package com.todoroo.astrid.widget; import android.app.PendingIntent; import android.app.Service; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.IBinder; import android.util.Log; import android.view.View; import android.widget.RemoteViews; import com.timsu.astrid.R; import com.todoroo.andlib.data.TodorooCursor; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.astrid.activity.TaskEditActivity; import com.todoroo.astrid.activity.TaskListActivity; import com.todoroo.astrid.api.Filter; import com.todoroo.astrid.core.CoreFilterExposer; import com.todoroo.astrid.dao.Database; import com.todoroo.astrid.model.Task; import com.todoroo.astrid.service.AstridDependencyInjector; import com.todoroo.astrid.service.TaskService; public class TasksWidget extends AppWidgetProvider { static { AstridDependencyInjector.initialize(); } public final static int[] TEXT_IDS = { R.id.task_1, R.id.task_2, R.id.task_3, R.id.task_4, R.id.task_5 }; public final static int[] SEPARATOR_IDS = { R.id.separator_1, R.id.separator_2, R.id.separator_3, R.id.separator_4 }; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { try { super.onUpdate(context, appWidgetManager, appWidgetIds); // Start in service to prevent Application Not Responding timeout context.startService(new Intent(context, UpdateService.class)); } catch (SecurityException e) { // :( } } public static class UpdateService extends Service { @Autowired Database database; @Autowired TaskService taskService; @Override public void onStart(Intent intent, int startId) { ContextManager.setContext(this); RemoteViews updateViews = buildUpdate(this); ComponentName thisWidget = new ComponentName(this, TasksWidget.class); AppWidgetManager manager = AppWidgetManager.getInstance(this); manager.updateAppWidget(thisWidget, updateViews); } @Override public IBinder onBind(Intent intent) { return null; } @SuppressWarnings("nls") public RemoteViews buildUpdate(Context context) { DependencyInjectionService.getInstance().inject(this); RemoteViews views = null; views = new RemoteViews(context.getPackageName(), R.layout.widget_initialized); int[] textIDs = TEXT_IDS; int[] separatorIDs = SEPARATOR_IDS; int numberOfTasks = 5; Intent listIntent = new Intent(context, TaskListActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, listIntent, 0); views.setOnClickPendingIntent(R.id.taskbody, pendingIntent); TodorooCursor<Task> cursor = null; try { Filter inboxFilter = CoreFilterExposer.buildInboxFilter(getResources()); inboxFilter.sqlQuery += "ORDER BY " + TaskService.defaultTaskOrder() + " LIMIT " + numberOfTasks; database.openForReading(); cursor = taskService.fetchFiltered(inboxFilter, null, Task.TITLE, Task.DUE_DATE); Task task = new Task(); for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); task.readFromCursor(cursor); String textContent = ""; int textColor = Color.WHITE; textContent = task.getValue(Task.TITLE); if(task.hasDueDate() && task.getValue(Task.DUE_DATE) < DateUtilities.now()) textColor = context.getResources().getColor(R.color.task_list_overdue); if(i > 0) views.setViewVisibility(separatorIDs[i-1], View.VISIBLE); views.setTextViewText(textIDs[i], textContent); views.setTextColor(textIDs[i], textColor); } for(int i = cursor.getCount() - 1; i < separatorIDs.length; i++) { if(i >= 0) views.setViewVisibility(separatorIDs[i], View.INVISIBLE); + if(i > cursor.getCount() - 1) + views.setViewVisibility(textIDs[i], View.INVISIBLE); } } catch (Exception e) { // can happen if database is not ready Log.e("WIDGET-UPDATE", "Error updating widget", e); } finally { if(cursor != null) cursor.close(); } Intent editIntent = new Intent(context, TaskEditActivity.class); pendingIntent = PendingIntent.getActivity(context, 0, editIntent, 0); views.setOnClickPendingIntent(R.id.widget_button, pendingIntent); return views; } } }
true
true
public RemoteViews buildUpdate(Context context) { DependencyInjectionService.getInstance().inject(this); RemoteViews views = null; views = new RemoteViews(context.getPackageName(), R.layout.widget_initialized); int[] textIDs = TEXT_IDS; int[] separatorIDs = SEPARATOR_IDS; int numberOfTasks = 5; Intent listIntent = new Intent(context, TaskListActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, listIntent, 0); views.setOnClickPendingIntent(R.id.taskbody, pendingIntent); TodorooCursor<Task> cursor = null; try { Filter inboxFilter = CoreFilterExposer.buildInboxFilter(getResources()); inboxFilter.sqlQuery += "ORDER BY " + TaskService.defaultTaskOrder() + " LIMIT " + numberOfTasks; database.openForReading(); cursor = taskService.fetchFiltered(inboxFilter, null, Task.TITLE, Task.DUE_DATE); Task task = new Task(); for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); task.readFromCursor(cursor); String textContent = ""; int textColor = Color.WHITE; textContent = task.getValue(Task.TITLE); if(task.hasDueDate() && task.getValue(Task.DUE_DATE) < DateUtilities.now()) textColor = context.getResources().getColor(R.color.task_list_overdue); if(i > 0) views.setViewVisibility(separatorIDs[i-1], View.VISIBLE); views.setTextViewText(textIDs[i], textContent); views.setTextColor(textIDs[i], textColor); } for(int i = cursor.getCount() - 1; i < separatorIDs.length; i++) { if(i >= 0) views.setViewVisibility(separatorIDs[i], View.INVISIBLE); } } catch (Exception e) { // can happen if database is not ready Log.e("WIDGET-UPDATE", "Error updating widget", e); } finally { if(cursor != null) cursor.close(); } Intent editIntent = new Intent(context, TaskEditActivity.class); pendingIntent = PendingIntent.getActivity(context, 0, editIntent, 0); views.setOnClickPendingIntent(R.id.widget_button, pendingIntent); return views; }
public RemoteViews buildUpdate(Context context) { DependencyInjectionService.getInstance().inject(this); RemoteViews views = null; views = new RemoteViews(context.getPackageName(), R.layout.widget_initialized); int[] textIDs = TEXT_IDS; int[] separatorIDs = SEPARATOR_IDS; int numberOfTasks = 5; Intent listIntent = new Intent(context, TaskListActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, listIntent, 0); views.setOnClickPendingIntent(R.id.taskbody, pendingIntent); TodorooCursor<Task> cursor = null; try { Filter inboxFilter = CoreFilterExposer.buildInboxFilter(getResources()); inboxFilter.sqlQuery += "ORDER BY " + TaskService.defaultTaskOrder() + " LIMIT " + numberOfTasks; database.openForReading(); cursor = taskService.fetchFiltered(inboxFilter, null, Task.TITLE, Task.DUE_DATE); Task task = new Task(); for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); task.readFromCursor(cursor); String textContent = ""; int textColor = Color.WHITE; textContent = task.getValue(Task.TITLE); if(task.hasDueDate() && task.getValue(Task.DUE_DATE) < DateUtilities.now()) textColor = context.getResources().getColor(R.color.task_list_overdue); if(i > 0) views.setViewVisibility(separatorIDs[i-1], View.VISIBLE); views.setTextViewText(textIDs[i], textContent); views.setTextColor(textIDs[i], textColor); } for(int i = cursor.getCount() - 1; i < separatorIDs.length; i++) { if(i >= 0) views.setViewVisibility(separatorIDs[i], View.INVISIBLE); if(i > cursor.getCount() - 1) views.setViewVisibility(textIDs[i], View.INVISIBLE); } } catch (Exception e) { // can happen if database is not ready Log.e("WIDGET-UPDATE", "Error updating widget", e); } finally { if(cursor != null) cursor.close(); } Intent editIntent = new Intent(context, TaskEditActivity.class); pendingIntent = PendingIntent.getActivity(context, 0, editIntent, 0); views.setOnClickPendingIntent(R.id.widget_button, pendingIntent); return views; }
diff --git a/src/org/apache/xpath/objects/XObject.java b/src/org/apache/xpath/objects/XObject.java index 498fe5fb..f30c8670 100644 --- a/src/org/apache/xpath/objects/XObject.java +++ b/src/org/apache/xpath/objects/XObject.java @@ -1,841 +1,843 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xpath.objects; import org.w3c.dom.DocumentFragment; //import org.w3c.dom.Text; //import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.traversal.NodeIterator; import org.apache.xml.dtm.*; import java.io.Serializable; import org.apache.xpath.res.XPATHErrorResources; import org.apache.xpath.XPathContext; import org.apache.xpath.NodeSetDTM; import org.apache.xpath.XPathException; import org.apache.xalan.res.XSLMessages; import org.apache.xpath.Expression; import org.apache.xml.utils.XMLString; import org.apache.xpath.axes.OneStepIterator; import org.apache.xpath.axes.DescendantIterator; /** * <meta name="usage" content="general"/> * This class represents an XPath object, and is capable of * converting the object to various types, such as a string. * This class acts as the base class to other XPath type objects, * such as XString, and provides polymorphic casting capabilities. */ public class XObject extends Expression implements Serializable, Cloneable { /** * The java object which this object wraps. * @serial */ protected Object m_obj; // This may be NULL!!! /** * Create an XObject. */ public XObject(){} /** * Create an XObject. * * @param obj Can be any object, should be a specific type * for derived classes, or null. */ public XObject(Object obj) { m_obj = obj; } /** * For support of literal objects in xpaths. * * @param xctxt The XPath execution context. * * @return This object. * * @throws javax.xml.transform.TransformerException */ public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException { return this; } /** * Specify if it's OK for detach to release the iterator for reuse. * * @param allowRelease true if it is OK for detach to release this iterator * for pooling. */ public void allowDetachToRelease(boolean allowRelease){} /** * Detaches the <code>DTMIterator</code> from the set which it iterated * over, releasing any computational resources and placing the iterator * in the INVALID state. After <code>detach</code> has been invoked, * calls to <code>nextNode</code> or <code>previousNode</code> will * raise a runtime exception. */ public void detach(){} /** * Forces the object to release it's resources. This is more harsh than * detach(). */ public void destruct() { if (null != m_obj) { allowDetachToRelease(true); detach(); m_obj = null; } } /** * Directly call the * characters method on the passed ContentHandler for the * string-value. Multiple calls to the * ContentHandler's characters methods may well occur for a single call to * this method. * * @param ch A non-null reference to a ContentHandler. * * @throws org.xml.sax.SAXException */ public void dispatchCharactersEvents(org.xml.sax.ContentHandler ch) throws org.xml.sax.SAXException { xstr().dispatchCharactersEvents(ch); } /** * Create the right XObject based on the type of the object passed. This * function can not make an XObject that exposes DOM Nodes, NodeLists, and * NodeIterators to the XSLT stylesheet as node-sets. * * @param val The java object which this object will wrap. * * @return the right XObject based on the type of the object passed. */ static public XObject create(Object val) { XObject result; if (val instanceof XObject) { result = (XObject) val; } else if (val instanceof String) { result = new XString((String) val); } else if (val instanceof Boolean) { result = new XBoolean((Boolean)val); } else if (val instanceof Double) { result = new XNumber(((Double) val)); } else { result = new XObject(val); } return result; } /** * Create the right XObject based on the type of the object passed. * This function <emph>can</emph> make an XObject that exposes DOM Nodes, NodeLists, and * NodeIterators to the XSLT stylesheet as node-sets. * * @param val The java object which this object will wrap. * @param xctxt The XPath context. * * @return the right XObject based on the type of the object passed. */ static public XObject create(Object val, XPathContext xctxt) { XObject result; if (val instanceof XObject) { result = (XObject) val; } else if (val instanceof String) { result = new XString((String) val); } else if (val instanceof Boolean) { result = new XBoolean((Boolean)val); } else if (val instanceof Number) { result = new XNumber(((Number) val)); } else if (val instanceof DTM) { DTM dtm = (DTM)val; try { int dtmRoot = dtm.getDocument(); DTMAxisIterator iter = dtm.getAxisIterator(Axis.SELF); iter.setStartNode(dtmRoot); DTMIterator iterator = new OneStepIterator(iter); + iterator.setRoot(dtmRoot, xctxt); result = new XNodeSet(iterator); } catch(Exception ex) { throw new org.apache.xml.utils.WrappedRuntimeException(ex); } } else if (val instanceof DTMAxisIterator) { DTMAxisIterator iter = (DTMAxisIterator)val; try { - DTMIterator iterator = new OneStepIterator(iter); - result = new XNodeSet(iterator); - } + DTMIterator iterator = new OneStepIterator(iter); + iterator.setRoot(iter.getStartNode(), xctxt); + result = new XNodeSet(iterator); + } catch(Exception ex) { throw new org.apache.xml.utils.WrappedRuntimeException(ex); } } else if (val instanceof DTMIterator) { result = new XNodeSet((DTMIterator) val); } // This next three instanceofs are a little worrysome, since a NodeList // might also implement a Node! else if (val instanceof org.w3c.dom.Node) { result = new XNodeSetForDOM((org.w3c.dom.Node)val, xctxt); } // This must come after org.w3c.dom.Node, since many Node implementations // also implement NodeList. else if (val instanceof org.w3c.dom.NodeList) { result = new XNodeSetForDOM((org.w3c.dom.NodeList)val, xctxt); } else if (val instanceof org.w3c.dom.traversal.NodeIterator) { result = new XNodeSetForDOM((org.w3c.dom.traversal.NodeIterator)val, xctxt); } else { result = new XObject(val); } return result; } /** Constant for NULL object type */ public static final int CLASS_NULL = -1; /** Constant for UNKNOWN object type */ public static final int CLASS_UNKNOWN = 0; /** Constant for BOOLEAN object type */ public static final int CLASS_BOOLEAN = 1; /** Constant for NUMBER object type */ public static final int CLASS_NUMBER = 2; /** Constant for STRING object type */ public static final int CLASS_STRING = 3; /** Constant for NODESET object type */ public static final int CLASS_NODESET = 4; /** Constant for RESULT TREE FRAGMENT object type */ public static final int CLASS_RTREEFRAG = 5; /** Represents an unresolved variable type as an integer. */ public static final int CLASS_UNRESOLVEDVARIABLE = 600; /** * Tell what kind of class this is. * * @return CLASS_UNKNOWN */ public int getType() { return CLASS_UNKNOWN; } /** * Given a request type, return the equivalent string. * For diagnostic purposes. * * @return type string "#UNKNOWN" + object class name */ public String getTypeString() { return "#UNKNOWN (" + object().getClass().getName() + ")"; } /** * Cast result object to a number. Always issues an error. * * @return 0.0 * * @throws javax.xml.transform.TransformerException */ public double num() throws javax.xml.transform.TransformerException { error(XPATHErrorResources.ER_CANT_CONVERT_TO_NUMBER, new Object[]{ getTypeString() }); //"Can not convert "+getTypeString()+" to a number"); return 0.0; } /** * Cast result object to a number, but allow side effects, such as the * incrementing of an iterator. * * @return numeric value of the string conversion from the * next node in the NodeSetDTM, or NAN if no node was found */ public double numWithSideEffects() throws javax.xml.transform.TransformerException { return num(); } /** * Cast result object to a boolean. Always issues an error. * * @return false * * @throws javax.xml.transform.TransformerException */ public boolean bool() throws javax.xml.transform.TransformerException { error(XPATHErrorResources.ER_CANT_CONVERT_TO_NUMBER, new Object[]{ getTypeString() }); //"Can not convert "+getTypeString()+" to a number"); return false; } /** * Cast result object to a boolean, but allow side effects, such as the * incrementing of an iterator. * * @return True if there is a next node in the nodeset */ public boolean boolWithSideEffects() throws javax.xml.transform.TransformerException { return bool(); } /** * Cast result object to a string. * * @return The string this wraps or the empty string if null */ public XMLString xstr() { return XMLStringFactoryImpl.getFactory().newstr(str()); } /** * Cast result object to a string. * * @return The object as a string */ public String str() { return (m_obj != null) ? m_obj.toString() : ""; } /** * Return the string representation of the object * * * @return the string representation of the object */ public String toString() { return str(); } /** * Cast result object to a result tree fragment. * * @param support XPath context to use for the conversion * * @return the objec as a result tree fragment. */ public int rtf(XPathContext support) { int result = rtf(); if (DTM.NULL == result) { DTM frag = support.createDocumentFragment(); // %OPT% frag.appendTextChild(str()); result = frag.getDocument(); } return result; } /** * Cast result object to a result tree fragment. * * @param support XPath context to use for the conversion * * @return the objec as a result tree fragment. */ public DocumentFragment rtree(XPathContext support) { DocumentFragment docFrag = null; int result = rtf(); if (DTM.NULL == result) { DTM frag = support.createDocumentFragment(); // %OPT% frag.appendTextChild(str()); docFrag = (DocumentFragment)frag.getNode(frag.getDocument()); } else { DTM frag = support.getDTM(result); docFrag = (DocumentFragment)frag.getNode(frag.getDocument()); } return docFrag; } /** * For functions to override. * * @return null */ public DocumentFragment rtree() { return null; } /** * For functions to override. * * @return null */ public int rtf() { return DTM.NULL; } /** * Return a java object that's closest to the representation * that should be handed to an extension. * * @return The object that this class wraps */ public Object object() { return m_obj; } /** * Cast result object to a nodelist. Always issues an error. * * @return null * * @throws javax.xml.transform.TransformerException */ public DTMIterator iter() throws javax.xml.transform.TransformerException { error(XPATHErrorResources.ER_CANT_CONVERT_TO_NODELIST, new Object[]{ getTypeString() }); //"Can not convert "+getTypeString()+" to a NodeList!"); return null; } /** * Cast result object to a nodelist. Always issues an error. * * @return null * * @throws javax.xml.transform.TransformerException */ public NodeIterator nodeset() throws javax.xml.transform.TransformerException { error(XPATHErrorResources.ER_CANT_CONVERT_TO_NODELIST, new Object[]{ getTypeString() }); //"Can not convert "+getTypeString()+" to a NodeList!"); return null; } /** * Cast result object to a nodelist. Always issues an error. * * @return null * * @throws javax.xml.transform.TransformerException */ public NodeList nodelist() throws javax.xml.transform.TransformerException { error(XPATHErrorResources.ER_CANT_CONVERT_TO_NODELIST, new Object[]{ getTypeString() }); //"Can not convert "+getTypeString()+" to a NodeList!"); return null; } /** * Cast result object to a nodelist. Always issues an error. * * @return The object as a NodeSetDTM. * * @throws javax.xml.transform.TransformerException */ public NodeSetDTM mutableNodeset() throws javax.xml.transform.TransformerException { error(XPATHErrorResources.ER_CANT_CONVERT_TO_MUTABLENODELIST, new Object[]{ getTypeString() }); //"Can not convert "+getTypeString()+" to a NodeSetDTM!"); return (NodeSetDTM) m_obj; } /** * Cast object to type t. * * @param t Type of object to cast this to * @param support XPath context to use for the conversion * * @return This object as the given type t * * @throws javax.xml.transform.TransformerException */ public Object castToType(int t, XPathContext support) throws javax.xml.transform.TransformerException { Object result; switch (t) { case CLASS_STRING : result = str(); break; case CLASS_NUMBER : result = new Double(num()); break; case CLASS_NODESET : result = iter(); break; case CLASS_BOOLEAN : result = new Boolean(bool()); break; case CLASS_UNKNOWN : result = m_obj; break; // %TBD% What to do here? // case CLASS_RTREEFRAG : // result = rtree(support); // break; default : error(XPATHErrorResources.ER_CANT_CONVERT_TO_TYPE, new Object[]{ getTypeString(), Integer.toString(t) }); //"Can not convert "+getTypeString()+" to a type#"+t); result = null; } return result; } /** * Tell if one object is less than the other. * * @param obj2 Object to compare this to * * @return True if this object is less than the given object * * @throws javax.xml.transform.TransformerException */ public boolean lessThan(XObject obj2) throws javax.xml.transform.TransformerException { // In order to handle the 'all' semantics of // nodeset comparisons, we always call the // nodeset function. Because the arguments // are backwards, we call the opposite comparison // function. if (obj2.getType() == XObject.CLASS_NODESET) return obj2.greaterThan(this); return this.num() < obj2.num(); } /** * Tell if one object is less than or equal to the other. * * @param obj2 Object to compare this to * * @return True if this object is less than or equal to the given object * * @throws javax.xml.transform.TransformerException */ public boolean lessThanOrEqual(XObject obj2) throws javax.xml.transform.TransformerException { // In order to handle the 'all' semantics of // nodeset comparisons, we always call the // nodeset function. Because the arguments // are backwards, we call the opposite comparison // function. if (obj2.getType() == XObject.CLASS_NODESET) return obj2.greaterThanOrEqual(this); return this.num() <= obj2.num(); } /** * Tell if one object is greater than the other. * * @param obj2 Object to compare this to * * @return True if this object is greater than the given object * * @throws javax.xml.transform.TransformerException */ public boolean greaterThan(XObject obj2) throws javax.xml.transform.TransformerException { // In order to handle the 'all' semantics of // nodeset comparisons, we always call the // nodeset function. Because the arguments // are backwards, we call the opposite comparison // function. if (obj2.getType() == XObject.CLASS_NODESET) return obj2.lessThan(this); return this.num() > obj2.num(); } /** * Tell if one object is greater than or equal to the other. * * @param obj2 Object to compare this to * * @return True if this object is greater than or equal to the given object * * @throws javax.xml.transform.TransformerException */ public boolean greaterThanOrEqual(XObject obj2) throws javax.xml.transform.TransformerException { // In order to handle the 'all' semantics of // nodeset comparisons, we always call the // nodeset function. Because the arguments // are backwards, we call the opposite comparison // function. if (obj2.getType() == XObject.CLASS_NODESET) return obj2.lessThanOrEqual(this); return this.num() >= obj2.num(); } /** * Tell if two objects are functionally equal. * * @param obj2 Object to compare this to * * @return True if this object is equal to the given object * * @throws javax.xml.transform.TransformerException */ public boolean equals(XObject obj2) { // In order to handle the 'all' semantics of // nodeset comparisons, we always call the // nodeset function. if (obj2.getType() == XObject.CLASS_NODESET) return obj2.equals(this); if (null != m_obj) { return m_obj.equals(obj2.m_obj); } else { return obj2.m_obj == null; } } /** * Tell if two objects are functionally not equal. * * @param obj2 Object to compare this to * * @return True if this object is not equal to the given object * * @throws javax.xml.transform.TransformerException */ public boolean notEquals(XObject obj2) throws javax.xml.transform.TransformerException { // In order to handle the 'all' semantics of // nodeset comparisons, we always call the // nodeset function. if (obj2.getType() == XObject.CLASS_NODESET) return obj2.notEquals(this); return !equals(obj2); } /** * Tell the user of an error, and probably throw an * exception. * * @param msg Error message to issue * * @throws javax.xml.transform.TransformerException */ protected void error(int msg) throws javax.xml.transform.TransformerException { error(msg, null); } /** * Tell the user of an error, and probably throw an * exception. * * @param msg Error message to issue * @param args Arguments to use in the message * * @throws javax.xml.transform.TransformerException */ protected void error(int msg, Object[] args) throws javax.xml.transform.TransformerException { String fmsg = XSLMessages.createXPATHMessage(msg, args); // boolean shouldThrow = support.problem(m_support.XPATHPROCESSOR, // m_support.ERROR, // null, // null, fmsg, 0, 0); // if(shouldThrow) { throw new XPathException(fmsg); } } /** * XObjects should not normally need to fix up variables. */ public void fixupVariables(java.util.Vector vars, int globalsSize) { // no-op } /** * Cast result object to a string. * * * NEEDSDOC @param fsb * @return The string this wraps or the empty string if null */ public void appendToFsb(org.apache.xml.utils.FastStringBuffer fsb) { fsb.append(str()); } }
false
true
static public XObject create(Object val, XPathContext xctxt) { XObject result; if (val instanceof XObject) { result = (XObject) val; } else if (val instanceof String) { result = new XString((String) val); } else if (val instanceof Boolean) { result = new XBoolean((Boolean)val); } else if (val instanceof Number) { result = new XNumber(((Number) val)); } else if (val instanceof DTM) { DTM dtm = (DTM)val; try { int dtmRoot = dtm.getDocument(); DTMAxisIterator iter = dtm.getAxisIterator(Axis.SELF); iter.setStartNode(dtmRoot); DTMIterator iterator = new OneStepIterator(iter); result = new XNodeSet(iterator); } catch(Exception ex) { throw new org.apache.xml.utils.WrappedRuntimeException(ex); } } else if (val instanceof DTMAxisIterator) { DTMAxisIterator iter = (DTMAxisIterator)val; try { DTMIterator iterator = new OneStepIterator(iter); result = new XNodeSet(iterator); } catch(Exception ex) { throw new org.apache.xml.utils.WrappedRuntimeException(ex); } } else if (val instanceof DTMIterator) { result = new XNodeSet((DTMIterator) val); } // This next three instanceofs are a little worrysome, since a NodeList // might also implement a Node! else if (val instanceof org.w3c.dom.Node) { result = new XNodeSetForDOM((org.w3c.dom.Node)val, xctxt); } // This must come after org.w3c.dom.Node, since many Node implementations // also implement NodeList. else if (val instanceof org.w3c.dom.NodeList) { result = new XNodeSetForDOM((org.w3c.dom.NodeList)val, xctxt); } else if (val instanceof org.w3c.dom.traversal.NodeIterator) { result = new XNodeSetForDOM((org.w3c.dom.traversal.NodeIterator)val, xctxt); } else { result = new XObject(val); } return result; }
static public XObject create(Object val, XPathContext xctxt) { XObject result; if (val instanceof XObject) { result = (XObject) val; } else if (val instanceof String) { result = new XString((String) val); } else if (val instanceof Boolean) { result = new XBoolean((Boolean)val); } else if (val instanceof Number) { result = new XNumber(((Number) val)); } else if (val instanceof DTM) { DTM dtm = (DTM)val; try { int dtmRoot = dtm.getDocument(); DTMAxisIterator iter = dtm.getAxisIterator(Axis.SELF); iter.setStartNode(dtmRoot); DTMIterator iterator = new OneStepIterator(iter); iterator.setRoot(dtmRoot, xctxt); result = new XNodeSet(iterator); } catch(Exception ex) { throw new org.apache.xml.utils.WrappedRuntimeException(ex); } } else if (val instanceof DTMAxisIterator) { DTMAxisIterator iter = (DTMAxisIterator)val; try { DTMIterator iterator = new OneStepIterator(iter); iterator.setRoot(iter.getStartNode(), xctxt); result = new XNodeSet(iterator); } catch(Exception ex) { throw new org.apache.xml.utils.WrappedRuntimeException(ex); } } else if (val instanceof DTMIterator) { result = new XNodeSet((DTMIterator) val); } // This next three instanceofs are a little worrysome, since a NodeList // might also implement a Node! else if (val instanceof org.w3c.dom.Node) { result = new XNodeSetForDOM((org.w3c.dom.Node)val, xctxt); } // This must come after org.w3c.dom.Node, since many Node implementations // also implement NodeList. else if (val instanceof org.w3c.dom.NodeList) { result = new XNodeSetForDOM((org.w3c.dom.NodeList)val, xctxt); } else if (val instanceof org.w3c.dom.traversal.NodeIterator) { result = new XNodeSetForDOM((org.w3c.dom.traversal.NodeIterator)val, xctxt); } else { result = new XObject(val); } return result; }
diff --git a/src/com/android/camera/panorama/PanoramaActivity.java b/src/com/android/camera/panorama/PanoramaActivity.java index a65d2634..fe708273 100755 --- a/src/com/android/camera/panorama/PanoramaActivity.java +++ b/src/com/android/camera/panorama/PanoramaActivity.java @@ -1,1100 +1,1101 @@ /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera.panorama; import com.android.camera.ActivityBase; import com.android.camera.CameraDisabledException; import com.android.camera.CameraHardwareException; import com.android.camera.CameraHolder; import com.android.camera.Exif; import com.android.camera.MenuHelper; import com.android.camera.ModePicker; import com.android.camera.OnClickAttr; import com.android.camera.R; import com.android.camera.RotateDialogController; import com.android.camera.ShutterButton; import com.android.camera.SoundPlayer; import com.android.camera.Storage; import com.android.camera.Thumbnail; import com.android.camera.Util; import com.android.camera.ui.Rotatable; import com.android.camera.ui.RotateImageView; import com.android.camera.ui.RotateLayout; import com.android.camera.ui.SharePopup; import android.content.ContentResolver; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.ImageFormat; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.SurfaceTexture; import android.graphics.YuvImage; import android.hardware.Camera.Parameters; import android.hardware.Camera.Size; import android.hardware.Sensor; import android.hardware.SensorManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.ParcelFileDescriptor; import android.os.SystemProperties; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.OrientationEventListener; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.List; /** * Activity to handle panorama capturing. */ public class PanoramaActivity extends ActivityBase implements ModePicker.OnModeChangeListener, SurfaceTexture.OnFrameAvailableListener, ShutterButton.OnShutterButtonListener, MosaicRendererSurfaceViewRenderer.MosaicSurfaceCreateListener { public static final int DEFAULT_SWEEP_ANGLE = 160; public static final int DEFAULT_BLEND_MODE = Mosaic.BLENDTYPE_HORIZONTAL; public static final int DEFAULT_CAPTURE_PIXELS = 960 * 720; private static final int MSG_LOW_RES_FINAL_MOSAIC_READY = 1; private static final int MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL = 2; private static final int MSG_GENERATE_FINAL_MOSAIC_ERROR = 3; private static final int MSG_RESET_TO_PREVIEW = 4; private static final int MSG_CLEAR_SCREEN_DELAY = 5; private static final int SCREEN_DELAY = 2 * 60 * 1000; private static final String TAG = "PanoramaActivity"; private static final int PREVIEW_STOPPED = 0; private static final int PREVIEW_ACTIVE = 1; private static final int CAPTURE_STATE_VIEWFINDER = 0; private static final int CAPTURE_STATE_MOSAIC = 1; // Speed is in unit of deg/sec private static final float PANNING_SPEED_THRESHOLD = 20f; // Ratio of nanosecond to second private static final float NS2S = 1.0f / 1000000000.0f; private static final String VIDEO_RECORD_SOUND = "/system/media/audio/ui/VideoRecord.ogg"; private boolean mPausing; private View mPanoLayout; private View mCaptureLayout; private View mReviewLayout; private ImageView mReview; private RotateLayout mCaptureIndicator; private PanoProgressBar mPanoProgressBar; private PanoProgressBar mSavingProgressBar; private View mFastIndicationBorder; private View mLeftIndicator; private View mRightIndicator; private MosaicRendererSurfaceView mMosaicView; private TextView mTooFastPrompt; private ShutterButton mShutterButton; private Object mWaitObject = new Object(); private String mPreparePreviewString; private String mDialogTitle; private String mDialogOkString; private String mDialogPanoramaFailedString; private int mIndicatorColor; private int mIndicatorColorFast; private float mCompassValueX; private float mCompassValueY; private float mCompassValueXStart; private float mCompassValueYStart; private float mCompassValueXStartBuffer; private float mCompassValueYStartBuffer; private int mCompassThreshold; private int mTraversedAngleX; private int mTraversedAngleY; private long mTimestamp; // Control variables for the terminate condition. private int mMinAngleX; private int mMaxAngleX; private int mMinAngleY; private int mMaxAngleY; private RotateImageView mThumbnailView; private Thumbnail mThumbnail; private SharePopup mSharePopup; private int mPreviewWidth; private int mPreviewHeight; private int mCameraState; private int mCaptureState; private SensorManager mSensorManager; private Sensor mSensor; private ModePicker mModePicker; private MosaicFrameProcessor mMosaicFrameProcessor; private long mTimeTaken; private Handler mMainHandler; private SurfaceTexture mSurfaceTexture; private boolean mThreadRunning; private boolean mCancelComputation; private float[] mTransformMatrix; private float mHorizontalViewAngle; private SoundPlayer mRecordSound; // Prefer FOCUS_MODE_INFINITY to FOCUS_MODE_CONTINUOUS_VIDEO because of // getting a better image quality by the former. private String mTargetFocusMode = Parameters.FOCUS_MODE_INFINITY; private PanoOrientationEventListener mOrientationEventListener; // The value could be 0, 90, 180, 270 for the 4 different orientations measured in clockwise // respectively. private int mDeviceOrientation; private int mOrientationCompensation; private RotateDialogController mRotateDialog; private class MosaicJpeg { public MosaicJpeg(byte[] data, int width, int height) { this.data = data; this.width = width; this.height = height; this.isValid = true; } public MosaicJpeg() { this.data = null; this.width = 0; this.height = 0; this.isValid = false; } public final byte[] data; public final int width; public final int height; public final boolean isValid; } private class PanoOrientationEventListener extends OrientationEventListener { public PanoOrientationEventListener(Context context) { super(context); } @Override public void onOrientationChanged(int orientation) { // We keep the last known orientation. So if the user first orient // the camera then point the camera to floor or sky, we still have // the correct orientation. if (orientation == ORIENTATION_UNKNOWN) return; mDeviceOrientation = Util.roundOrientation(orientation, mDeviceOrientation); // When the screen is unlocked, display rotation may change. Always // calculate the up-to-date orientationCompensation. int orientationCompensation = mDeviceOrientation + Util.getDisplayRotation(PanoramaActivity.this); if (mOrientationCompensation != orientationCompensation) { mOrientationCompensation = orientationCompensation; setOrientationIndicator(mOrientationCompensation); } } } private void setOrientationIndicator(int degree) { if (mSharePopup != null) mSharePopup.setOrientation(degree); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); addBaseMenuItems(menu); return true; } private void addBaseMenuItems(Menu menu) { MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_CAMERA, new Runnable() { public void run() { switchToOtherMode(ModePicker.MODE_CAMERA); } }); MenuHelper.addSwitchModeMenuItem(menu, ModePicker.MODE_VIDEO, new Runnable() { public void run() { switchToOtherMode(ModePicker.MODE_VIDEO); } }); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Window window = getWindow(); Util.enterLightsOutMode(window); Util.initializeScreenBrightness(window, getContentResolver()); createContentView(); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); if (mSensor == null) { mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); } mOrientationEventListener = new PanoOrientationEventListener(this); mTransformMatrix = new float[16]; mPreparePreviewString = getResources().getString(R.string.pano_dialog_prepare_preview); mDialogTitle = getResources().getString(R.string.pano_dialog_title); mDialogOkString = getResources().getString(R.string.dialog_ok); mDialogPanoramaFailedString = getResources().getString(R.string.pano_dialog_panorama_failed); mMainHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_LOW_RES_FINAL_MOSAIC_READY: onBackgroundThreadFinished(); showFinalMosaic((Bitmap) msg.obj); saveHighResMosaic(); break; case MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL: onBackgroundThreadFinished(); // Set the thumbnail bitmap here because mThumbnailView must be accessed // from the UI thread. updateThumbnailButton(); // Share popup may still have the reference to the old thumbnail. Clear it. mSharePopup = null; resetToPreview(); break; case MSG_GENERATE_FINAL_MOSAIC_ERROR: onBackgroundThreadFinished(); if (mPausing) { resetToPreview(); } else { mRotateDialog.showAlertDialog( mDialogTitle, mDialogPanoramaFailedString, mDialogOkString, new Runnable() { @Override public void run() { resetToPreview(); }}, null, null); } break; case MSG_RESET_TO_PREVIEW: onBackgroundThreadFinished(); resetToPreview(); break; case MSG_CLEAR_SCREEN_DELAY: getWindow().clearFlags(WindowManager.LayoutParams. FLAG_KEEP_SCREEN_ON); break; } clearMosaicFrameProcessorIfNeeded(); } }; } private void setupCamera() { openCamera(); Parameters parameters = mCameraDevice.getParameters(); setupCaptureParams(parameters); configureCamera(parameters); } private void releaseCamera() { if (mCameraDevice != null) { mCameraDevice.setPreviewCallbackWithBuffer(null); CameraHolder.instance().release(); mCameraDevice = null; mCameraState = PREVIEW_STOPPED; } } private void openCamera() { try { mCameraDevice = Util.openCamera(this, CameraHolder.instance().getBackCameraId()); } catch (CameraHardwareException e) { Util.showErrorAndFinish(this, R.string.cannot_connect_camera); return; } catch (CameraDisabledException e) { Util.showErrorAndFinish(this, R.string.camera_disabled); return; } } private boolean findBestPreviewSize(List<Size> supportedSizes, boolean need4To3, boolean needSmaller) { int pixelsDiff = DEFAULT_CAPTURE_PIXELS; boolean hasFound = false; for (Size size : supportedSizes) { int h = size.height; int w = size.width; // we only want 4:3 format. int d = DEFAULT_CAPTURE_PIXELS - h * w; if (needSmaller && d < 0) { // no bigger preview than 960x720. continue; } if (need4To3 && (h * 4 != w * 3)) { continue; } d = Math.abs(d); if (d < pixelsDiff) { mPreviewWidth = w; mPreviewHeight = h; pixelsDiff = d; hasFound = true; } } return hasFound; } private void setupCaptureParams(Parameters parameters) { List<Size> supportedSizes = parameters.getSupportedPreviewSizes(); if (!findBestPreviewSize(supportedSizes, true, true)) { Log.w(TAG, "No 4:3 ratio preview size supported."); if (!findBestPreviewSize(supportedSizes, false, true)) { Log.w(TAG, "Can't find a supported preview size smaller than 960x720."); findBestPreviewSize(supportedSizes, false, false); } } Log.v(TAG, "preview h = " + mPreviewHeight + " , w = " + mPreviewWidth); parameters.setPreviewSize(mPreviewWidth, mPreviewHeight); List<int[]> frameRates = parameters.getSupportedPreviewFpsRange(); int last = frameRates.size() - 1; int minFps = (frameRates.get(last))[Parameters.PREVIEW_FPS_MIN_INDEX]; int maxFps = (frameRates.get(last))[Parameters.PREVIEW_FPS_MAX_INDEX]; parameters.setPreviewFpsRange(minFps, maxFps); Log.v(TAG, "preview fps: " + minFps + ", " + maxFps); List<String> supportedFocusModes = parameters.getSupportedFocusModes(); if (supportedFocusModes.indexOf(mTargetFocusMode) >= 0) { parameters.setFocusMode(mTargetFocusMode); } else { // Use the default focus mode and log a message Log.w(TAG, "Cannot set the focus mode to " + mTargetFocusMode + " becuase the mode is not supported."); } parameters.setRecordingHint(false); mHorizontalViewAngle = (((mDeviceOrientation / 90) % 2) == 0) ? parameters.getHorizontalViewAngle() : parameters.getVerticalViewAngle(); } public int getPreviewBufSize() { PixelFormat pixelInfo = new PixelFormat(); PixelFormat.getPixelFormatInfo(mCameraDevice.getParameters().getPreviewFormat(), pixelInfo); // TODO: remove this extra 32 byte after the driver bug is fixed. return (mPreviewWidth * mPreviewHeight * pixelInfo.bitsPerPixel / 8) + 32; } private void configureCamera(Parameters parameters) { mCameraDevice.setParameters(parameters); } private boolean switchToOtherMode(int mode) { if (isFinishing()) { return false; } MenuHelper.gotoMode(mode, this); finish(); return true; } public boolean onModeChanged(int mode) { if (mode != ModePicker.MODE_PANORAMA) { return switchToOtherMode(mode); } else { return true; } } @Override public void onMosaicSurfaceChanged() { runOnUiThread(new Runnable() { @Override public void run() { if (!mPausing) { startCameraPreview(); } } }); } @Override public void onMosaicSurfaceCreated(final int textureID) { runOnUiThread(new Runnable() { @Override public void run() { if (mSurfaceTexture != null) { mSurfaceTexture.release(); } mSurfaceTexture = new SurfaceTexture(textureID); if (!mPausing) { mSurfaceTexture.setOnFrameAvailableListener(PanoramaActivity.this); } } }); } public void runViewFinder() { mMosaicView.setWarping(false); // Call preprocess to render it to low-res and high-res RGB textures. mMosaicView.preprocess(mTransformMatrix); mMosaicView.setReady(); mMosaicView.requestRender(); } public void runMosaicCapture() { mMosaicView.setWarping(true); // Call preprocess to render it to low-res and high-res RGB textures. mMosaicView.preprocess(mTransformMatrix); // Lock the conditional variable to ensure the order of transferGPUtoCPU and // mMosaicFrame.processFrame(). mMosaicView.lockPreviewReadyFlag(); // Now, transfer the textures from GPU to CPU memory for processing mMosaicView.transferGPUtoCPU(); // Wait on the condition variable (will be opened when GPU->CPU transfer is done). mMosaicView.waitUntilPreviewReady(); mMosaicFrameProcessor.processFrame(); } public synchronized void onFrameAvailable(SurfaceTexture surface) { /* This function may be called by some random thread, * so let's be safe and use synchronize. No OpenGL calls can be done here. */ // Updating the texture should be done in the GL thread which mMosaicView is attached. mMosaicView.queueEvent(new Runnable() { @Override public void run() { mSurfaceTexture.updateTexImage(); mSurfaceTexture.getTransformMatrix(mTransformMatrix); } }); // Update the transformation matrix for mosaic pre-process. if (mCaptureState == CAPTURE_STATE_VIEWFINDER) { runViewFinder(); } else { runMosaicCapture(); } } private void hideDirectionIndicators() { mLeftIndicator.setVisibility(View.GONE); mRightIndicator.setVisibility(View.GONE); } private void showDirectionIndicators(int direction) { switch (direction) { case PanoProgressBar.DIRECTION_NONE: mLeftIndicator.setVisibility(View.VISIBLE); mRightIndicator.setVisibility(View.VISIBLE); break; case PanoProgressBar.DIRECTION_LEFT: mLeftIndicator.setVisibility(View.VISIBLE); mRightIndicator.setVisibility(View.GONE); break; case PanoProgressBar.DIRECTION_RIGHT: mLeftIndicator.setVisibility(View.GONE); mRightIndicator.setVisibility(View.VISIBLE); break; } } public void startCapture() { // Reset values so we can do this again. mCancelComputation = false; mTimeTaken = System.currentTimeMillis(); mCaptureState = CAPTURE_STATE_MOSAIC; mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan_recording); mCaptureIndicator.setVisibility(View.VISIBLE); showDirectionIndicators(PanoProgressBar.DIRECTION_NONE); mThumbnailView.setEnabled(false); mCompassValueXStart = mCompassValueXStartBuffer; mCompassValueYStart = mCompassValueYStartBuffer; mMinAngleX = 0; mMaxAngleX = 0; mMinAngleY = 0; mMaxAngleY = 0; mTimestamp = 0; mMosaicFrameProcessor.setProgressListener(new MosaicFrameProcessor.ProgressListener() { @Override public void onProgress(boolean isFinished, float panningRateX, float panningRateY, float progressX, float progressY) { if (isFinished || (mMaxAngleX - mMinAngleX >= DEFAULT_SWEEP_ANGLE) || (mMaxAngleY - mMinAngleY >= DEFAULT_SWEEP_ANGLE)) { stopCapture(false); } else { updateProgress(panningRateX, progressX, progressY); } } }); if (mModePicker != null) mModePicker.setEnabled(false); mPanoProgressBar.reset(); // TODO: calculate the indicator width according to different devices to reflect the actual // angle of view of the camera device. mPanoProgressBar.setIndicatorWidth(20); mPanoProgressBar.setMaxProgress(DEFAULT_SWEEP_ANGLE); mPanoProgressBar.setVisibility(View.VISIBLE); keepScreenOn(); } private void stopCapture(boolean aborted) { mCaptureState = CAPTURE_STATE_VIEWFINDER; mCaptureIndicator.setVisibility(View.GONE); hideTooFastIndication(); hideDirectionIndicators(); mThumbnailView.setEnabled(true); mMosaicFrameProcessor.setProgressListener(null); stopCameraPreview(); mSurfaceTexture.setOnFrameAvailableListener(null); if (!aborted && !mThreadRunning) { mRotateDialog.showWaitingDialog(mPreparePreviewString); runBackgroundThread(new Thread() { @Override public void run() { MosaicJpeg jpeg = generateFinalMosaic(false); if (jpeg != null && jpeg.isValid) { Bitmap bitmap = null; bitmap = BitmapFactory.decodeByteArray(jpeg.data, 0, jpeg.data.length); mMainHandler.sendMessage(mMainHandler.obtainMessage( MSG_LOW_RES_FINAL_MOSAIC_READY, bitmap)); } else { mMainHandler.sendMessage(mMainHandler.obtainMessage( MSG_RESET_TO_PREVIEW)); } } }); } // do we have to wait for the thread to complete before enabling this? if (mModePicker != null) mModePicker.setEnabled(true); keepScreenOnAwhile(); } private void showTooFastIndication() { mTooFastPrompt.setVisibility(View.VISIBLE); mFastIndicationBorder.setVisibility(View.VISIBLE); mPanoProgressBar.setIndicatorColor(mIndicatorColorFast); mLeftIndicator.setEnabled(true); mRightIndicator.setEnabled(true); } private void hideTooFastIndication() { mTooFastPrompt.setVisibility(View.GONE); mFastIndicationBorder.setVisibility(View.GONE); mPanoProgressBar.setIndicatorColor(mIndicatorColor); mLeftIndicator.setEnabled(false); mRightIndicator.setEnabled(false); } private void updateProgress(float panningRate, float progressX, float progressY) { mMosaicView.setReady(); mMosaicView.requestRender(); // TODO: Now we just display warning message by the panning speed. // Since we only support horizontal panning, we should display a warning message // in UI when there're significant vertical movements. if (Math.abs(panningRate * mHorizontalViewAngle) > PANNING_SPEED_THRESHOLD) { showTooFastIndication(); } else { hideTooFastIndication(); } mPanoProgressBar.setProgress((int) (progressX * mHorizontalViewAngle)); } private void createContentView() { setContentView(R.layout.panorama); mCaptureState = CAPTURE_STATE_VIEWFINDER; Resources appRes = getResources(); mCaptureLayout = (View) findViewById(R.id.pano_capture_layout); mPanoProgressBar = (PanoProgressBar) findViewById(R.id.pano_pan_progress_bar); mPanoProgressBar.setBackgroundColor(appRes.getColor(R.color.pano_progress_empty)); mPanoProgressBar.setDoneColor(appRes.getColor(R.color.pano_progress_done)); mIndicatorColor = appRes.getColor(R.color.pano_progress_indication); mIndicatorColorFast = appRes.getColor(R.color.pano_progress_indication_fast); mPanoProgressBar.setIndicatorColor(mIndicatorColor); mPanoProgressBar.setOnDirectionChangeListener( new PanoProgressBar.OnDirectionChangeListener () { @Override public void onDirectionChange(int direction) { if (mCaptureState == CAPTURE_STATE_MOSAIC) { showDirectionIndicators(direction); } } }); mLeftIndicator = (ImageView) findViewById(R.id.pano_pan_left_indicator); mRightIndicator = (ImageView) findViewById(R.id.pano_pan_right_indicator); mLeftIndicator.setEnabled(false); mRightIndicator.setEnabled(false); mTooFastPrompt = (TextView) findViewById(R.id.pano_capture_too_fast_textview); mFastIndicationBorder = (View) findViewById(R.id.pano_speed_indication_border); mSavingProgressBar = (PanoProgressBar) findViewById(R.id.pano_saving_progress_bar); mSavingProgressBar.setIndicatorWidth(0); mSavingProgressBar.setMaxProgress(100); mSavingProgressBar.setBackgroundColor(appRes.getColor(R.color.pano_progress_empty)); mSavingProgressBar.setDoneColor(appRes.getColor(R.color.pano_progress_indication)); mCaptureIndicator = (RotateLayout) findViewById(R.id.pano_capture_indicator); mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail); mThumbnailView.enableFilter(false); mReviewLayout = (View) findViewById(R.id.pano_review_layout); mReview = (ImageView) findViewById(R.id.pano_reviewarea); mMosaicView = (MosaicRendererSurfaceView) findViewById(R.id.pano_renderer); mMosaicView.getRenderer().setMosaicSurfaceCreateListener(this); mModePicker = (ModePicker) findViewById(R.id.mode_picker); mModePicker.setVisibility(View.VISIBLE); mModePicker.setOnModeChangeListener(this); mModePicker.setCurrentMode(ModePicker.MODE_PANORAMA); mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan); mShutterButton.setOnShutterButtonListener(this); mPanoLayout = findViewById(R.id.pano_layout); mRotateDialog = new RotateDialogController(this, R.layout.rotate_dialog); if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { Rotatable[] rotateLayout = { (Rotatable) findViewById(R.id.pano_pan_progress_bar_layout), (Rotatable) findViewById(R.id.pano_capture_too_fast_textview_layout), (Rotatable) findViewById(R.id.pano_review_saving_indication_layout), (Rotatable) findViewById(R.id.pano_saving_progress_bar_layout), (Rotatable) findViewById(R.id.pano_review_cancel_button_layout), + (Rotatable) findViewById(R.id.pano_rotate_reviewarea), (Rotatable) mRotateDialog, (Rotatable) mCaptureIndicator, (Rotatable) mModePicker, (Rotatable) mThumbnailView}; for (Rotatable r : rotateLayout) { r.setOrientation(270); } } } @Override public void onShutterButtonClick() { // If mSurfaceTexture == null then GL setup is not finished yet. // No buttons can be pressed. if (mPausing || mThreadRunning || mSurfaceTexture == null) return; // Since this button will stay on the screen when capturing, we need to check the state // right now. switch (mCaptureState) { case CAPTURE_STATE_VIEWFINDER: if (mRecordSound != null) mRecordSound.play(); startCapture(); break; case CAPTURE_STATE_MOSAIC: if (mRecordSound != null) mRecordSound.play(); stopCapture(false); } } @Override public void onShutterButtonFocus(boolean pressed) { } public void reportProgress() { mSavingProgressBar.reset(); mSavingProgressBar.setRightIncreasing(true); Thread t = new Thread() { @Override public void run() { while (mThreadRunning) { final int progress = mMosaicFrameProcessor.reportProgress( true, mCancelComputation); try { synchronized (mWaitObject) { mWaitObject.wait(50); } } catch (InterruptedException e) { throw new RuntimeException("Panorama reportProgress failed", e); } // Update the progress bar runOnUiThread(new Runnable() { public void run() { mSavingProgressBar.setProgress(progress); } }); } } }; t.start(); } private void initThumbnailButton() { // Load the thumbnail from the disk. if (mThumbnail == null) { mThumbnail = Thumbnail.loadFrom(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME)); } updateThumbnailButton(); } private void updateThumbnailButton() { // Update last image if URI is invalid and the storage is ready. ContentResolver contentResolver = getContentResolver(); if ((mThumbnail == null || !Util.isUriValid(mThumbnail.getUri(), contentResolver))) { mThumbnail = Thumbnail.getLastThumbnail(contentResolver); } if (mThumbnail != null) { mThumbnailView.setBitmap(mThumbnail.getBitmap()); } else { mThumbnailView.setBitmap(null); } } public void saveHighResMosaic() { runBackgroundThread(new Thread() { @Override public void run() { MosaicJpeg jpeg = generateFinalMosaic(true); if (jpeg == null) { // Cancelled by user. mMainHandler.sendEmptyMessage(MSG_RESET_TO_PREVIEW); } else if (!jpeg.isValid) { // Error when generating mosaic. mMainHandler.sendEmptyMessage(MSG_GENERATE_FINAL_MOSAIC_ERROR); } else { int orientation = Exif.getOrientation(jpeg.data); Uri uri = savePanorama(jpeg.data, jpeg.width, jpeg.height, orientation); if (uri != null) { // Create a thumbnail whose width or height is equal or bigger // than the screen's width or height. int widthRatio = (int) Math.ceil((double) jpeg.width / mPanoLayout.getWidth()); int heightRatio = (int) Math.ceil((double) jpeg.height / mPanoLayout.getHeight()); int inSampleSize = Integer.highestOneBit( Math.max(widthRatio, heightRatio)); mThumbnail = Thumbnail.createThumbnail( jpeg.data, orientation, inSampleSize, uri); } mMainHandler.sendMessage( mMainHandler.obtainMessage(MSG_RESET_TO_PREVIEW_WITH_THUMBNAIL)); } } }); reportProgress(); } private void runBackgroundThread(Thread thread) { mThreadRunning = true; thread.start(); } private void onBackgroundThreadFinished() { mThreadRunning = false; mRotateDialog.dismissDialog(); } private void cancelHighResComputation() { mCancelComputation = true; synchronized (mWaitObject) { mWaitObject.notify(); } } @OnClickAttr public void onCancelButtonClicked(View v) { if (mPausing || mSurfaceTexture == null) return; cancelHighResComputation(); } @OnClickAttr public void onThumbnailClicked(View v) { if (mPausing || mThreadRunning || mSurfaceTexture == null) return; showSharePopup(); } private void showSharePopup() { if (mThumbnail == null) return; Uri uri = mThumbnail.getUri(); if (mSharePopup == null || !uri.equals(mSharePopup.getUri())) { // The orientation compensation is set to 0 here because we only support landscape. mSharePopup = new SharePopup(this, uri, mThumbnail.getBitmap(), mOrientationCompensation, findViewById(R.id.frame_layout)); } mSharePopup.showAtLocation(mThumbnailView, Gravity.NO_GRAVITY, 0, 0); } private void reset() { mCaptureState = CAPTURE_STATE_VIEWFINDER; mReviewLayout.setVisibility(View.GONE); mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan); mPanoProgressBar.setVisibility(View.GONE); mCaptureLayout.setVisibility(View.VISIBLE); mMosaicFrameProcessor.reset(); mSurfaceTexture.setOnFrameAvailableListener(this); } private void resetToPreview() { reset(); if (!mPausing) startCameraPreview(); } private void showFinalMosaic(Bitmap bitmap) { if (bitmap != null) { mReview.setImageBitmap(bitmap); } mCaptureLayout.setVisibility(View.GONE); mReviewLayout.setVisibility(View.VISIBLE); } private Uri savePanorama(byte[] jpegData, int width, int height, int orientation) { if (jpegData != null) { String imagePath = PanoUtil.createName( getResources().getString(R.string.pano_file_name_format), mTimeTaken); return Storage.addImage(getContentResolver(), imagePath, mTimeTaken, null, orientation, jpegData, width, height); } return null; } private void clearMosaicFrameProcessorIfNeeded() { if (!mPausing || mThreadRunning) return; mMosaicFrameProcessor.clear(); } private void initMosaicFrameProcessorIfNeeded() { if (mPausing || mThreadRunning) return; if (mMosaicFrameProcessor == null) { // Start the activity for the first time. mMosaicFrameProcessor = new MosaicFrameProcessor( mPreviewWidth, mPreviewHeight, getPreviewBufSize()); } mMosaicFrameProcessor.initialize(); } private void initSoundRecorder() { // Construct sound player; use enforced sound output if necessary File recordSoundFile = new File(VIDEO_RECORD_SOUND); try { ParcelFileDescriptor recordSoundParcel = ParcelFileDescriptor.open(recordSoundFile, ParcelFileDescriptor.MODE_READ_ONLY); AssetFileDescriptor recordSoundAsset = new AssetFileDescriptor(recordSoundParcel, 0, AssetFileDescriptor.UNKNOWN_LENGTH); if (SystemProperties.get("ro.camera.sound.forced", "0").equals("0")) { mRecordSound = new SoundPlayer(recordSoundAsset, false); } else { mRecordSound = new SoundPlayer(recordSoundAsset, true); } } catch (java.io.FileNotFoundException e) { Log.e(TAG, "System video record sound not found"); mRecordSound = null; } } private void releaseSoundRecorder() { if (mRecordSound != null) { mRecordSound.release(); mRecordSound = null; } } @Override protected void onPause() { super.onPause(); mPausing = true; cancelHighResComputation(); // Stop the capturing first. if (mCaptureState == CAPTURE_STATE_MOSAIC) { stopCapture(true); reset(); } if (mSharePopup != null) mSharePopup.dismiss(); if (mThumbnail != null && !mThumbnail.fromFile()) { mThumbnail.saveTo(new File(getFilesDir(), Thumbnail.LAST_THUMB_FILENAME)); } releaseCamera(); releaseSoundRecorder(); mMosaicView.onPause(); clearMosaicFrameProcessorIfNeeded(); mOrientationEventListener.disable(); resetScreenOn(); System.gc(); } @Override protected void doOnResume() { mPausing = false; mOrientationEventListener.enable(); mCaptureState = CAPTURE_STATE_VIEWFINDER; setupCamera(); initSoundRecorder(); // Camera must be initialized before MosaicFrameProcessor is initialized. The preview size // has to be decided by camera device. initMosaicFrameProcessorIfNeeded(); mMosaicView.onResume(); initThumbnailButton(); keepScreenOnAwhile(); } /** * Generate the final mosaic image. * * @param highRes flag to indicate whether we want to get a high-res version. * @return a MosaicJpeg with its isValid flag set to true if successful; null if the generation * process is cancelled; and a MosaicJpeg with its isValid flag set to false if there * is an error in generating the final mosaic. */ public MosaicJpeg generateFinalMosaic(boolean highRes) { int mosaicReturnCode = mMosaicFrameProcessor.createMosaic(highRes); if (mosaicReturnCode == Mosaic.MOSAIC_RET_CANCELLED) { return null; } else if (mosaicReturnCode == Mosaic.MOSAIC_RET_ERROR) { return new MosaicJpeg(); } byte[] imageData = mMosaicFrameProcessor.getFinalMosaicNV21(); if (imageData == null) { Log.e(TAG, "getFinalMosaicNV21() returned null."); return new MosaicJpeg(); } int len = imageData.length - 8; int width = (imageData[len + 0] << 24) + ((imageData[len + 1] & 0xFF) << 16) + ((imageData[len + 2] & 0xFF) << 8) + (imageData[len + 3] & 0xFF); int height = (imageData[len + 4] << 24) + ((imageData[len + 5] & 0xFF) << 16) + ((imageData[len + 6] & 0xFF) << 8) + (imageData[len + 7] & 0xFF); Log.v(TAG, "ImLength = " + (len) + ", W = " + width + ", H = " + height); if (width <= 0 || height <= 0) { // TODO: pop up a error meesage indicating that the final result is not generated. Log.e(TAG, "width|height <= 0!!, len = " + (len) + ", W = " + width + ", H = " + height); return new MosaicJpeg(); } YuvImage yuvimage = new YuvImage(imageData, ImageFormat.NV21, width, height, null); ByteArrayOutputStream out = new ByteArrayOutputStream(); yuvimage.compressToJpeg(new Rect(0, 0, width, height), 100, out); try { out.close(); } catch (Exception e) { Log.e(TAG, "Exception in storing final mosaic", e); return new MosaicJpeg(); } return new MosaicJpeg(out.toByteArray(), width, height); } private void setPreviewTexture(SurfaceTexture surface) { try { mCameraDevice.setPreviewTexture(surface); } catch (Throwable ex) { releaseCamera(); throw new RuntimeException("setPreviewTexture failed", ex); } } private void startCameraPreview() { // If we're previewing already, stop the preview first (this will blank // the screen). if (mCameraState != PREVIEW_STOPPED) stopCameraPreview(); // Set the display orientation to 0, so that the underlying mosaic library // can always get undistorted mPreviewWidth x mPreviewHeight image data // from SurfaceTexture. mCameraDevice.setDisplayOrientation(0); setPreviewTexture(mSurfaceTexture); try { Log.v(TAG, "startPreview"); mCameraDevice.startPreview(); } catch (Throwable ex) { releaseCamera(); throw new RuntimeException("startPreview failed", ex); } mCameraState = PREVIEW_ACTIVE; } private void stopCameraPreview() { if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) { Log.v(TAG, "stopPreview"); mCameraDevice.stopPreview(); } mCameraState = PREVIEW_STOPPED; } @Override public void onUserInteraction() { super.onUserInteraction(); if (mCaptureState != CAPTURE_STATE_MOSAIC) keepScreenOnAwhile(); } private void resetScreenOn() { mMainHandler.removeMessages(MSG_CLEAR_SCREEN_DELAY); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private void keepScreenOnAwhile() { mMainHandler.removeMessages(MSG_CLEAR_SCREEN_DELAY); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mMainHandler.sendEmptyMessageDelayed(MSG_CLEAR_SCREEN_DELAY, SCREEN_DELAY); } private void keepScreenOn() { mMainHandler.removeMessages(MSG_CLEAR_SCREEN_DELAY); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }
true
true
private void createContentView() { setContentView(R.layout.panorama); mCaptureState = CAPTURE_STATE_VIEWFINDER; Resources appRes = getResources(); mCaptureLayout = (View) findViewById(R.id.pano_capture_layout); mPanoProgressBar = (PanoProgressBar) findViewById(R.id.pano_pan_progress_bar); mPanoProgressBar.setBackgroundColor(appRes.getColor(R.color.pano_progress_empty)); mPanoProgressBar.setDoneColor(appRes.getColor(R.color.pano_progress_done)); mIndicatorColor = appRes.getColor(R.color.pano_progress_indication); mIndicatorColorFast = appRes.getColor(R.color.pano_progress_indication_fast); mPanoProgressBar.setIndicatorColor(mIndicatorColor); mPanoProgressBar.setOnDirectionChangeListener( new PanoProgressBar.OnDirectionChangeListener () { @Override public void onDirectionChange(int direction) { if (mCaptureState == CAPTURE_STATE_MOSAIC) { showDirectionIndicators(direction); } } }); mLeftIndicator = (ImageView) findViewById(R.id.pano_pan_left_indicator); mRightIndicator = (ImageView) findViewById(R.id.pano_pan_right_indicator); mLeftIndicator.setEnabled(false); mRightIndicator.setEnabled(false); mTooFastPrompt = (TextView) findViewById(R.id.pano_capture_too_fast_textview); mFastIndicationBorder = (View) findViewById(R.id.pano_speed_indication_border); mSavingProgressBar = (PanoProgressBar) findViewById(R.id.pano_saving_progress_bar); mSavingProgressBar.setIndicatorWidth(0); mSavingProgressBar.setMaxProgress(100); mSavingProgressBar.setBackgroundColor(appRes.getColor(R.color.pano_progress_empty)); mSavingProgressBar.setDoneColor(appRes.getColor(R.color.pano_progress_indication)); mCaptureIndicator = (RotateLayout) findViewById(R.id.pano_capture_indicator); mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail); mThumbnailView.enableFilter(false); mReviewLayout = (View) findViewById(R.id.pano_review_layout); mReview = (ImageView) findViewById(R.id.pano_reviewarea); mMosaicView = (MosaicRendererSurfaceView) findViewById(R.id.pano_renderer); mMosaicView.getRenderer().setMosaicSurfaceCreateListener(this); mModePicker = (ModePicker) findViewById(R.id.mode_picker); mModePicker.setVisibility(View.VISIBLE); mModePicker.setOnModeChangeListener(this); mModePicker.setCurrentMode(ModePicker.MODE_PANORAMA); mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan); mShutterButton.setOnShutterButtonListener(this); mPanoLayout = findViewById(R.id.pano_layout); mRotateDialog = new RotateDialogController(this, R.layout.rotate_dialog); if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { Rotatable[] rotateLayout = { (Rotatable) findViewById(R.id.pano_pan_progress_bar_layout), (Rotatable) findViewById(R.id.pano_capture_too_fast_textview_layout), (Rotatable) findViewById(R.id.pano_review_saving_indication_layout), (Rotatable) findViewById(R.id.pano_saving_progress_bar_layout), (Rotatable) findViewById(R.id.pano_review_cancel_button_layout), (Rotatable) mRotateDialog, (Rotatable) mCaptureIndicator, (Rotatable) mModePicker, (Rotatable) mThumbnailView}; for (Rotatable r : rotateLayout) { r.setOrientation(270); } } }
private void createContentView() { setContentView(R.layout.panorama); mCaptureState = CAPTURE_STATE_VIEWFINDER; Resources appRes = getResources(); mCaptureLayout = (View) findViewById(R.id.pano_capture_layout); mPanoProgressBar = (PanoProgressBar) findViewById(R.id.pano_pan_progress_bar); mPanoProgressBar.setBackgroundColor(appRes.getColor(R.color.pano_progress_empty)); mPanoProgressBar.setDoneColor(appRes.getColor(R.color.pano_progress_done)); mIndicatorColor = appRes.getColor(R.color.pano_progress_indication); mIndicatorColorFast = appRes.getColor(R.color.pano_progress_indication_fast); mPanoProgressBar.setIndicatorColor(mIndicatorColor); mPanoProgressBar.setOnDirectionChangeListener( new PanoProgressBar.OnDirectionChangeListener () { @Override public void onDirectionChange(int direction) { if (mCaptureState == CAPTURE_STATE_MOSAIC) { showDirectionIndicators(direction); } } }); mLeftIndicator = (ImageView) findViewById(R.id.pano_pan_left_indicator); mRightIndicator = (ImageView) findViewById(R.id.pano_pan_right_indicator); mLeftIndicator.setEnabled(false); mRightIndicator.setEnabled(false); mTooFastPrompt = (TextView) findViewById(R.id.pano_capture_too_fast_textview); mFastIndicationBorder = (View) findViewById(R.id.pano_speed_indication_border); mSavingProgressBar = (PanoProgressBar) findViewById(R.id.pano_saving_progress_bar); mSavingProgressBar.setIndicatorWidth(0); mSavingProgressBar.setMaxProgress(100); mSavingProgressBar.setBackgroundColor(appRes.getColor(R.color.pano_progress_empty)); mSavingProgressBar.setDoneColor(appRes.getColor(R.color.pano_progress_indication)); mCaptureIndicator = (RotateLayout) findViewById(R.id.pano_capture_indicator); mThumbnailView = (RotateImageView) findViewById(R.id.thumbnail); mThumbnailView.enableFilter(false); mReviewLayout = (View) findViewById(R.id.pano_review_layout); mReview = (ImageView) findViewById(R.id.pano_reviewarea); mMosaicView = (MosaicRendererSurfaceView) findViewById(R.id.pano_renderer); mMosaicView.getRenderer().setMosaicSurfaceCreateListener(this); mModePicker = (ModePicker) findViewById(R.id.mode_picker); mModePicker.setVisibility(View.VISIBLE); mModePicker.setOnModeChangeListener(this); mModePicker.setCurrentMode(ModePicker.MODE_PANORAMA); mShutterButton = (ShutterButton) findViewById(R.id.shutter_button); mShutterButton.setBackgroundResource(R.drawable.btn_shutter_pan); mShutterButton.setOnShutterButtonListener(this); mPanoLayout = findViewById(R.id.pano_layout); mRotateDialog = new RotateDialogController(this, R.layout.rotate_dialog); if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { Rotatable[] rotateLayout = { (Rotatable) findViewById(R.id.pano_pan_progress_bar_layout), (Rotatable) findViewById(R.id.pano_capture_too_fast_textview_layout), (Rotatable) findViewById(R.id.pano_review_saving_indication_layout), (Rotatable) findViewById(R.id.pano_saving_progress_bar_layout), (Rotatable) findViewById(R.id.pano_review_cancel_button_layout), (Rotatable) findViewById(R.id.pano_rotate_reviewarea), (Rotatable) mRotateDialog, (Rotatable) mCaptureIndicator, (Rotatable) mModePicker, (Rotatable) mThumbnailView}; for (Rotatable r : rotateLayout) { r.setOrientation(270); } } }
diff --git a/src/com/servegame/abendstern/tunnelblick/backend/ModalMouseMotionInputDriver.java b/src/com/servegame/abendstern/tunnelblick/backend/ModalMouseMotionInputDriver.java index 495f5db..8082e16 100644 --- a/src/com/servegame/abendstern/tunnelblick/backend/ModalMouseMotionInputDriver.java +++ b/src/com/servegame/abendstern/tunnelblick/backend/ModalMouseMotionInputDriver.java @@ -1,58 +1,60 @@ package com.servegame.abendstern.tunnelblick.backend; import java.awt.event.*; /** * Input driver which translates mouse motion into pointer and/or body * control. * * The driver is modal in that, at any given time, it is controlling EITHER * pointer zero or body 0. The mouse whell is used to select mode; up shifts to * pointer mode, down to body mode. */ public final class ModalMouseMotionInputDriver extends AWTInputDriver implements MouseMotionListener, MouseWheelListener { private boolean pointerMode = true; private GameManager manager = null; /** * Sets the mode to use. True is pointer mode, false is body mode. */ public void setPointerMode(boolean pointerMode) { this.pointerMode = pointerMode; } public void installInto(GameManager man) { manager = man; man.getCanvas().addMouseMotionListener(this); man.getFrame ().addMouseWheelListener (this); } public void mouseMoved(MouseEvent evt) { java.awt.Component canvas = manager.getCanvas(); float x = evt.getX() / (float)canvas.getWidth(); float y = evt.getY() / (float)canvas.getHeight() * manager.vheight(); //OpenGL's Y axis is upside-down y = manager.vheight() - y; InputStatus is = manager.getSharedInputStatus(); - if (pointerMode) { - is.pointers[0][0] = x; - is.pointers[0][1] = y; - enqueue(new InputEvent(InputEvent.TYPE_POINTER_MOVEMENT, 0, x, y)); - } else { - is.bodies[0] = x; - enqueue(new InputEvent(InputEvent.TYPE_BODY_MOVEMENT, 0, x, y)); + synchronized (manager) { + if (pointerMode) { + is.pointers[0][0] = x; + is.pointers[0][1] = y; + enqueue(new InputEvent(InputEvent.TYPE_POINTER_MOVEMENT, 0, x, y)); + } else { + is.bodies[0] = x; + enqueue(new InputEvent(InputEvent.TYPE_BODY_MOVEMENT, 0, x, y)); + } } } public void mouseDragged(MouseEvent evt) { mouseMoved(evt); } public void mouseWheelMoved(MouseWheelEvent evt) { pointerMode = (evt.getWheelRotation() < 0); } }
true
true
public void mouseMoved(MouseEvent evt) { java.awt.Component canvas = manager.getCanvas(); float x = evt.getX() / (float)canvas.getWidth(); float y = evt.getY() / (float)canvas.getHeight() * manager.vheight(); //OpenGL's Y axis is upside-down y = manager.vheight() - y; InputStatus is = manager.getSharedInputStatus(); if (pointerMode) { is.pointers[0][0] = x; is.pointers[0][1] = y; enqueue(new InputEvent(InputEvent.TYPE_POINTER_MOVEMENT, 0, x, y)); } else { is.bodies[0] = x; enqueue(new InputEvent(InputEvent.TYPE_BODY_MOVEMENT, 0, x, y)); } }
public void mouseMoved(MouseEvent evt) { java.awt.Component canvas = manager.getCanvas(); float x = evt.getX() / (float)canvas.getWidth(); float y = evt.getY() / (float)canvas.getHeight() * manager.vheight(); //OpenGL's Y axis is upside-down y = manager.vheight() - y; InputStatus is = manager.getSharedInputStatus(); synchronized (manager) { if (pointerMode) { is.pointers[0][0] = x; is.pointers[0][1] = y; enqueue(new InputEvent(InputEvent.TYPE_POINTER_MOVEMENT, 0, x, y)); } else { is.bodies[0] = x; enqueue(new InputEvent(InputEvent.TYPE_BODY_MOVEMENT, 0, x, y)); } } }
diff --git a/src/main/java/org/drools/planner/examples/ras2012/move/WaitTimeAssignmentMoveFactory.java b/src/main/java/org/drools/planner/examples/ras2012/move/WaitTimeAssignmentMoveFactory.java index 6becc2e..8e5579e 100644 --- a/src/main/java/org/drools/planner/examples/ras2012/move/WaitTimeAssignmentMoveFactory.java +++ b/src/main/java/org/drools/planner/examples/ras2012/move/WaitTimeAssignmentMoveFactory.java @@ -1,46 +1,43 @@ package org.drools.planner.examples.ras2012.move; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import org.drools.planner.core.move.Move; import org.drools.planner.core.move.factory.AbstractMoveFactory; import org.drools.planner.core.solution.Solution; import org.drools.planner.examples.ras2012.RAS2012Solution; import org.drools.planner.examples.ras2012.model.Node; import org.drools.planner.examples.ras2012.model.WaitTime; import org.drools.planner.examples.ras2012.model.planner.ItineraryAssignment; public class WaitTimeAssignmentMoveFactory extends AbstractMoveFactory { @Override public List<Move> createMoveList(@SuppressWarnings("rawtypes") final Solution solution) { // prepare the various delays + // TODO estimate maximum necessary wait time from the longest arc and slowest train List<WaitTime> wts = new LinkedList<WaitTime>(); wts.add(null); wts.add(new WaitTime(1)); wts.add(new WaitTime(2)); wts.add(new WaitTime(3)); wts.add(new WaitTime(4)); wts.add(new WaitTime(5)); wts.add(new WaitTime(10)); - wts.add(new WaitTime(15)); wts.add(new WaitTime(20)); - wts.add(new WaitTime(25)); - wts.add(new WaitTime(30)); - wts.add(new WaitTime(45)); - wts.add(new WaitTime(60)); + wts.add(new WaitTime(40)); final List<Move> moves = new ArrayList<Move>(); final RAS2012Solution sol = (RAS2012Solution) solution; for (final ItineraryAssignment ia : sol.getAssignments()) { for (final Node waitPoint : ia.getRoute().getWaitPoints()) { for (WaitTime waitTime : wts) { moves.add(new WaitTimeAssignmentMove(ia, waitPoint, waitTime)); } } } return moves; } }
false
true
public List<Move> createMoveList(@SuppressWarnings("rawtypes") final Solution solution) { // prepare the various delays List<WaitTime> wts = new LinkedList<WaitTime>(); wts.add(null); wts.add(new WaitTime(1)); wts.add(new WaitTime(2)); wts.add(new WaitTime(3)); wts.add(new WaitTime(4)); wts.add(new WaitTime(5)); wts.add(new WaitTime(10)); wts.add(new WaitTime(15)); wts.add(new WaitTime(20)); wts.add(new WaitTime(25)); wts.add(new WaitTime(30)); wts.add(new WaitTime(45)); wts.add(new WaitTime(60)); final List<Move> moves = new ArrayList<Move>(); final RAS2012Solution sol = (RAS2012Solution) solution; for (final ItineraryAssignment ia : sol.getAssignments()) { for (final Node waitPoint : ia.getRoute().getWaitPoints()) { for (WaitTime waitTime : wts) { moves.add(new WaitTimeAssignmentMove(ia, waitPoint, waitTime)); } } } return moves; }
public List<Move> createMoveList(@SuppressWarnings("rawtypes") final Solution solution) { // prepare the various delays // TODO estimate maximum necessary wait time from the longest arc and slowest train List<WaitTime> wts = new LinkedList<WaitTime>(); wts.add(null); wts.add(new WaitTime(1)); wts.add(new WaitTime(2)); wts.add(new WaitTime(3)); wts.add(new WaitTime(4)); wts.add(new WaitTime(5)); wts.add(new WaitTime(10)); wts.add(new WaitTime(20)); wts.add(new WaitTime(40)); final List<Move> moves = new ArrayList<Move>(); final RAS2012Solution sol = (RAS2012Solution) solution; for (final ItineraryAssignment ia : sol.getAssignments()) { for (final Node waitPoint : ia.getRoute().getWaitPoints()) { for (WaitTime waitTime : wts) { moves.add(new WaitTimeAssignmentMove(ia, waitPoint, waitTime)); } } } return moves; }
diff --git a/maven-artifact/src/main/java/org/apache/maven/artifact/metadata/SnapshotArtifactMetadata.java b/maven-artifact/src/main/java/org/apache/maven/artifact/metadata/SnapshotArtifactMetadata.java index 912412749..632d1fdc3 100644 --- a/maven-artifact/src/main/java/org/apache/maven/artifact/metadata/SnapshotArtifactMetadata.java +++ b/maven-artifact/src/main/java/org/apache/maven/artifact/metadata/SnapshotArtifactMetadata.java @@ -1,160 +1,171 @@ package org.apache.maven.artifact.metadata; /* * Copyright 2001-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.codehaus.plexus.util.StringUtils; import org.apache.maven.artifact.Artifact; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Contains the information stored for a snapshot. * * @author <a href="mailto:[email protected]">Brett Porter</a> * @version $Id$ */ public class SnapshotArtifactMetadata extends AbstractVersionArtifactMetadata { private String timestamp = null; private int buildNumber = 0; private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone( "UTC" ); private static final String UTC_TIMESTAMP_PATTERN = "yyyyMMdd.HHmmss"; public static final Pattern VERSION_FILE_PATTERN = Pattern.compile( "^(.*)-([0-9]{8}.[0-9]{6})-([0-9]+)$" ); // TODO: very quick and nasty hack to get the same timestamp across a build - not embedder friendly private static String sessionTimestamp = null; public SnapshotArtifactMetadata( Artifact artifact ) { super( artifact, artifact.getArtifactId() + "-" + artifact.getBaseVersion() + "." + SNAPSHOT_VERSION_FILE ); } public String constructVersion() { String version = artifact.getBaseVersion(); if ( timestamp != null && buildNumber > 0 ) { String newVersion = timestamp + "-" + buildNumber; if ( version != null ) { version = StringUtils.replace( version, "SNAPSHOT", newVersion ); } else { version = newVersion; } } return version; } protected void setContent( String content ) { Matcher matcher = VERSION_FILE_PATTERN.matcher( content ); if ( matcher.matches() ) { timestamp = matcher.group( 2 ); buildNumber = Integer.valueOf( matcher.group( 3 ) ).intValue(); } else { timestamp = null; buildNumber = 0; } } public String getTimestamp() { return timestamp; } public static DateFormat getUtcDateFormatter() { DateFormat utcDateFormatter = new SimpleDateFormat( UTC_TIMESTAMP_PATTERN ); utcDateFormatter.setTimeZone( UTC_TIME_ZONE ); return utcDateFormatter; } public void update() { this.buildNumber++; timestamp = getSessionTimestamp(); } private static String getSessionTimestamp() { if ( sessionTimestamp == null ) { sessionTimestamp = getUtcDateFormatter().format( new Date() ); } return sessionTimestamp; } public int compareTo( Object o ) { SnapshotArtifactMetadata metadata = (SnapshotArtifactMetadata) o; // TODO: probably shouldn't test timestamp - except that it may be used do differentiate for a build number of 0 // in the local repository. check, then remove from here and just compare the build numbers if ( buildNumber > metadata.buildNumber ) { return 1; } else if ( timestamp == null ) { - return -1; + if ( metadata.timestamp == null ) + { + return 0; + } + else + { + return -1; + } + } + else if ( metadata.timestamp == null ) + { + return 1; } else { return timestamp.compareTo( metadata.timestamp ); } } public boolean newerThanFile( File file ) { long fileTime = file.lastModified(); // previous behaviour - compare based on timestamp of file // problem was that version.txt is often updated even if the remote snapshot was not // return ( lastModified > fileTime ); // Compare to timestamp if ( timestamp != null ) { String fileTimestamp = getUtcDateFormatter().format( new Date( fileTime ) ); return ( fileTimestamp.compareTo( timestamp ) < 0 ); } return false; } public String toString() { return "snapshot information for " + artifact.getArtifactId() + " " + artifact.getBaseVersion(); } }
true
true
public int compareTo( Object o ) { SnapshotArtifactMetadata metadata = (SnapshotArtifactMetadata) o; // TODO: probably shouldn't test timestamp - except that it may be used do differentiate for a build number of 0 // in the local repository. check, then remove from here and just compare the build numbers if ( buildNumber > metadata.buildNumber ) { return 1; } else if ( timestamp == null ) { return -1; } else { return timestamp.compareTo( metadata.timestamp ); } }
public int compareTo( Object o ) { SnapshotArtifactMetadata metadata = (SnapshotArtifactMetadata) o; // TODO: probably shouldn't test timestamp - except that it may be used do differentiate for a build number of 0 // in the local repository. check, then remove from here and just compare the build numbers if ( buildNumber > metadata.buildNumber ) { return 1; } else if ( timestamp == null ) { if ( metadata.timestamp == null ) { return 0; } else { return -1; } } else if ( metadata.timestamp == null ) { return 1; } else { return timestamp.compareTo( metadata.timestamp ); } }
diff --git a/src/com/facebook/buck/util/BlockingHttpEndpoint.java b/src/com/facebook/buck/util/BlockingHttpEndpoint.java index 3c17c6a543..653ed3329b 100644 --- a/src/com/facebook/buck/util/BlockingHttpEndpoint.java +++ b/src/com/facebook/buck/util/BlockingHttpEndpoint.java @@ -1,104 +1,105 @@ /* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.util; import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * HttpEndpoint implementation which only allows a certain number of concurrent requests to be in * flight at any given point in time. */ public class BlockingHttpEndpoint implements HttpEndpoint { public static final int DEFAULT_COMMON_TIMEOUT_MS = 5000; private URL url; private int timeout = DEFAULT_COMMON_TIMEOUT_MS; private final ListeningExecutorService requestService; private static final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(BlockingHttpEndpoint.class.getSimpleName() + "-%d") .build(); public BlockingHttpEndpoint(String url, int maxParallelRequests) throws MalformedURLException { this.url = new URL(url); // Create an ExecutorService that blocks after N requests are in flight. Taken from // http://www.springone2gx.com/blog/billy_newport/2011/05/there_s_more_to_configuring_threadpools_than_thread_pool_size LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(maxParallelRequests); ExecutorService executor = new ThreadPoolExecutor(maxParallelRequests, maxParallelRequests, 2L, TimeUnit.MINUTES, workQueue, threadFactory, new ThreadPoolExecutor.CallerRunsPolicy()); requestService = MoreExecutors.listeningDecorator(executor); } @Override public ListenableFuture<HttpResponse> post(String content) throws IOException { HttpURLConnection connection = buildConnection("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); return send(connection, content); } private ListenableFuture<HttpResponse> send(final HttpURLConnection connection, final String content) { return requestService.submit(new Callable<HttpResponse>() { + @Override public HttpResponse call() { try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) { out.writeBytes(content); out.flush(); out.close(); InputStream inputStream = connection.getInputStream(); String response = CharStreams.toString( new InputStreamReader(inputStream, Charsets.UTF_8)); return new HttpResponse(content, response); } catch (IOException e) { throw new RuntimeException(e); } } }); } private HttpURLConnection buildConnection(String httpMethod) throws IOException { HttpURLConnection connection = (HttpURLConnection) this.url.openConnection(); connection.setUseCaches(false); connection.setDoOutput(true); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setRequestMethod(httpMethod); return connection; } }
true
true
private ListenableFuture<HttpResponse> send(final HttpURLConnection connection, final String content) { return requestService.submit(new Callable<HttpResponse>() { public HttpResponse call() { try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) { out.writeBytes(content); out.flush(); out.close(); InputStream inputStream = connection.getInputStream(); String response = CharStreams.toString( new InputStreamReader(inputStream, Charsets.UTF_8)); return new HttpResponse(content, response); } catch (IOException e) { throw new RuntimeException(e); } } }); }
private ListenableFuture<HttpResponse> send(final HttpURLConnection connection, final String content) { return requestService.submit(new Callable<HttpResponse>() { @Override public HttpResponse call() { try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) { out.writeBytes(content); out.flush(); out.close(); InputStream inputStream = connection.getInputStream(); String response = CharStreams.toString( new InputStreamReader(inputStream, Charsets.UTF_8)); return new HttpResponse(content, response); } catch (IOException e) { throw new RuntimeException(e); } } }); }
diff --git a/src/com/herocraftonline/dev/heroes/skill/ActiveSkill.java b/src/com/herocraftonline/dev/heroes/skill/ActiveSkill.java index fd660de8..905b7723 100644 --- a/src/com/herocraftonline/dev/heroes/skill/ActiveSkill.java +++ b/src/com/herocraftonline/dev/heroes/skill/ActiveSkill.java @@ -1,371 +1,372 @@ package com.herocraftonline.dev.heroes.skill; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.herocraftonline.dev.heroes.Heroes; import com.herocraftonline.dev.heroes.api.SkillCompleteEvent; import com.herocraftonline.dev.heroes.api.SkillResult; import com.herocraftonline.dev.heroes.api.SkillResult.ResultType; import com.herocraftonline.dev.heroes.api.SkillUseEvent; import com.herocraftonline.dev.heroes.classes.HeroClass; import com.herocraftonline.dev.heroes.classes.HeroClass.ExperienceType; import com.herocraftonline.dev.heroes.effects.common.SlowEffect; import com.herocraftonline.dev.heroes.hero.Hero; import com.herocraftonline.dev.heroes.hero.HeroManager; import com.herocraftonline.dev.heroes.util.Messaging; import com.herocraftonline.dev.heroes.util.Setting; /** * A skill that performs an action in direct response to a user command. All skill identifiers <i>must</i> * begin with <i>skill</i>, e.g. "skill fireball", in order to be recognized. ActiveSkills define four default settings: * mana, cooldown, experience and usage text. Mana is deducted and a cooldown is activated when the * {@link #use(Hero, String[]) use} method returns <code>true</code>. The {@link #execute(CommandSender, String[]) * execute} automatically handles class, level, mana and cooldown checks on a player attempting to use a skill and * should not be overridden. If all of these checks pass, the <code>use</code> method is called, which should contain * the heart of the skill's behavior that is unique to each skill. * </br> * </br> * <b>Skill Framework:</b> * <ul> * <li>{@link ActiveSkill}</li> * <ul> * <li>{@link ActiveEffectSkill}</li> * <li>{@link TargettedSkill}</li> * </ul> * <li>{@link PassiveSkill}</li> <li>{@link OutsourcedSkill}</li> </ul> */ public abstract class ActiveSkill extends Skill { private String useText; private boolean awardExpOnCast = true; /** * When defining your own constructor, be sure to assign the name, description, usage, argument bounds and * identifier fields as defined in {@link com.herocraftonline.dev.heroes.command.BaseCommand}. Remember that each * identifier must begin with <i>skill</i>. * * @param plugin * the active Heroes instance */ public ActiveSkill(Heroes plugin, String name) { super(plugin, name); } /** * Called whenever a command with an identifier registered to this skill is used. This implementation performs all * necessary class, level, mana and cooldown checks. This method should <i>not</i> be overridden unless you really * know what you're doing. If all checks pass, this method calls {@link #use(Hero, String[]) use}. If * <code>use</code> returns <code>true</code>, this method automatically deducts mana, awards experience and sets a * cooldown. * * @param sender * the <code>CommandSender</code> issuing the command * @param args * the arguments provided with the command */ @SuppressWarnings("deprecation") @Override public boolean execute(CommandSender sender, String identifier, String[] args) { if (!(sender instanceof Player)) { return false; } String name = this.getName(); Player player = (Player) sender; HeroManager hm = plugin.getHeroManager(); Hero hero = hm.getHero(player); if (hero == null) { Messaging.send(player, "You are not a hero."); return false; } HeroClass heroClass = hero.getHeroClass(); HeroClass secondClass = hero.getSecondClass(); if (!heroClass.hasSkill(name) && (secondClass == null || !secondClass.hasSkill(name))) { Messaging.send(player, "Your classes don't have the skill: $1.", name); return true; } int level = SkillConfigManager.getUseSetting(hero, this, Setting.LEVEL, 1, true); if (hero.getSkillLevel(this) < level) { messageAndEvent(hero, new SkillResult(ResultType.LOW_LEVEL, true, level)); return true; } long time = System.currentTimeMillis(); Long global = hero.getCooldown("global"); if (global != null && time < global) { messageAndEvent(hero, new SkillResult(ResultType.ON_GLOBAL_COOLDOWN, true, (global - time) / 1000)); return true; } int skillLevel = hero.getSkillLevel(this); int cooldown = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN, 0, true); double coolReduce = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN_REDUCE, 0.0, false) * skillLevel; cooldown -= (int) coolReduce; if (cooldown > 0) { Long expiry = hero.getCooldown(name); if (expiry != null && time < expiry) { long remaining = expiry - time; messageAndEvent(hero, new SkillResult(ResultType.ON_COOLDOWN, true, name, remaining / 1000)); return false; } } int manaCost = SkillConfigManager.getUseSetting(hero, this, Setting.MANA, 0, true); double manaReduce = SkillConfigManager.getUseSetting(hero, this, Setting.MANA_REDUCE, 0.0, false) * skillLevel; manaCost -= (int) manaReduce; // Reagent stuff ItemStack itemStack = getReagentCost(hero); int healthCost = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST, 0, true); double healthReduce = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST_REDUCE, 0.0, false) * skillLevel; healthCost -= (int) healthReduce; int staminaCost = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA, 0, true); double stamReduce = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA_REDUCE, 0.0, false) * skillLevel; staminaCost -= (int) stamReduce; SkillUseEvent skillEvent = new SkillUseEvent(this, player, hero, manaCost, healthCost, staminaCost, itemStack, args); plugin.getServer().getPluginManager().callEvent(skillEvent); if (skillEvent.isCancelled()) { messageAndEvent(hero, SkillResult.CANCELLED); return true; } // Update manaCost with result of SkillUseEvent manaCost = skillEvent.getManaCost(); if (manaCost > hero.getMana()) { messageAndEvent(hero, SkillResult.LOW_MANA); return true; } // Update healthCost with results of SkillUseEvent healthCost = skillEvent.getHealthCost(); if (healthCost > 0 && hero.getHealth() <= healthCost) { messageAndEvent(hero, SkillResult.LOW_HEALTH); return true; } //Update staminaCost with results of SkilluseEvent staminaCost = skillEvent.getStaminaCost(); if (staminaCost > 0 && hero.getPlayer().getFoodLevel() < staminaCost) { messageAndEvent(hero, SkillResult.LOW_STAMINA); return true; } itemStack = skillEvent.getReagentCost(); if (itemStack != null && itemStack.getAmount() != 0 && !hasReagentCost(player, itemStack)) { String reagentName = itemStack.getType().name().toLowerCase().replace("_", " "); messageAndEvent(hero, new SkillResult(ResultType.MISSING_REAGENT, true, String.valueOf(itemStack.getAmount()), reagentName)); return true; } int delay = SkillConfigManager.getUseSetting(hero, this, Setting.DELAY, 0, true); DelayedSkill dSkill = null; if (delay > 0 && !hm.getDelayedSkills().containsKey(hero)) { if (addDelayedSkill(hero, delay, identifier, args)) { messageAndEvent(hero, SkillResult.START_DELAY); if (Heroes.properties.slowCasting) { hero.addEffect(new SlowEffect(this, "Casting", delay, 2, false, "", "", hero)); } return true; } else { // Generic return if the adding of the delayed skill failed - the failure should send it's own message return true; } } else if (hm.getDelayedSkills().containsKey(hero)) { dSkill = hm.getDelayedSkills().get(hero); if (!dSkill.getSkill().equals(this)) { hm.getDelayedSkills().remove(hero); hero.setDelayedSkill(null); hero.removeEffect(hero.getEffect("Casting")); broadcast(player.getLocation(), "$1 has stopped using $2!", player.getDisplayName(), dSkill.getSkill().getName()); //If the new skill is also a delayed skill lets add it to the warmups and proceed if (delay > 0) { addDelayedSkill(hero, delay, identifier, args); if (Heroes.properties.slowCasting) { hero.addEffect(new SlowEffect(this, "Casting", delay, 2, false, "", "", hero)); } messageAndEvent(hero, SkillResult.START_DELAY); return true; } + dSkill = null; } else if (!dSkill.isReady()) { Messaging.send(sender, "You have already begun to use that skill!"); return true; } else { hero.removeEffect(hero.getEffect("Casting")); hm.addCompletedSkill(hero); } } SkillResult skillResult; if (dSkill instanceof DelayedTargettedSkill) { skillResult = ((TargettedSkill) this).useDelayed(hero, ((DelayedTargettedSkill) dSkill).getTarget(), args); } else { skillResult = use(hero, args); } if (skillResult.type == ResultType.NORMAL){ time = System.currentTimeMillis(); // Set cooldown if (cooldown > 0) { hero.setCooldown(name, time + cooldown); } if (Heroes.properties.globalCooldown > 0) { hero.setCooldown("global", Heroes.properties.globalCooldown + time); } // Award XP for skill usage if (this.awardExpOnCast) { this.awardExp(hero); } // Deduct mana hero.setMana(hero.getMana() - manaCost); if (hero.isVerbose() && manaCost > 0) { Messaging.send(hero.getPlayer(), ChatColor.BLUE + "MANA " + Messaging.createManaBar(hero.getMana())); } // Deduct health if (healthCost > 0) { plugin.getDamageManager().addSpellTarget(player, hero, this); player.damage(healthCost, player); } if (staminaCost > 0) { player.setFoodLevel(player.getFoodLevel() - staminaCost); } // Only charge the item cost if it's non-null if (itemStack != null && itemStack.getAmount() > 0) { player.getInventory().removeItem(itemStack); player.updateInventory(); } } messageAndEvent(hero, skillResult); return true; } /** * Creates and returns a <code>ConfigurationNode</code> containing the default usage text. When using additional * configuration settings in your skills, be sure to override this method to define them with defaults. * * @return a default configuration */ @Override public ConfigurationSection getDefaultConfig() { ConfigurationSection section = super.getDefaultConfig(); section.set(Setting.USE_TEXT.node(), "%hero% used %skill%!"); return section; } protected boolean addDelayedSkill(Hero hero, int delay, final String identifier, final String[] args) { final Player player = hero.getPlayer(); DelayedSkill dSkill = new DelayedSkill(identifier, player, delay, this, args); broadcast(player.getLocation(), "$1 begins to use $2!", player.getDisplayName(), getName()); plugin.getHeroManager().getDelayedSkills().put(hero, dSkill); hero.setDelayedSkill(dSkill); return true; } /** * Returns the text to be displayed when the skill is successfully used. This text is pulled from the * {@link #SETTING_USETEXT} entry in the skill's configuration during initialization. * * @return the usage text */ public String getUseText() { return useText; } /** * Loads and stores the skill's usage text from the configuration. By default, this text is "%hero% used %skill%!" * where %hero% and %skill% are replaced with the Hero's and skill's names, respectively. */ @Override public void init() { String useText = SkillConfigManager.getRaw(this, Setting.USE_TEXT, "%hero% used %skill%!"); useText = useText.replace("%hero%", "$1").replace("%skill%", "$2"); setUseText(useText); } /** * Changes the stored usage text. This can be used to override the message found in the skill's configuration. * * @param useText * the new usage text */ public void setUseText(String useText) { this.useText = useText; } /** * The heart of any ActiveSkill, this method defines what actually happens when the skill is used. See * {@link #execute(CommandSender, String[]) execute} for a brief explanation of the execution process. * * @param hero * the {@link Hero} using the skill * @param args * the arguments provided with the command * @return {@link SkillResult} if skill completed normally, or with an execution error */ public abstract SkillResult use(Hero hero, String[] args); private void awardExp(Hero hero) { if (hero.canGain(ExperienceType.SKILL)) { hero.gainExp(SkillConfigManager.getUseSetting(hero, this, Setting.EXP, 0, false), ExperienceType.SKILL); } } protected void broadcastExecuteText(Hero hero) { Player player = hero.getPlayer(); broadcast(player.getLocation(), getUseText(), player.getDisplayName(), getName()); } /** * Uses the {@link SkillResult} arguments to display a message to the skill-user or ignore the message altogether * * @param hero - {@link Hero} using the skill * @param sr - the {@link SkillResult} that holds the {@link ResultType} and information */ private void messageAndEvent(Hero hero, SkillResult sr) { Player player = hero.getPlayer(); if (sr.showMessage) switch (sr.type) { case INVALID_TARGET: Messaging.send(player, "Invalid Target!"); break; case LOW_HEALTH: Messaging.send(player, "Not enough health!"); break; case LOW_LEVEL: Messaging.send(player, "You must be level $1 to do that.", sr.args[0]); break; case LOW_MANA: Messaging.send(player, "Not enough mana!"); break; case LOW_STAMINA: Messaging.send(player, "You are too fatigued!"); break; case ON_COOLDOWN: Messaging.send(hero.getPlayer(), "Sorry, $1 still has $2 seconds left on cooldown!", sr.args[0], sr.args[1]); break; case ON_GLOBAL_COOLDOWN: Messaging.send(hero.getPlayer(), "Sorry, you must wait $1 seconds longer before using another skill.", sr.args[0]); break; case MISSING_REAGENT: Messaging.send(player, "Sorry, you need to have $1 $2 to use $3!", sr.args[0], sr.args[1], getName()); break; case SKIP_POST_USAGE: return; default: break; } SkillCompleteEvent sce = new SkillCompleteEvent(hero, this, sr); plugin.getServer().getPluginManager().callEvent(sce); } }
true
true
public boolean execute(CommandSender sender, String identifier, String[] args) { if (!(sender instanceof Player)) { return false; } String name = this.getName(); Player player = (Player) sender; HeroManager hm = plugin.getHeroManager(); Hero hero = hm.getHero(player); if (hero == null) { Messaging.send(player, "You are not a hero."); return false; } HeroClass heroClass = hero.getHeroClass(); HeroClass secondClass = hero.getSecondClass(); if (!heroClass.hasSkill(name) && (secondClass == null || !secondClass.hasSkill(name))) { Messaging.send(player, "Your classes don't have the skill: $1.", name); return true; } int level = SkillConfigManager.getUseSetting(hero, this, Setting.LEVEL, 1, true); if (hero.getSkillLevel(this) < level) { messageAndEvent(hero, new SkillResult(ResultType.LOW_LEVEL, true, level)); return true; } long time = System.currentTimeMillis(); Long global = hero.getCooldown("global"); if (global != null && time < global) { messageAndEvent(hero, new SkillResult(ResultType.ON_GLOBAL_COOLDOWN, true, (global - time) / 1000)); return true; } int skillLevel = hero.getSkillLevel(this); int cooldown = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN, 0, true); double coolReduce = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN_REDUCE, 0.0, false) * skillLevel; cooldown -= (int) coolReduce; if (cooldown > 0) { Long expiry = hero.getCooldown(name); if (expiry != null && time < expiry) { long remaining = expiry - time; messageAndEvent(hero, new SkillResult(ResultType.ON_COOLDOWN, true, name, remaining / 1000)); return false; } } int manaCost = SkillConfigManager.getUseSetting(hero, this, Setting.MANA, 0, true); double manaReduce = SkillConfigManager.getUseSetting(hero, this, Setting.MANA_REDUCE, 0.0, false) * skillLevel; manaCost -= (int) manaReduce; // Reagent stuff ItemStack itemStack = getReagentCost(hero); int healthCost = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST, 0, true); double healthReduce = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST_REDUCE, 0.0, false) * skillLevel; healthCost -= (int) healthReduce; int staminaCost = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA, 0, true); double stamReduce = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA_REDUCE, 0.0, false) * skillLevel; staminaCost -= (int) stamReduce; SkillUseEvent skillEvent = new SkillUseEvent(this, player, hero, manaCost, healthCost, staminaCost, itemStack, args); plugin.getServer().getPluginManager().callEvent(skillEvent); if (skillEvent.isCancelled()) { messageAndEvent(hero, SkillResult.CANCELLED); return true; } // Update manaCost with result of SkillUseEvent manaCost = skillEvent.getManaCost(); if (manaCost > hero.getMana()) { messageAndEvent(hero, SkillResult.LOW_MANA); return true; } // Update healthCost with results of SkillUseEvent healthCost = skillEvent.getHealthCost(); if (healthCost > 0 && hero.getHealth() <= healthCost) { messageAndEvent(hero, SkillResult.LOW_HEALTH); return true; } //Update staminaCost with results of SkilluseEvent staminaCost = skillEvent.getStaminaCost(); if (staminaCost > 0 && hero.getPlayer().getFoodLevel() < staminaCost) { messageAndEvent(hero, SkillResult.LOW_STAMINA); return true; } itemStack = skillEvent.getReagentCost(); if (itemStack != null && itemStack.getAmount() != 0 && !hasReagentCost(player, itemStack)) { String reagentName = itemStack.getType().name().toLowerCase().replace("_", " "); messageAndEvent(hero, new SkillResult(ResultType.MISSING_REAGENT, true, String.valueOf(itemStack.getAmount()), reagentName)); return true; } int delay = SkillConfigManager.getUseSetting(hero, this, Setting.DELAY, 0, true); DelayedSkill dSkill = null; if (delay > 0 && !hm.getDelayedSkills().containsKey(hero)) { if (addDelayedSkill(hero, delay, identifier, args)) { messageAndEvent(hero, SkillResult.START_DELAY); if (Heroes.properties.slowCasting) { hero.addEffect(new SlowEffect(this, "Casting", delay, 2, false, "", "", hero)); } return true; } else { // Generic return if the adding of the delayed skill failed - the failure should send it's own message return true; } } else if (hm.getDelayedSkills().containsKey(hero)) { dSkill = hm.getDelayedSkills().get(hero); if (!dSkill.getSkill().equals(this)) { hm.getDelayedSkills().remove(hero); hero.setDelayedSkill(null); hero.removeEffect(hero.getEffect("Casting")); broadcast(player.getLocation(), "$1 has stopped using $2!", player.getDisplayName(), dSkill.getSkill().getName()); //If the new skill is also a delayed skill lets add it to the warmups and proceed if (delay > 0) { addDelayedSkill(hero, delay, identifier, args); if (Heroes.properties.slowCasting) { hero.addEffect(new SlowEffect(this, "Casting", delay, 2, false, "", "", hero)); } messageAndEvent(hero, SkillResult.START_DELAY); return true; } } else if (!dSkill.isReady()) { Messaging.send(sender, "You have already begun to use that skill!"); return true; } else { hero.removeEffect(hero.getEffect("Casting")); hm.addCompletedSkill(hero); } } SkillResult skillResult; if (dSkill instanceof DelayedTargettedSkill) { skillResult = ((TargettedSkill) this).useDelayed(hero, ((DelayedTargettedSkill) dSkill).getTarget(), args); } else { skillResult = use(hero, args); } if (skillResult.type == ResultType.NORMAL){ time = System.currentTimeMillis(); // Set cooldown if (cooldown > 0) { hero.setCooldown(name, time + cooldown); } if (Heroes.properties.globalCooldown > 0) { hero.setCooldown("global", Heroes.properties.globalCooldown + time); } // Award XP for skill usage if (this.awardExpOnCast) { this.awardExp(hero); } // Deduct mana hero.setMana(hero.getMana() - manaCost); if (hero.isVerbose() && manaCost > 0) { Messaging.send(hero.getPlayer(), ChatColor.BLUE + "MANA " + Messaging.createManaBar(hero.getMana())); } // Deduct health if (healthCost > 0) { plugin.getDamageManager().addSpellTarget(player, hero, this); player.damage(healthCost, player); } if (staminaCost > 0) { player.setFoodLevel(player.getFoodLevel() - staminaCost); } // Only charge the item cost if it's non-null if (itemStack != null && itemStack.getAmount() > 0) { player.getInventory().removeItem(itemStack); player.updateInventory(); } } messageAndEvent(hero, skillResult); return true; }
public boolean execute(CommandSender sender, String identifier, String[] args) { if (!(sender instanceof Player)) { return false; } String name = this.getName(); Player player = (Player) sender; HeroManager hm = plugin.getHeroManager(); Hero hero = hm.getHero(player); if (hero == null) { Messaging.send(player, "You are not a hero."); return false; } HeroClass heroClass = hero.getHeroClass(); HeroClass secondClass = hero.getSecondClass(); if (!heroClass.hasSkill(name) && (secondClass == null || !secondClass.hasSkill(name))) { Messaging.send(player, "Your classes don't have the skill: $1.", name); return true; } int level = SkillConfigManager.getUseSetting(hero, this, Setting.LEVEL, 1, true); if (hero.getSkillLevel(this) < level) { messageAndEvent(hero, new SkillResult(ResultType.LOW_LEVEL, true, level)); return true; } long time = System.currentTimeMillis(); Long global = hero.getCooldown("global"); if (global != null && time < global) { messageAndEvent(hero, new SkillResult(ResultType.ON_GLOBAL_COOLDOWN, true, (global - time) / 1000)); return true; } int skillLevel = hero.getSkillLevel(this); int cooldown = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN, 0, true); double coolReduce = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN_REDUCE, 0.0, false) * skillLevel; cooldown -= (int) coolReduce; if (cooldown > 0) { Long expiry = hero.getCooldown(name); if (expiry != null && time < expiry) { long remaining = expiry - time; messageAndEvent(hero, new SkillResult(ResultType.ON_COOLDOWN, true, name, remaining / 1000)); return false; } } int manaCost = SkillConfigManager.getUseSetting(hero, this, Setting.MANA, 0, true); double manaReduce = SkillConfigManager.getUseSetting(hero, this, Setting.MANA_REDUCE, 0.0, false) * skillLevel; manaCost -= (int) manaReduce; // Reagent stuff ItemStack itemStack = getReagentCost(hero); int healthCost = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST, 0, true); double healthReduce = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST_REDUCE, 0.0, false) * skillLevel; healthCost -= (int) healthReduce; int staminaCost = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA, 0, true); double stamReduce = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA_REDUCE, 0.0, false) * skillLevel; staminaCost -= (int) stamReduce; SkillUseEvent skillEvent = new SkillUseEvent(this, player, hero, manaCost, healthCost, staminaCost, itemStack, args); plugin.getServer().getPluginManager().callEvent(skillEvent); if (skillEvent.isCancelled()) { messageAndEvent(hero, SkillResult.CANCELLED); return true; } // Update manaCost with result of SkillUseEvent manaCost = skillEvent.getManaCost(); if (manaCost > hero.getMana()) { messageAndEvent(hero, SkillResult.LOW_MANA); return true; } // Update healthCost with results of SkillUseEvent healthCost = skillEvent.getHealthCost(); if (healthCost > 0 && hero.getHealth() <= healthCost) { messageAndEvent(hero, SkillResult.LOW_HEALTH); return true; } //Update staminaCost with results of SkilluseEvent staminaCost = skillEvent.getStaminaCost(); if (staminaCost > 0 && hero.getPlayer().getFoodLevel() < staminaCost) { messageAndEvent(hero, SkillResult.LOW_STAMINA); return true; } itemStack = skillEvent.getReagentCost(); if (itemStack != null && itemStack.getAmount() != 0 && !hasReagentCost(player, itemStack)) { String reagentName = itemStack.getType().name().toLowerCase().replace("_", " "); messageAndEvent(hero, new SkillResult(ResultType.MISSING_REAGENT, true, String.valueOf(itemStack.getAmount()), reagentName)); return true; } int delay = SkillConfigManager.getUseSetting(hero, this, Setting.DELAY, 0, true); DelayedSkill dSkill = null; if (delay > 0 && !hm.getDelayedSkills().containsKey(hero)) { if (addDelayedSkill(hero, delay, identifier, args)) { messageAndEvent(hero, SkillResult.START_DELAY); if (Heroes.properties.slowCasting) { hero.addEffect(new SlowEffect(this, "Casting", delay, 2, false, "", "", hero)); } return true; } else { // Generic return if the adding of the delayed skill failed - the failure should send it's own message return true; } } else if (hm.getDelayedSkills().containsKey(hero)) { dSkill = hm.getDelayedSkills().get(hero); if (!dSkill.getSkill().equals(this)) { hm.getDelayedSkills().remove(hero); hero.setDelayedSkill(null); hero.removeEffect(hero.getEffect("Casting")); broadcast(player.getLocation(), "$1 has stopped using $2!", player.getDisplayName(), dSkill.getSkill().getName()); //If the new skill is also a delayed skill lets add it to the warmups and proceed if (delay > 0) { addDelayedSkill(hero, delay, identifier, args); if (Heroes.properties.slowCasting) { hero.addEffect(new SlowEffect(this, "Casting", delay, 2, false, "", "", hero)); } messageAndEvent(hero, SkillResult.START_DELAY); return true; } dSkill = null; } else if (!dSkill.isReady()) { Messaging.send(sender, "You have already begun to use that skill!"); return true; } else { hero.removeEffect(hero.getEffect("Casting")); hm.addCompletedSkill(hero); } } SkillResult skillResult; if (dSkill instanceof DelayedTargettedSkill) { skillResult = ((TargettedSkill) this).useDelayed(hero, ((DelayedTargettedSkill) dSkill).getTarget(), args); } else { skillResult = use(hero, args); } if (skillResult.type == ResultType.NORMAL){ time = System.currentTimeMillis(); // Set cooldown if (cooldown > 0) { hero.setCooldown(name, time + cooldown); } if (Heroes.properties.globalCooldown > 0) { hero.setCooldown("global", Heroes.properties.globalCooldown + time); } // Award XP for skill usage if (this.awardExpOnCast) { this.awardExp(hero); } // Deduct mana hero.setMana(hero.getMana() - manaCost); if (hero.isVerbose() && manaCost > 0) { Messaging.send(hero.getPlayer(), ChatColor.BLUE + "MANA " + Messaging.createManaBar(hero.getMana())); } // Deduct health if (healthCost > 0) { plugin.getDamageManager().addSpellTarget(player, hero, this); player.damage(healthCost, player); } if (staminaCost > 0) { player.setFoodLevel(player.getFoodLevel() - staminaCost); } // Only charge the item cost if it's non-null if (itemStack != null && itemStack.getAmount() > 0) { player.getInventory().removeItem(itemStack); player.updateInventory(); } } messageAndEvent(hero, skillResult); return true; }
diff --git a/org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/internal/swt/SWTGLCanvas.java b/org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/internal/swt/SWTGLCanvas.java index 6868fe38b..d7f3d2835 100644 --- a/org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/internal/swt/SWTGLCanvas.java +++ b/org.caleydo.core/src/org/caleydo/core/view/opengl/canvas/internal/swt/SWTGLCanvas.java @@ -1,348 +1,352 @@ /******************************************************************************* * Caleydo - visualization for molecular biology - http://caleydo.org * * Copyright(C) 2005, 2012 Graz University of Technology, Marc Streit, Alexander * Lex, Christian Partl, Johannes Kepler University Linz </p> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/> *******************************************************************************/ package org.caleydo.core.view.opengl.canvas.internal.swt; import java.util.Deque; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedDeque; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLEventListener; import org.caleydo.core.util.base.ILabelProvider; import org.caleydo.core.view.opengl.canvas.IGLCanvas; import org.caleydo.core.view.opengl.canvas.IGLFocusListener; import org.caleydo.core.view.opengl.canvas.IGLKeyListener; import org.caleydo.core.view.opengl.canvas.IGLMouseListener; import org.caleydo.core.view.opengl.picking.IPickingListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import com.jogamp.opengl.swt.GLCanvas; /** * @author Samuel Gratzl * */ final class SWTGLCanvas implements IGLCanvas { private final GLCanvas canvas; private final Map<Object, Object> listenerMapping = new ConcurrentHashMap<>(); private final Deque<GLEventListener> glEventListeners = new ConcurrentLinkedDeque<>(); SWTGLCanvas(GLCanvas canvas) { this.canvas = canvas; canvas.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { // problem if the canvas is not the the top level widget, only release(...) will be called -> call it // manually on disposing - if (!PlatformUI.getWorkbench().isClosing()) - e.widget.dispose(); + if (!PlatformUI.getWorkbench().isClosing()) { + // e.widget.dispose(); + fireDispose(SWTGLCanvas.this.canvas); + SWTGLCanvas.this.canvas.getContext().destroy(); + SWTGLCanvas.this.canvas.setRealized(false); + } } }); // wrap listeners for manually sending reshape events canvas.addGLEventListener(new GLEventListener() { int w = -1, h = -1; @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { this.w = width; this.h = height; fireReshape(drawable, x, y, width, height); } @Override public void init(GLAutoDrawable drawable) { this.w = drawable.getWidth(); this.h = drawable.getHeight(); fireInit(drawable); } @Override public void dispose(GLAutoDrawable drawable) { fireDispose(drawable); } @Override public void display(GLAutoDrawable drawable) { // manually fire reshape events if (w != drawable.getWidth() || h != drawable.getHeight() && w != -1) { w = drawable.getWidth(); h = drawable.getHeight(); - fireReshape(drawable, 0,0, drawable.getWidth(), drawable.getHeight()); + fireReshape(drawable, 0, 0, drawable.getWidth(), drawable.getHeight()); } fireDisplay(drawable); } }); } @Override public IPickingListener createTooltip(ILabelProvider label) { return new SWTTooltipManager(canvas, label); } @Override public IPickingListener createTooltip(String label) { return new SWTTooltipManager(canvas, label); } /** * @param drawable */ void fireDisplay(GLAutoDrawable drawable) { for (GLEventListener l : glEventListeners) l.display(drawable); } void fireDispose(GLAutoDrawable drawable) { for (GLEventListener l : glEventListeners) l.dispose(drawable); } void fireInit(GLAutoDrawable drawable) { for (GLEventListener l : glEventListeners) l.init(drawable); } void fireReshape(GLAutoDrawable drawable, int x, int y, int width, int height) { for (GLEventListener l : glEventListeners) l.reshape(drawable, x, y, width, height); } /** * @return the canvas */ GLCanvas getCanvas() { return canvas; } /* * (non-Javadoc) * * @see * org.caleydo.core.view.opengl.canvas.IGLCanvas#addMouseListener(org.caleydo.core.view.opengl.canvas.IGLMouseListener * ) */ @Override public void addMouseListener(final IGLMouseListener listener) { getDisplay().syncExec(new Runnable() { @Override public void run() { SWTMouseAdapter a = new SWTMouseAdapter(listener); listenerMapping.put(listener, a); canvas.addMouseListener(a); canvas.addMouseMoveListener(a); canvas.addMouseWheelListener(a); } }); } /* * (non-Javadoc) * * @see org.caleydo.core.view.opengl.canvas.IGLCanvas#removeMouseListener(org.caleydo.core.view.opengl.canvas. * IGLMouseListener) */ @Override public void removeMouseListener(final IGLMouseListener listener) { getDisplay().syncExec(new Runnable() { @Override public void run() { SWTMouseAdapter a = (SWTMouseAdapter) listenerMapping.remove(listener); if (a == null) return; canvas.removeMouseListener(a); canvas.removeMouseMoveListener(a); canvas.removeMouseWheelListener(a); } }); } /* * (non-Javadoc) * * @see * org.caleydo.core.view.opengl.canvas.IGLCanvas#addFocusListener(org.caleydo.core.view.opengl.canvas.IGLFocusListener * ) */ @Override public void addFocusListener(final IGLFocusListener listener) { getDisplay().syncExec(new Runnable() { @Override public void run() { SWTFocusAdapter a = new SWTFocusAdapter(listener); listenerMapping.put(listener, a); canvas.addFocusListener(a); } }); } /* * (non-Javadoc) * * @see org.caleydo.core.view.opengl.canvas.IGLCanvas#removeFocusListener(org.caleydo.core.view.opengl.canvas. * IGLFocusListener) */ @Override public void removeFocusListener(final IGLFocusListener listener) { getDisplay().syncExec(new Runnable() { @Override public void run() { SWTFocusAdapter a = (SWTFocusAdapter) listenerMapping.remove(listener); if (a == null) return; canvas.removeFocusListener(a); } }); } /* * (non-Javadoc) * * @see org.caleydo.core.view.opengl.canvas.IGLCanvas#requestFocus() */ @Override public void requestFocus() { getDisplay().asyncExec(new Runnable() { @Override public void run() { canvas.forceFocus(); } }); } protected Display getDisplay() { return canvas.getDisplay(); } /* * (non-Javadoc) * * @see * org.caleydo.core.view.opengl.canvas.IGLCanvas#addKeyListener(org.caleydo.core.view.opengl.canvas.IGLKeyListener) */ @Override public void addKeyListener(final IGLKeyListener listener) { getDisplay().syncExec(new Runnable() { @Override public void run() { SWTKeyAdapter a = new SWTKeyAdapter(listener); listenerMapping.put(listener, a); canvas.addKeyListener(a); } }); } /* * (non-Javadoc) * * @see * org.caleydo.core.view.opengl.canvas.IGLCanvas#removeKeyListener(org.caleydo.core.view.opengl.canvas.IGLKeyListener * ) */ @Override public void removeKeyListener(final IGLKeyListener listener) { getDisplay().syncExec(new Runnable() { @Override public void run() { SWTKeyAdapter a = (SWTKeyAdapter) listenerMapping.remove(listener); if (a == null) return; canvas.removeKeyListener(a); } }); } /* * (non-Javadoc) * * @see org.caleydo.core.view.opengl.canvas.IGLCanvas#addGLEventListener(javax.media.opengl.GLEventListener) */ @Override public void addGLEventListener(GLEventListener listener) { glEventListeners.add(listener); } /* * (non-Javadoc) * * @see org.caleydo.core.view.opengl.canvas.IGLCanvas#removeGLEventListener(javax.media.opengl.GLEventListener) */ @Override public void removeGLEventListener(GLEventListener listener) { glEventListeners.remove(listener); } /* * (non-Javadoc) * * @see org.caleydo.core.view.opengl.canvas.IGLCanvas#getWidth() */ @Override public int getWidth() { return canvas.getWidth(); } /* * (non-Javadoc) * * @see org.caleydo.core.view.opengl.canvas.IGLCanvas#getHeight() */ @Override public int getHeight() { return canvas.getHeight(); } /* * (non-Javadoc) * * @see org.caleydo.core.view.opengl.canvas.IGLCanvas#asGLAutoDrawAble() */ @Override public GLAutoDrawable asGLAutoDrawAble() { return canvas; } /* * (non-Javadoc) * * @see org.caleydo.core.view.opengl.canvas.IGLCanvas#asComposite() */ @Override public Composite asComposite() { return canvas; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "AWTGLCanvas of " + canvas.toString(); } }
false
true
SWTGLCanvas(GLCanvas canvas) { this.canvas = canvas; canvas.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { // problem if the canvas is not the the top level widget, only release(...) will be called -> call it // manually on disposing if (!PlatformUI.getWorkbench().isClosing()) e.widget.dispose(); } }); // wrap listeners for manually sending reshape events canvas.addGLEventListener(new GLEventListener() { int w = -1, h = -1; @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { this.w = width; this.h = height; fireReshape(drawable, x, y, width, height); } @Override public void init(GLAutoDrawable drawable) { this.w = drawable.getWidth(); this.h = drawable.getHeight(); fireInit(drawable); } @Override public void dispose(GLAutoDrawable drawable) { fireDispose(drawable); } @Override public void display(GLAutoDrawable drawable) { // manually fire reshape events if (w != drawable.getWidth() || h != drawable.getHeight() && w != -1) { w = drawable.getWidth(); h = drawable.getHeight(); fireReshape(drawable, 0,0, drawable.getWidth(), drawable.getHeight()); } fireDisplay(drawable); } }); }
SWTGLCanvas(GLCanvas canvas) { this.canvas = canvas; canvas.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { // problem if the canvas is not the the top level widget, only release(...) will be called -> call it // manually on disposing if (!PlatformUI.getWorkbench().isClosing()) { // e.widget.dispose(); fireDispose(SWTGLCanvas.this.canvas); SWTGLCanvas.this.canvas.getContext().destroy(); SWTGLCanvas.this.canvas.setRealized(false); } } }); // wrap listeners for manually sending reshape events canvas.addGLEventListener(new GLEventListener() { int w = -1, h = -1; @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { this.w = width; this.h = height; fireReshape(drawable, x, y, width, height); } @Override public void init(GLAutoDrawable drawable) { this.w = drawable.getWidth(); this.h = drawable.getHeight(); fireInit(drawable); } @Override public void dispose(GLAutoDrawable drawable) { fireDispose(drawable); } @Override public void display(GLAutoDrawable drawable) { // manually fire reshape events if (w != drawable.getWidth() || h != drawable.getHeight() && w != -1) { w = drawable.getWidth(); h = drawable.getHeight(); fireReshape(drawable, 0, 0, drawable.getWidth(), drawable.getHeight()); } fireDisplay(drawable); } }); }
diff --git a/src/edu/umn/genomics/table/TableViewPreferenceEditor.java b/src/edu/umn/genomics/table/TableViewPreferenceEditor.java index 1776d86..b73cfcc 100644 --- a/src/edu/umn/genomics/table/TableViewPreferenceEditor.java +++ b/src/edu/umn/genomics/table/TableViewPreferenceEditor.java @@ -1,185 +1,192 @@ /* * @(#) $RCSfile: TableView.java,v $ $Revision: 1.51 $ $Date: 2004/08/02 20:23:46 $ $Name: TableView1_3 $ * * Center for Computational Genomics and Bioinformatics * Academic Health Center, University of Minnesota * Copyright (c) 2000-2002. The Regents of the University of Minnesota * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * see: http://www.gnu.org/copyleft/gpl.html * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ package edu.umn.genomics.table; import java.io.Serializable; // import java.io.*; // import java.net.*; import java.awt.Component; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; import java.lang.reflect.*; import java.util.*; import java.util.prefs.*; import edu.umn.genomics.component.table.*; import edu.umn.genomics.graph.*; import edu.umn.genomics.graph.swing.DrawableIcon; public class TableViewPreferenceEditor extends JFrame { PreferenceTableModel ptm = null; Map<Class,TableCellRenderer> rendererMap = new HashMap<Class,TableCellRenderer>(); Map<Class,TableCellEditor> editorMap = new HashMap<Class,TableCellEditor>(); class DrawableListCellRenderer extends JLabel implements ListCellRenderer { DrawableIcon icon = new DrawableIcon(12,12,new DrawableO(3,true)); public DrawableListCellRenderer() { setOpaque(true); setHorizontalAlignment(CENTER); setVerticalAlignment(CENTER); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } if (value instanceof Drawable) { icon.setDrawable((Drawable)value); setIcon(icon); } else { System.err.println("No icon " + value); setIcon(null); } setText(value != null ? value.toString() : ""); return this; } } DrawableListCellRenderer drawableListCellRenderer = new DrawableListCellRenderer(); public void setDefaultPreferences() throws Exception { if (ptm != null) { ptm.useDefaultValues(); } } public TableViewPreferenceEditor() throws BackingStoreException { super("Preference Editor"); ptm = new PreferenceTableModel(); JComboBox drawableChoices = new JComboBox(); drawableChoices.addItem(new DrawableT(1)); drawableChoices.addItem(new DrawableT(2)); drawableChoices.addItem(new DrawableT(3)); drawableChoices.addItem(new DrawableT(4)); drawableChoices.addItem(new DrawableT(5)); drawableChoices.addItem(new DrawableX(1)); drawableChoices.addItem(new DrawableX(2)); drawableChoices.addItem(new DrawableX(3)); drawableChoices.addItem(new DrawableX(4)); drawableChoices.addItem(new DrawableX(5)); drawableChoices.addItem(new DrawableO(1,false)); drawableChoices.addItem(new DrawableO(2,false)); drawableChoices.addItem(new DrawableO(3,false)); drawableChoices.addItem(new DrawableO(1,true)); drawableChoices.addItem(new DrawableO(2,true)); drawableChoices.addItem(new DrawableO(3,true)); drawableChoices.addItem(new DrawableBox(1,false)); drawableChoices.addItem(new DrawableBox(2,false)); drawableChoices.addItem(new DrawableBox(3,false)); drawableChoices.addItem(new DrawableBox(1,true)); drawableChoices.addItem(new DrawableBox(2,true)); drawableChoices.addItem(new DrawableBox(3,true)); drawableChoices.addItem(new DrawableStar(4,3)); drawableChoices.addItem(new DrawableStar(4,4)); drawableChoices.addItem(new DrawableStar(4,5)); drawableChoices.addItem(new DrawableStar(4,6)); drawableChoices.addItem(new DrawableStar(4,7)); drawableChoices.addItem(new DrawableStar(4,8)); drawableChoices.addItem(new DrawableStar(4,9)); drawableChoices.setRenderer(drawableListCellRenderer); rendererMap.put(java.awt.Color.class,new ColorRenderer()); editorMap.put(java.awt.Color.class,new ColorEditor()); editorMap.put(edu.umn.genomics.graph.Drawable.class,new DefaultCellEditor(drawableChoices)); JTable table = new JTable(ptm) { public TableCellEditor getCellEditor(int row, int column) { if (column == 2) { Object value = getValueAt(row,column); if (value != null) { for (Class cellClass : editorMap.keySet()) { if (cellClass.isInstance(value)) { return editorMap.get(cellClass); } } } } return super.getCellEditor(row, column); } }; + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + TableColumn col = table.getColumnModel().getColumn(0); + col.setPreferredWidth(100); + col = table.getColumnModel().getColumn(1); + col.setPreferredWidth(100); + col = table.getColumnModel().getColumn(2); + col.setPreferredWidth(250); table.setDefaultRenderer(Class.class, new ClassNameRenderer()); table.setDefaultRenderer(String.class, new DefaultTableCellRenderer()); table.setDefaultRenderer(Object.class, new DelegatingRenderer(rendererMap)); // table.getColumnModel().getColumn(2).setCellEditor(new DelegatingEditor(editorMap)); // table.getColumnModel().getColumn(2).setCellEditor(new ColorEditor()); // table.setDefaultEditor(java.awt.Color.class,new ColorEditor()); JScrollPane jsp = new JScrollPane(table); add(jsp); JToolBar tb = new JToolBar(); tb.setFloatable(false); JButton btn; // Defaults btn = new JButton("Close"); btn.setToolTipText("Close this window."); btn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { ((JFrame)((JButton)e.getSource()).getTopLevelAncestor()).dispose(); } catch (Exception ex) { ExceptionHandler.popupException(""+ex); } } } ); tb.add(btn); btn = new JButton("Set Defaults"); btn.setToolTipText("Set Preferences to Application Defaults"); btn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { setDefaultPreferences(); } catch (Exception ex) { ExceptionHandler.popupException(""+ex); } } } ); tb.add(btn); // Import // Export add(tb,BorderLayout.NORTH); pack(); setVisible(true); } }
true
true
public TableViewPreferenceEditor() throws BackingStoreException { super("Preference Editor"); ptm = new PreferenceTableModel(); JComboBox drawableChoices = new JComboBox(); drawableChoices.addItem(new DrawableT(1)); drawableChoices.addItem(new DrawableT(2)); drawableChoices.addItem(new DrawableT(3)); drawableChoices.addItem(new DrawableT(4)); drawableChoices.addItem(new DrawableT(5)); drawableChoices.addItem(new DrawableX(1)); drawableChoices.addItem(new DrawableX(2)); drawableChoices.addItem(new DrawableX(3)); drawableChoices.addItem(new DrawableX(4)); drawableChoices.addItem(new DrawableX(5)); drawableChoices.addItem(new DrawableO(1,false)); drawableChoices.addItem(new DrawableO(2,false)); drawableChoices.addItem(new DrawableO(3,false)); drawableChoices.addItem(new DrawableO(1,true)); drawableChoices.addItem(new DrawableO(2,true)); drawableChoices.addItem(new DrawableO(3,true)); drawableChoices.addItem(new DrawableBox(1,false)); drawableChoices.addItem(new DrawableBox(2,false)); drawableChoices.addItem(new DrawableBox(3,false)); drawableChoices.addItem(new DrawableBox(1,true)); drawableChoices.addItem(new DrawableBox(2,true)); drawableChoices.addItem(new DrawableBox(3,true)); drawableChoices.addItem(new DrawableStar(4,3)); drawableChoices.addItem(new DrawableStar(4,4)); drawableChoices.addItem(new DrawableStar(4,5)); drawableChoices.addItem(new DrawableStar(4,6)); drawableChoices.addItem(new DrawableStar(4,7)); drawableChoices.addItem(new DrawableStar(4,8)); drawableChoices.addItem(new DrawableStar(4,9)); drawableChoices.setRenderer(drawableListCellRenderer); rendererMap.put(java.awt.Color.class,new ColorRenderer()); editorMap.put(java.awt.Color.class,new ColorEditor()); editorMap.put(edu.umn.genomics.graph.Drawable.class,new DefaultCellEditor(drawableChoices)); JTable table = new JTable(ptm) { public TableCellEditor getCellEditor(int row, int column) { if (column == 2) { Object value = getValueAt(row,column); if (value != null) { for (Class cellClass : editorMap.keySet()) { if (cellClass.isInstance(value)) { return editorMap.get(cellClass); } } } } return super.getCellEditor(row, column); } }; table.setDefaultRenderer(Class.class, new ClassNameRenderer()); table.setDefaultRenderer(String.class, new DefaultTableCellRenderer()); table.setDefaultRenderer(Object.class, new DelegatingRenderer(rendererMap)); // table.getColumnModel().getColumn(2).setCellEditor(new DelegatingEditor(editorMap)); // table.getColumnModel().getColumn(2).setCellEditor(new ColorEditor()); // table.setDefaultEditor(java.awt.Color.class,new ColorEditor()); JScrollPane jsp = new JScrollPane(table); add(jsp); JToolBar tb = new JToolBar(); tb.setFloatable(false); JButton btn; // Defaults btn = new JButton("Close"); btn.setToolTipText("Close this window."); btn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { ((JFrame)((JButton)e.getSource()).getTopLevelAncestor()).dispose(); } catch (Exception ex) { ExceptionHandler.popupException(""+ex); } } } ); tb.add(btn); btn = new JButton("Set Defaults"); btn.setToolTipText("Set Preferences to Application Defaults"); btn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { setDefaultPreferences(); } catch (Exception ex) { ExceptionHandler.popupException(""+ex); } } } ); tb.add(btn); // Import // Export add(tb,BorderLayout.NORTH); pack(); setVisible(true); }
public TableViewPreferenceEditor() throws BackingStoreException { super("Preference Editor"); ptm = new PreferenceTableModel(); JComboBox drawableChoices = new JComboBox(); drawableChoices.addItem(new DrawableT(1)); drawableChoices.addItem(new DrawableT(2)); drawableChoices.addItem(new DrawableT(3)); drawableChoices.addItem(new DrawableT(4)); drawableChoices.addItem(new DrawableT(5)); drawableChoices.addItem(new DrawableX(1)); drawableChoices.addItem(new DrawableX(2)); drawableChoices.addItem(new DrawableX(3)); drawableChoices.addItem(new DrawableX(4)); drawableChoices.addItem(new DrawableX(5)); drawableChoices.addItem(new DrawableO(1,false)); drawableChoices.addItem(new DrawableO(2,false)); drawableChoices.addItem(new DrawableO(3,false)); drawableChoices.addItem(new DrawableO(1,true)); drawableChoices.addItem(new DrawableO(2,true)); drawableChoices.addItem(new DrawableO(3,true)); drawableChoices.addItem(new DrawableBox(1,false)); drawableChoices.addItem(new DrawableBox(2,false)); drawableChoices.addItem(new DrawableBox(3,false)); drawableChoices.addItem(new DrawableBox(1,true)); drawableChoices.addItem(new DrawableBox(2,true)); drawableChoices.addItem(new DrawableBox(3,true)); drawableChoices.addItem(new DrawableStar(4,3)); drawableChoices.addItem(new DrawableStar(4,4)); drawableChoices.addItem(new DrawableStar(4,5)); drawableChoices.addItem(new DrawableStar(4,6)); drawableChoices.addItem(new DrawableStar(4,7)); drawableChoices.addItem(new DrawableStar(4,8)); drawableChoices.addItem(new DrawableStar(4,9)); drawableChoices.setRenderer(drawableListCellRenderer); rendererMap.put(java.awt.Color.class,new ColorRenderer()); editorMap.put(java.awt.Color.class,new ColorEditor()); editorMap.put(edu.umn.genomics.graph.Drawable.class,new DefaultCellEditor(drawableChoices)); JTable table = new JTable(ptm) { public TableCellEditor getCellEditor(int row, int column) { if (column == 2) { Object value = getValueAt(row,column); if (value != null) { for (Class cellClass : editorMap.keySet()) { if (cellClass.isInstance(value)) { return editorMap.get(cellClass); } } } } return super.getCellEditor(row, column); } }; table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); TableColumn col = table.getColumnModel().getColumn(0); col.setPreferredWidth(100); col = table.getColumnModel().getColumn(1); col.setPreferredWidth(100); col = table.getColumnModel().getColumn(2); col.setPreferredWidth(250); table.setDefaultRenderer(Class.class, new ClassNameRenderer()); table.setDefaultRenderer(String.class, new DefaultTableCellRenderer()); table.setDefaultRenderer(Object.class, new DelegatingRenderer(rendererMap)); // table.getColumnModel().getColumn(2).setCellEditor(new DelegatingEditor(editorMap)); // table.getColumnModel().getColumn(2).setCellEditor(new ColorEditor()); // table.setDefaultEditor(java.awt.Color.class,new ColorEditor()); JScrollPane jsp = new JScrollPane(table); add(jsp); JToolBar tb = new JToolBar(); tb.setFloatable(false); JButton btn; // Defaults btn = new JButton("Close"); btn.setToolTipText("Close this window."); btn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { ((JFrame)((JButton)e.getSource()).getTopLevelAncestor()).dispose(); } catch (Exception ex) { ExceptionHandler.popupException(""+ex); } } } ); tb.add(btn); btn = new JButton("Set Defaults"); btn.setToolTipText("Set Preferences to Application Defaults"); btn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { try { setDefaultPreferences(); } catch (Exception ex) { ExceptionHandler.popupException(""+ex); } } } ); tb.add(btn); // Import // Export add(tb,BorderLayout.NORTH); pack(); setVisible(true); }
diff --git a/JavaArchive.java b/JavaArchive.java index babeec0..b7ea00f 100644 --- a/JavaArchive.java +++ b/JavaArchive.java @@ -1,103 +1,104 @@ /* * Copyright (c) 2011 Xamarin Inc. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package jar2xml; import java.io.File; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.jar.JarFile; import java.util.jar.JarEntry; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import org.objectweb.asm.*; import org.objectweb.asm.tree.*; public class JavaArchive { private List<JarFile> files = new ArrayList<JarFile> (); private ClassLoader loader; public JavaArchive (List<String> filenames, List<String> additionalJars) throws Exception { List<URL> urls = new ArrayList<URL> (); for (String filename : filenames) { files.add (new JarFile (filename)); urls.add (new File (filename).getAbsoluteFile ().toURL ()); } for (String additionalJar : additionalJars) urls.add (new File (additionalJar).getAbsoluteFile ().toURL ()); URL [] urlsArray = new URL [urls.size ()]; urls.toArray (urlsArray); loader = new URLClassLoader (urlsArray, JavaArchive.class.getClassLoader ()); } public List<JavaPackage> getPackages () { HashMap<String, JavaPackage> packages = new HashMap <String, JavaPackage> (); for (JarFile file : files) getPackages (packages, file); ArrayList<JavaPackage> result = new ArrayList<JavaPackage> (packages.values ()); Collections.sort (result); return result; } void getPackages (HashMap<String, JavaPackage> packages, JarFile file) { Enumeration<JarEntry> entries = file.entries (); while (entries.hasMoreElements ()) { JarEntry entry = entries.nextElement (); String name = entry.getName (); if (name.endsWith (".class")) { name = name.substring (0, name.length () - 6); try { InputStream stream = file.getInputStream (entry); ClassReader reader = new ClassReader (stream); ClassNode node = new ClassNode (); reader.accept (node, 0); JavaClass.asmClasses.put (node.name, node); Class c = loader.loadClass (name.replace ('/', '.')); //String pkgname = c.getPackage ().getName (); String pkgname = name.substring (0, name.lastIndexOf ('/')).replace ('/', '.'); JavaPackage pkg = packages.get (pkgname); if (pkg == null) { pkg = new JavaPackage (pkgname); packages.put (pkgname, pkg); } pkg.addClass (new JavaClass (c, node)); } catch (Throwable t) { + t.printStackTrace (); System.err.println ("warning J2X9001: Couldn't load class " + name + " : " + t); } } } } }
true
true
void getPackages (HashMap<String, JavaPackage> packages, JarFile file) { Enumeration<JarEntry> entries = file.entries (); while (entries.hasMoreElements ()) { JarEntry entry = entries.nextElement (); String name = entry.getName (); if (name.endsWith (".class")) { name = name.substring (0, name.length () - 6); try { InputStream stream = file.getInputStream (entry); ClassReader reader = new ClassReader (stream); ClassNode node = new ClassNode (); reader.accept (node, 0); JavaClass.asmClasses.put (node.name, node); Class c = loader.loadClass (name.replace ('/', '.')); //String pkgname = c.getPackage ().getName (); String pkgname = name.substring (0, name.lastIndexOf ('/')).replace ('/', '.'); JavaPackage pkg = packages.get (pkgname); if (pkg == null) { pkg = new JavaPackage (pkgname); packages.put (pkgname, pkg); } pkg.addClass (new JavaClass (c, node)); } catch (Throwable t) { System.err.println ("warning J2X9001: Couldn't load class " + name + " : " + t); } } } }
void getPackages (HashMap<String, JavaPackage> packages, JarFile file) { Enumeration<JarEntry> entries = file.entries (); while (entries.hasMoreElements ()) { JarEntry entry = entries.nextElement (); String name = entry.getName (); if (name.endsWith (".class")) { name = name.substring (0, name.length () - 6); try { InputStream stream = file.getInputStream (entry); ClassReader reader = new ClassReader (stream); ClassNode node = new ClassNode (); reader.accept (node, 0); JavaClass.asmClasses.put (node.name, node); Class c = loader.loadClass (name.replace ('/', '.')); //String pkgname = c.getPackage ().getName (); String pkgname = name.substring (0, name.lastIndexOf ('/')).replace ('/', '.'); JavaPackage pkg = packages.get (pkgname); if (pkg == null) { pkg = new JavaPackage (pkgname); packages.put (pkgname, pkg); } pkg.addClass (new JavaClass (c, node)); } catch (Throwable t) { t.printStackTrace (); System.err.println ("warning J2X9001: Couldn't load class " + name + " : " + t); } } } }
diff --git a/src/main/java/org/jahia/services/usermanager/ldap/JahiaLDAPConfigManager.java b/src/main/java/org/jahia/services/usermanager/ldap/JahiaLDAPConfigManager.java index 5d086b4..b4e076e 100644 --- a/src/main/java/org/jahia/services/usermanager/ldap/JahiaLDAPConfigManager.java +++ b/src/main/java/org/jahia/services/usermanager/ldap/JahiaLDAPConfigManager.java @@ -1,37 +1,40 @@ package org.jahia.services.usermanager.ldap; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Unbind configuration at module start/stop */ public class JahiaLDAPConfigManager { public static final Logger logger = LoggerFactory.getLogger(JahiaLDAPConfigFactory.class); private ConfigurationAdmin configurationAdmin; public void start() { unbindConfiguration(); } public void stop() { unbindConfiguration(); } private void unbindConfiguration() { try { - for (Configuration configuration : configurationAdmin.listConfigurations("(service.factoryPid=org.jahia.services.usermanager.ldap)")) { - configuration.setBundleLocation(null); + Configuration[] configurations = configurationAdmin.listConfigurations("(service.factoryPid=org.jahia.services.usermanager.ldap)"); + if (configurations != null) { + for (Configuration configuration : configurations) { + configuration.setBundleLocation(null); + } } } catch (Exception e) { logger.error("Cannot unbind configurations",e); } } public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) { this.configurationAdmin = configurationAdmin; } }
true
true
private void unbindConfiguration() { try { for (Configuration configuration : configurationAdmin.listConfigurations("(service.factoryPid=org.jahia.services.usermanager.ldap)")) { configuration.setBundleLocation(null); } } catch (Exception e) { logger.error("Cannot unbind configurations",e); } }
private void unbindConfiguration() { try { Configuration[] configurations = configurationAdmin.listConfigurations("(service.factoryPid=org.jahia.services.usermanager.ldap)"); if (configurations != null) { for (Configuration configuration : configurations) { configuration.setBundleLocation(null); } } } catch (Exception e) { logger.error("Cannot unbind configurations",e); } }
diff --git a/src/Inventory.java b/src/Inventory.java index 4b3c4b5..7b6a552 100644 --- a/src/Inventory.java +++ b/src/Inventory.java @@ -1,75 +1,75 @@ /** * A class that handles the players inventory. * * @author Bobby Henley * @version 1 */ import java.util.ArrayList; import java.util.HashMap; import java.util.Map.Entry; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SpriteSheet; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class Inventory implements Menu { private int width = 550, height = 400; private int INV_OFFSET_X = width/2 - 30, INV_OFFSET_Y = height/2 - 30; private boolean visible; private HashMap<String, Integer> playerStats; private Player ply; private GameConfig invMenu; public Inventory(Player p) { ply = p; playerStats = p.getStats(); invMenu = new GameConfig("./loc/inventorytext.json"); } @Override public void setVisible(boolean b) { visible = b; } @Override public boolean isOpen() { return visible; } @Override public void draw(Graphics g) { if(visible) { g.setColor(Color.black); g.fillRect(ply.getX() - INV_OFFSET_X, ply.getY() - INV_OFFSET_Y, width, height); for(int i = 0; i < 320; i+=32) { for(int j = 0; j < height - 80; j+=32) { g.setColor(Color.white); g.drawRect(i + ply.getX() - INV_OFFSET_X, (j + 80) + ply.getY() - INV_OFFSET_Y, 32, 32); } } for(int x = 0; x < 10; x+=32) { for(int y = 0; y < 10; x+=32) { - g.drawImage(ply.getPlayerItems().get(x).getItemImage().getScaledCopy(32, 32), x + ply.getX() - INV_OFFSET_X, (y + 80) + ply.getY() - INV_OFFSET_Y); + g.drawImage(ply.getPlayerItems().get(x).getImage().getScaledCopy(32, 32), x + ply.getX() - INV_OFFSET_X, (y + 80) + ply.getY() - INV_OFFSET_Y); } } // "" + ply.getStat( /*for (Entry<String, JsonElement> ele : invMenu.getObject().entrySet()) { g.drawString(ele.getValue().getAsString().replace("%n", ele.getKey().split("#(.*)")[0]), 50, 50); }*/ g.drawString(invMenu.getValueAsString("#title"), 320/2 - 40 + ply.getX() - INV_OFFSET_X, 10 + ply.getY() - INV_OFFSET_Y); g.drawString(invMenu.getValueAsString("#stat"), (width - 130) + ply.getX() - INV_OFFSET_X, 10 + ply.getY() - INV_OFFSET_Y); g.drawRect(ply.getX() - INV_OFFSET_X, ply.getY() - INV_OFFSET_Y, width, height); } } }
true
true
public void draw(Graphics g) { if(visible) { g.setColor(Color.black); g.fillRect(ply.getX() - INV_OFFSET_X, ply.getY() - INV_OFFSET_Y, width, height); for(int i = 0; i < 320; i+=32) { for(int j = 0; j < height - 80; j+=32) { g.setColor(Color.white); g.drawRect(i + ply.getX() - INV_OFFSET_X, (j + 80) + ply.getY() - INV_OFFSET_Y, 32, 32); } } for(int x = 0; x < 10; x+=32) { for(int y = 0; y < 10; x+=32) { g.drawImage(ply.getPlayerItems().get(x).getItemImage().getScaledCopy(32, 32), x + ply.getX() - INV_OFFSET_X, (y + 80) + ply.getY() - INV_OFFSET_Y); } } // "" + ply.getStat( /*for (Entry<String, JsonElement> ele : invMenu.getObject().entrySet()) { g.drawString(ele.getValue().getAsString().replace("%n", ele.getKey().split("#(.*)")[0]), 50, 50); }*/ g.drawString(invMenu.getValueAsString("#title"), 320/2 - 40 + ply.getX() - INV_OFFSET_X, 10 + ply.getY() - INV_OFFSET_Y); g.drawString(invMenu.getValueAsString("#stat"), (width - 130) + ply.getX() - INV_OFFSET_X, 10 + ply.getY() - INV_OFFSET_Y); g.drawRect(ply.getX() - INV_OFFSET_X, ply.getY() - INV_OFFSET_Y, width, height); }
public void draw(Graphics g) { if(visible) { g.setColor(Color.black); g.fillRect(ply.getX() - INV_OFFSET_X, ply.getY() - INV_OFFSET_Y, width, height); for(int i = 0; i < 320; i+=32) { for(int j = 0; j < height - 80; j+=32) { g.setColor(Color.white); g.drawRect(i + ply.getX() - INV_OFFSET_X, (j + 80) + ply.getY() - INV_OFFSET_Y, 32, 32); } } for(int x = 0; x < 10; x+=32) { for(int y = 0; y < 10; x+=32) { g.drawImage(ply.getPlayerItems().get(x).getImage().getScaledCopy(32, 32), x + ply.getX() - INV_OFFSET_X, (y + 80) + ply.getY() - INV_OFFSET_Y); } } // "" + ply.getStat( /*for (Entry<String, JsonElement> ele : invMenu.getObject().entrySet()) { g.drawString(ele.getValue().getAsString().replace("%n", ele.getKey().split("#(.*)")[0]), 50, 50); }*/ g.drawString(invMenu.getValueAsString("#title"), 320/2 - 40 + ply.getX() - INV_OFFSET_X, 10 + ply.getY() - INV_OFFSET_Y); g.drawString(invMenu.getValueAsString("#stat"), (width - 130) + ply.getX() - INV_OFFSET_X, 10 + ply.getY() - INV_OFFSET_Y); g.drawRect(ply.getX() - INV_OFFSET_X, ply.getY() - INV_OFFSET_Y, width, height); }
diff --git a/Tetris/src/javagame/MenuStrip.java b/Tetris/src/javagame/MenuStrip.java index 6d81f7d..4b164f6 100644 --- a/Tetris/src/javagame/MenuStrip.java +++ b/Tetris/src/javagame/MenuStrip.java @@ -1,154 +1,155 @@ package javagame; import java.util.ArrayList; import org.newdawn.slick.*; /** * @author Kevin Patton * A menu with various choices. Menu items can be added and removed. * Control schemes can be refined, and the menu selection can be captured * and returned. Can also launch various game states. */ public class MenuStrip { public static final int DEFAULT_SELECTION = 0; public static final int DEFAULT_NEXT = Input.KEY_DOWN; public static final int DEFAULT_PREVIOUS = Input.KEY_UP; public static final int DEFAULT_SELECT = Input.KEY_ENTER; private ArrayList<Interactable> menuItems; private Animation cursorAnimation; /** The sound the plays when the user changes the menu selection. */ private Sound selectSound; /** * The menu item that currently has 'focus.' In other words, * if the user presses enter while selection is 2, then the * second menu item's code will launch. */ private int selection = DEFAULT_SELECTION; /** The key to press in order to go to the next menu item. */ private int nextKey = DEFAULT_NEXT; /** The key to press in order to go to the previous menu item. */ private int previousKey = DEFAULT_PREVIOUS; /** The key to press in order to select the current menu item. */ private int selectKey = DEFAULT_SELECT; private int size = 0; private int x = 0; private int y = 0; private int lineHeight = 0; /** * Constructor that allows you to initialize the menu items. * @param items the menu items to be displayed and chooseable */ public MenuStrip(Interactable...items) { menuItems = new ArrayList<Interactable>(); Image cursorSheet = null; try { selectSound = new Sound("res/rotate.wav"); cursorSheet = new Image("res/cursor.png"); } catch (SlickException e) { e.printStackTrace(); } cursorAnimation = new Animation(new SpriteSheet(cursorSheet, 32, 32), 100); for (Interactable item : items) { menuItems.add(item); size++; } - lineHeight = menuItems.get(0).getHeight(); + if (size > 0) + lineHeight = menuItems.get(0).getHeight(); } /** * Default constructor. */ public MenuStrip() { menuItems = new ArrayList<Interactable>(); size = 0; } public void setLocation(int x, int y) { this.x = x; this.y = y; } public void gameActive() { menuItems.get(0).changeItem("Resume Game"); } public void gameDone() { menuItems.get(0).changeItem("New Game"); } public int getSelection() { return selection; } public void render(Graphics g) { cursorAnimation.draw(x - 40, y + selection * lineHeight); for (Interactable i : menuItems) { i.render(x, y); } } /** * Obtains input from the parent class and performs * the necessary updates to this MenuStrip as a result. * @param input an object containing the user's input information * @return the menu selection chosen by the player */ public int acceptInput(Input input) { if (input.isKeyPressed(nextKey)) { advanceSelection(); selectSound.play(); } if (input.isKeyPressed(previousKey)) { regressSelection(); selectSound.play(); } if (input.isKeyPressed(selectKey)) { System.out.println("Selected " + selection + "."); return selection; } return -1; } /** * Changes the menu selection to be one before whatever * it is currently. */ private void regressSelection() { if (selection > 0) selection--; else if (selection == 0) selection = size - 1; } /** * Changes the menu selection to be one after whatever * it is currently. */ private void advanceSelection() { if (selection < size - 1) selection++; else if (selection == size - 1) selection = 0; } /** * Adds a menu item to this MenuStrip. * @param item the String to be added to the menu items */ public void addMenuItem(Interactable item) { menuItems.add(item); size = menuItems.size(); } // Returns this object in a String representation. public String toString() { String estr = ""; for (Interactable item : menuItems) estr += item + "\n"; return estr; } }
true
true
public MenuStrip(Interactable...items) { menuItems = new ArrayList<Interactable>(); Image cursorSheet = null; try { selectSound = new Sound("res/rotate.wav"); cursorSheet = new Image("res/cursor.png"); } catch (SlickException e) { e.printStackTrace(); } cursorAnimation = new Animation(new SpriteSheet(cursorSheet, 32, 32), 100); for (Interactable item : items) { menuItems.add(item); size++; } lineHeight = menuItems.get(0).getHeight(); }
public MenuStrip(Interactable...items) { menuItems = new ArrayList<Interactable>(); Image cursorSheet = null; try { selectSound = new Sound("res/rotate.wav"); cursorSheet = new Image("res/cursor.png"); } catch (SlickException e) { e.printStackTrace(); } cursorAnimation = new Animation(new SpriteSheet(cursorSheet, 32, 32), 100); for (Interactable item : items) { menuItems.add(item); size++; } if (size > 0) lineHeight = menuItems.get(0).getHeight(); }
diff --git a/src/main/java/org/myrest/io/GPBText.java b/src/main/java/org/myrest/io/GPBText.java index 9ef1836..c0a1ede 100644 --- a/src/main/java/org/myrest/io/GPBText.java +++ b/src/main/java/org/myrest/io/GPBText.java @@ -1,37 +1,36 @@ package org.myrest.io; import java.io.UnsupportedEncodingException; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.codec.http.HttpVersion; import com.google.protobuf.Message; /** * * Write GPB to text * */ public class GPBText extends DefaultHttpResponse { byte[] bytes; public GPBText(Message msg) throws UnsupportedEncodingException { super(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); setHeader("Content-Type", "application/x-protobuf"); byte[] bytes = msg.toByteArray(); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(bytes); - buffer.writeBytes(bytes); super.setContent(buffer); this.bytes = bytes; } public String asString() throws UnsupportedEncodingException { return new String(bytes, "UTF-8"); } }
true
true
public GPBText(Message msg) throws UnsupportedEncodingException { super(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); setHeader("Content-Type", "application/x-protobuf"); byte[] bytes = msg.toByteArray(); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(bytes); buffer.writeBytes(bytes); super.setContent(buffer); this.bytes = bytes; }
public GPBText(Message msg) throws UnsupportedEncodingException { super(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); setHeader("Content-Type", "application/x-protobuf"); byte[] bytes = msg.toByteArray(); ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(bytes); super.setContent(buffer); this.bytes = bytes; }
diff --git a/src/main/java/org/bukkit/inventory/ItemStack.java b/src/main/java/org/bukkit/inventory/ItemStack.java index 7a424c79..95dc1f10 100644 --- a/src/main/java/org/bukkit/inventory/ItemStack.java +++ b/src/main/java/org/bukkit/inventory/ItemStack.java @@ -1,391 +1,391 @@ package org.bukkit.inventory; import com.google.common.collect.ImmutableMap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.bukkit.Material; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.enchantments.Enchantment; import org.bukkit.material.MaterialData; /** * Represents a stack of items */ public class ItemStack implements ConfigurationSerializable { private int type; private int amount = 0; private MaterialData data = null; private short durability = 0; private Map<Enchantment, Integer> enchantments = new HashMap<Enchantment, Integer>(); public ItemStack(final int type) { this(type, 0); } public ItemStack(final Material type) { this(type, 0); } public ItemStack(final int type, final int amount) { this(type, amount, (short) 0); } public ItemStack(final Material type, final int amount) { this(type.getId(), amount); } public ItemStack(final int type, final int amount, final short damage) { this(type, amount, damage, null); } public ItemStack(final Material type, final int amount, final short damage) { this(type.getId(), amount, damage); } public ItemStack(final int type, final int amount, final short damage, final Byte data) { this.type = type; this.amount = amount; this.durability = damage; if (data != null) { createData(data); this.durability = data; } } public ItemStack(final Material type, final int amount, final short damage, final Byte data) { this(type.getId(), amount, damage, data); } /** * Gets the type of this item * * @return Type of the items in this stack */ public Material getType() { return Material.getMaterial(type); } /** * Sets the type of this item<br /> * <br /> * Note that in doing so you will reset the MaterialData for this stack * * @param type New type to set the items in this stack to */ public void setType(Material type) { setTypeId(type.getId()); } /** * Gets the type id of this item * * @return Type Id of the items in this stack */ public int getTypeId() { return type; } /** * Sets the type id of this item<br /> * <br /> * Note that in doing so you will reset the MaterialData for this stack * * @param type New type id to set the items in this stack to */ public void setTypeId(int type) { this.type = type; createData((byte) 0); } /** * Gets the amount of items in this stack * * @return Amount of items in this stick */ public int getAmount() { return amount; } /** * Sets the amount of items in this stack * * @param amount New amount of items in this stack */ public void setAmount(int amount) { this.amount = amount; } /** * Gets the MaterialData for this stack of items * * @return MaterialData for this item */ public MaterialData getData() { Material mat = Material.getMaterial(getTypeId()); if (mat != null && mat.getData() != null) { data = mat.getNewData((byte) this.durability); } return data; } /** * Sets the MaterialData for this stack of items * * @param data New MaterialData for this item */ public void setData(MaterialData data) { Material mat = getType(); if ((mat == null) || (mat.getData() == null)) { this.data = data; } else { if ((data.getClass() == mat.getData()) || (data.getClass() == MaterialData.class)) { this.data = data; } else { throw new IllegalArgumentException("Provided data is not of type " + mat.getData().getName() + ", found " + data.getClass().getName()); } } } /** * Sets the durability of this item * * @param durability Durability of this item */ public void setDurability(final short durability) { this.durability = durability; } /** * Gets the durability of this item * * @return Durability of this item */ public short getDurability() { return durability; } /** * Get the maximum stacksize for the material hold in this ItemStack * Returns -1 if it has no idea. * * @return The maximum you can stack this material to. */ public int getMaxStackSize() { Material material = getType(); if (material != null) { return material.getMaxStackSize(); } return -1; } private void createData(final byte data) { Material mat = Material.getMaterial(type); if (mat == null) { this.data = new MaterialData(type, data); } else { this.data = mat.getNewData(data); } } @Override public String toString() { return "ItemStack{" + getType().name() + " x " + getAmount() + "}"; } @Override public boolean equals(Object obj) { if (!(obj instanceof ItemStack)) { return false; } ItemStack item = (ItemStack) obj; return item.getAmount() == getAmount() && item.getTypeId() == getTypeId() && getDurability() == item.getDurability() && getEnchantments().equals(item.getEnchantments()); } @Override public ItemStack clone() { ItemStack result = new ItemStack(type, amount, durability); result.addEnchantments(getEnchantments()); return result; } @Override public int hashCode() { int hash = 11; hash = hash * 19 + 7 * getTypeId(); // Overriding hashCode since equals is overridden, it's just hash = hash * 7 + 23 * getAmount(); // too bad these are mutable values... Q_Q return hash; } /** * Checks if this ItemStack contains the given {@link Enchantment} * * @param ench Enchantment to test * @return True if this has the given enchantment */ public boolean containsEnchantment(Enchantment ench) { return enchantments.containsKey(ench); } /** * Gets the level of the specified enchantment on this item stack * * @param ench Enchantment to check * @return Level of the enchantment, or 0 */ public int getEnchantmentLevel(Enchantment ench) { return enchantments.get(ench); } /** * Gets a map containing all enchantments and their levels on this item. * * @return Map of enchantments. */ public Map<Enchantment, Integer> getEnchantments() { return ImmutableMap.copyOf(enchantments); } /** * Adds the specified enchantments to this item stack. * <p> * This method is the same as calling {@link #addEnchantment(org.bukkit.enchantments.Enchantment, int)} * for each element of the map. * * @param enchantments Enchantments to add */ public void addEnchantments(Map<Enchantment, Integer> enchantments) { for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) { addEnchantment(entry.getKey(), entry.getValue()); } } /** * Adds the specified {@link Enchantment} to this item stack. * <p> * If this item stack already contained the given enchantment (at any level), it will be replaced. * * @param ench Enchantment to add * @param level Level of the enchantment */ public void addEnchantment(Enchantment ench, int level) { if ((level < ench.getStartLevel()) || (level > ench.getMaxLevel())) { throw new IllegalArgumentException("Enchantment level is either too low or too high (given " + level + ", bounds are " + ench.getStartLevel() + " to " + ench.getMaxLevel()); } else if (!ench.canEnchantItem(this)) { throw new IllegalArgumentException("Specified enchantment cannot be applied to this itemstack"); } addUnsafeEnchantment(ench, level); } /** * Adds the specified enchantments to this item stack in an unsafe manner. * <p> * This method is the same as calling {@link #addUnsafeEnchantment(org.bukkit.enchantments.Enchantment, int)} * for each element of the map. * * @param enchantments Enchantments to add */ public void addUnsafeEnchantments(Map<Enchantment, Integer> enchantments) { for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) { addUnsafeEnchantment(entry.getKey(), entry.getValue()); } } /** * Adds the specified {@link Enchantment} to this item stack. * <p> * If this item stack already contained the given enchantment (at any level), it will be replaced. * <p> * This method is unsafe and will ignore level restrictions or item type. Use at your own * discretion. * * @param ench Enchantment to add * @param level Level of the enchantment */ public void addUnsafeEnchantment(Enchantment ench, int level) { enchantments.put(ench, level); } /** * Removes the specified {@link Enchantment} if it exists on this item stack * * @param ench Enchantment to remove * @return Previous level, or 0 */ public int removeEnchantment(Enchantment ench) { Integer previous = enchantments.remove(ench); return (previous == null) ? 0 : previous; } public Map<String, Object> serialize() { Map<String, Object> result = new LinkedHashMap<String, Object>(); result.put("type", getType().name()); if (durability != 0) { result.put("damage", durability); } if (amount != 1) { result.put("amount", amount); } Map<Enchantment, Integer> enchants = getEnchantments(); if (enchants.size() > 0) { Map<String, Integer> safeEnchants = new HashMap<String, Integer>(); for (Map.Entry<Enchantment, Integer> entry : enchants.entrySet()) { safeEnchants.put(entry.getKey().getName(), entry.getValue()); } result.put("enchantments", safeEnchants); } return result; } public static ItemStack deserialize(Map<String, Object> args) { Material type = Material.getMaterial((String) args.get("type")); - int damage = 0; + short damage = 0; int amount = 1; if (args.containsKey("damage")) { - damage = (Integer) args.get("damage"); + damage = (Short) args.get("damage"); } if (args.containsKey("amount")) { amount = (Integer) args.get("amount"); } - ItemStack result = new ItemStack(type, amount, (short) damage); + ItemStack result = new ItemStack(type, amount, damage); if (args.containsKey("enchantments")) { Object raw = args.get("enchantments"); if (raw instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) raw; for (Map.Entry<Object, Object> entry : map.entrySet()) { Enchantment enchantment = Enchantment.getByName(entry.getKey().toString()); if ((enchantment != null) && (entry.getValue() instanceof Integer)) { result.addEnchantment(enchantment, (Integer) entry.getValue()); } } } } return result; } }
false
true
public static ItemStack deserialize(Map<String, Object> args) { Material type = Material.getMaterial((String) args.get("type")); int damage = 0; int amount = 1; if (args.containsKey("damage")) { damage = (Integer) args.get("damage"); } if (args.containsKey("amount")) { amount = (Integer) args.get("amount"); } ItemStack result = new ItemStack(type, amount, (short) damage); if (args.containsKey("enchantments")) { Object raw = args.get("enchantments"); if (raw instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) raw; for (Map.Entry<Object, Object> entry : map.entrySet()) { Enchantment enchantment = Enchantment.getByName(entry.getKey().toString()); if ((enchantment != null) && (entry.getValue() instanceof Integer)) { result.addEnchantment(enchantment, (Integer) entry.getValue()); } } } } return result; }
public static ItemStack deserialize(Map<String, Object> args) { Material type = Material.getMaterial((String) args.get("type")); short damage = 0; int amount = 1; if (args.containsKey("damage")) { damage = (Short) args.get("damage"); } if (args.containsKey("amount")) { amount = (Integer) args.get("amount"); } ItemStack result = new ItemStack(type, amount, damage); if (args.containsKey("enchantments")) { Object raw = args.get("enchantments"); if (raw instanceof Map) { @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) raw; for (Map.Entry<Object, Object> entry : map.entrySet()) { Enchantment enchantment = Enchantment.getByName(entry.getKey().toString()); if ((enchantment != null) && (entry.getValue() instanceof Integer)) { result.addEnchantment(enchantment, (Integer) entry.getValue()); } } } } return result; }
diff --git a/SMSFixLibrary/src/com/mattprecious/smsfix/library/FixService.java b/SMSFixLibrary/src/com/mattprecious/smsfix/library/FixService.java index f29d0db..7bc6258 100644 --- a/SMSFixLibrary/src/com/mattprecious/smsfix/library/FixService.java +++ b/SMSFixLibrary/src/com/mattprecious/smsfix/library/FixService.java @@ -1,433 +1,434 @@ /* * Copyright 2011 Matthew Precious * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mattprecious.smsfix.library; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import java.util.TimeZone; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.IBinder; import android.preference.PreferenceManager; import android.telephony.TelephonyManager; import android.util.Log; /** * Service to fix all incoming text messages * * How it works: * The service listens to the SMS database for any changes. Once notified, the * service loops through the database in descending order and checks each * message ID against the last known ID. If the ID is greater, then we can * assume it is a new message and alter its time stamp. Once we reach a message * that is not new, stop the loop. * * Foreground service code taken from the Android API Demos: * ForegroundService.java * * @author Matthew Precious * */ public class FixService extends Service { private SharedPreferences settings; // The content://sms URI does not notify when a thread is deleted, so // instead we use the content://mms-sms/conversations URI for observing. // This provider, however, does not play nice when looking for and editing // the existing messages. So, we use the original content://sms URI for our // editing private Uri observingURI = Uri.parse("content://mms-sms/conversations"); private Uri editingURI = Uri.parse("content://sms"); private Cursor observingCursor; private Cursor editingCursor; private FixServiceObserver observer = new FixServiceObserver(); private TelephonyManager telephonyManager; // notification variables private static NotificationManager nm; private static Notification notif; private static boolean running = false; public long lastSMSId = 0; // the ID of the last message we've // altered private static final Class<?>[] setForegroundSignature = new Class[] { boolean.class }; private static final Class<?>[] startForegroundSignature = new Class[] { int.class, Notification.class }; private static final Class<?>[] stopForegroundSignature = new Class[] { boolean.class }; private Method setForeground; private Method startForeground; private Method stopForeground; private Object[] setForegroundArgs = new Object[1]; private Object[] startForegroundArgs = new Object[2]; private Object[] stopForegroundArgs = new Object[1]; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); running = true; settings = PreferenceManager.getDefaultSharedPreferences(this); telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // set up everything we need for the running notification nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.icon; if (settings.getString("notify_icon", "grey").equals("grey")) { icon = R.drawable.icon_bw; } notif = new Notification(icon, null, 0); + notif.flags |= Notification.FLAG_ONGOING_EVENT; PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, SMSFix.class), 0); notif.setLatestEventInfo(this, getString(R.string.app_name), getString(R.string.notify_message), contentIntent); // set up the query we'll be observing // we only need the ID and the date String[] columns = { "_id", "date" }; observingCursor = getContentResolver().query(observingURI, columns, null, null, null); editingCursor = getContentResolver().query(editingURI, columns, "type=?", new String[] { "1" }, "_id DESC"); // if the observingCursor is null, fall back and try getting a cursor // using the editingCursor if (observingCursor == null) { observingCursor = getContentResolver().query(editingURI, columns, null, null, null); } // register the observer observingCursor.registerContentObserver(observer); // get the current last message ID lastSMSId = getLastMessageId(); setupForegroundVars(); Log.i(getClass().getSimpleName(), "SMS messages now being monitored"); } @Override public void onDestroy() { super.onDestroy(); // Make sure our notification is gone. stopForegroundCompat(R.string.notify_message); Log.i(getClass().getSimpleName(), "SMS messages are no longer being monitored. Good-bye."); } // This is the old onStart method that will be called on the pre-2.0 // platform. On 2.0 or later we override onStartCommand() so this // method will not be called. @Override public void onStart(Intent intent, int startId) { if (settings.getBoolean("notify", false)) { startNotify(); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (settings.getBoolean("notify", false)) { startNotify(); } // We want this service to continue running until it is explicitly // stopped, so return sticky. return START_STICKY; } private void setupForegroundVars() { try { startForeground = getClass().getMethod("startForeground", startForegroundSignature); stopForeground = getClass().getMethod("stopForeground", stopForegroundSignature); return; } catch (NoSuchMethodException e) { // Running on an older platform. startForeground = stopForeground = null; } try { setForeground = getClass().getMethod("setForeground", setForegroundSignature); } catch (NoSuchMethodException e) { throw new IllegalStateException("OS doesn't have Service.startForeground OR Service.setForeground!"); } } public void startNotify() { startForegroundCompat(R.string.notify_message, notif); } /** * This is a wrapper around the new startForeground method, using the older * APIs if it is not available. */ void startForegroundCompat(int id, Notification notification) { // If we have the new startForeground API, then use it. if (startForeground != null) { startForegroundArgs[0] = Integer.valueOf(id); startForegroundArgs[1] = notification; invokeMethod(startForeground, startForegroundArgs); return; } // Fall back on the old API. setForegroundArgs[0] = Boolean.TRUE; invokeMethod(setForeground, setForegroundArgs); nm.notify(id, notification); } /** * This is a wrapper around the new stopForeground method, using the older * APIs if it is not available. */ void stopForegroundCompat(int id) { // If we have the new stopForeground API, then use it. if (stopForeground != null) { stopForegroundArgs[0] = Boolean.TRUE; try { stopForeground.invoke(this, stopForegroundArgs); } catch (InvocationTargetException e) { // Should not happen. Log.w("ApiDemos", "Unable to invoke stopForeground", e); } catch (IllegalAccessException e) { // Should not happen. Log.w("ApiDemos", "Unable to invoke stopForeground", e); } return; } // Fall back on the old API. Note to cancel BEFORE changing the // foreground state, since we could be killed at that point. nm.cancel(id); setForegroundArgs[0] = Boolean.FALSE; invokeMethod(setForeground, setForegroundArgs); } void invokeMethod(Method method, Object[] args) { try { method.invoke(this, args); } catch (InvocationTargetException e) { // Should not happen. Log.w(getClass().getSimpleName(), "Unable to invoke method", e); } catch (IllegalAccessException e) { // Should not happen. Log.w(getClass().getSimpleName(), "Unable to invoke method", e); } } /** * Returns true if the service is running * * @return boolean */ public static boolean isRunning() { return running; } /** * Returns the ID of the most recent message * * @return long */ private long getLastMessageId() { long ret = -1; // if there are any messages at our cursor if (editingCursor.getCount() > 0) { // get the first one editingCursor.moveToFirst(); // grab its ID ret = editingCursor.getLong(editingCursor.getColumnIndexOrThrow("_id")); } return ret; } /** * Updates the time stamp on any messages that have come in */ private void fixLastMessage() { // if there are any messages if (editingCursor.getCount() > 0) { // move to the first one editingCursor.moveToFirst(); // get the message's ID long id = editingCursor.getLong(editingCursor.getColumnIndexOrThrow("_id")); // keep the current last changed ID long oldLastChanged = lastSMSId; // update our counter lastSMSId = id; // while the new ID is still greater than the last altered message // loop just in case messages come in quick succession while (id > oldLastChanged) { // alter the time stamp alterMessage(id); // base case, handle there being no more messages and break out if (editingCursor.isLast()) { break; } // move to the next message editingCursor.moveToNext(); // grab its ID id = editingCursor.getLong(editingCursor.getColumnIndexOrThrow("_id")); } } else { // there aren't any messages, reset the id counter lastSMSId = -1; } } /** * Get the desired offset change based on the user's preferences * * @return long */ private long getOffset() { long offset = 0; // if the user wants us to auto-determine the offset use the negative of // their GMT offset String method = settings.getString("offset_method", "manual"); if (method.equals("automatic") || method.equals("neg_automatic")) { offset = TimeZone.getDefault().getRawOffset(); // account for DST if (TimeZone.getDefault().useDaylightTime() && TimeZone.getDefault().inDaylightTime(new Date())) { offset += 3600000; } if (method.equals("automatic")) { offset *= -1; } // otherwise, use the offset the user has specified } else { offset = Integer.parseInt(settings.getString("offset_hours", "0")) * 3600000; offset += Integer.parseInt(settings.getString("offset_minutes", "0")) * 60000; } return offset; } /** * Alter the time stamp of the message with the given ID * * @param id * - the ID of the message to be altered */ private void alterMessage(long id) { Log.i(getClass().getSimpleName(), "Adjusting timestamp for message: " + id); // grab the date assigned to the message long longdate = editingCursor.getLong(editingCursor.getColumnIndexOrThrow("date")); // if the user has asked for the Future Only option, make sure the // message // time is greater than the phone time, giving a 5 second grace // period // keeping the preference name as cdma so when users upgrade it uses // their current value if (!settings.getBoolean("cdma", false) || (longdate - (new Date()).getTime() > 5000)) { // if the user wants to use the phone's time, use the current date if (settings.getString("offset_method", "manual").equals("phone")) { longdate = (new Date()).getTime(); } else { longdate = longdate + getOffset(); } } // update the message with the new time stamp ContentValues values = new ContentValues(); values.put("date", longdate); getContentResolver().update(editingURI, values, "_id = " + id, null); } /** * Checks if the roaming condition is met. Returns true if the user doesn't * care about roaming, or if the user does but isn't currently roaming * * @return boolean */ private boolean roamingConditionMet() { boolean onlyRoaming = settings.getBoolean("roaming", false); boolean isRoaming = telephonyManager.isNetworkRoaming(); boolean roamingCondition = !(onlyRoaming && isRoaming); return roamingCondition; } /** * ContentObserver to handle updates to the SMS database * * @author Matthew Precious * */ private class FixServiceObserver extends ContentObserver { public FixServiceObserver() { super(null); } @Override public void onChange(boolean selfChange) { super.onChange(selfChange); // if the change wasn't self inflicted // TODO: make this boolean actually work... if (!selfChange && roamingConditionMet()) { Log.i(getClass().getSimpleName(), "SMS database altered, checking...!"); // requery the database to get the latest messages editingCursor.requery(); // fix them fixLastMessage(); } } } }
true
true
public void onCreate() { super.onCreate(); running = true; settings = PreferenceManager.getDefaultSharedPreferences(this); telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // set up everything we need for the running notification nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.icon; if (settings.getString("notify_icon", "grey").equals("grey")) { icon = R.drawable.icon_bw; } notif = new Notification(icon, null, 0); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, SMSFix.class), 0); notif.setLatestEventInfo(this, getString(R.string.app_name), getString(R.string.notify_message), contentIntent); // set up the query we'll be observing // we only need the ID and the date String[] columns = { "_id", "date" }; observingCursor = getContentResolver().query(observingURI, columns, null, null, null); editingCursor = getContentResolver().query(editingURI, columns, "type=?", new String[] { "1" }, "_id DESC"); // if the observingCursor is null, fall back and try getting a cursor // using the editingCursor if (observingCursor == null) { observingCursor = getContentResolver().query(editingURI, columns, null, null, null); } // register the observer observingCursor.registerContentObserver(observer); // get the current last message ID lastSMSId = getLastMessageId(); setupForegroundVars(); Log.i(getClass().getSimpleName(), "SMS messages now being monitored"); }
public void onCreate() { super.onCreate(); running = true; settings = PreferenceManager.getDefaultSharedPreferences(this); telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // set up everything we need for the running notification nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.icon; if (settings.getString("notify_icon", "grey").equals("grey")) { icon = R.drawable.icon_bw; } notif = new Notification(icon, null, 0); notif.flags |= Notification.FLAG_ONGOING_EVENT; PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, SMSFix.class), 0); notif.setLatestEventInfo(this, getString(R.string.app_name), getString(R.string.notify_message), contentIntent); // set up the query we'll be observing // we only need the ID and the date String[] columns = { "_id", "date" }; observingCursor = getContentResolver().query(observingURI, columns, null, null, null); editingCursor = getContentResolver().query(editingURI, columns, "type=?", new String[] { "1" }, "_id DESC"); // if the observingCursor is null, fall back and try getting a cursor // using the editingCursor if (observingCursor == null) { observingCursor = getContentResolver().query(editingURI, columns, null, null, null); } // register the observer observingCursor.registerContentObserver(observer); // get the current last message ID lastSMSId = getLastMessageId(); setupForegroundVars(); Log.i(getClass().getSimpleName(), "SMS messages now being monitored"); }
diff --git a/src/org/geometerplus/fbreader/library/Library.java b/src/org/geometerplus/fbreader/library/Library.java index 61f14b24..afe43d7e 100644 --- a/src/org/geometerplus/fbreader/library/Library.java +++ b/src/org/geometerplus/fbreader/library/Library.java @@ -1,544 +1,544 @@ /* * Copyright (C) 2007-2011 Geometer Plus <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.fbreader.library; import java.io.File; import java.lang.ref.WeakReference; import java.util.*; import org.geometerplus.zlibrary.core.filesystem.*; import org.geometerplus.zlibrary.core.image.ZLImage; import org.geometerplus.zlibrary.core.util.ZLMiscUtil; import org.geometerplus.zlibrary.core.resources.ZLResource; import org.geometerplus.fbreader.formats.FormatPlugin; import org.geometerplus.fbreader.formats.PluginCollection; import org.geometerplus.fbreader.Paths; public final class Library { static final int STATE_NOT_INITIALIZED = 0; static final int STATE_FULLY_INITIALIZED = 1; public static final String ROOT_FAVORITES = "favorites"; public static final String ROOT_SEARCH_RESULTS = "searchResults"; public static final String ROOT_RECENT = "recent"; public static final String ROOT_BY_AUTHOR = "byAuthor"; public static final String ROOT_BY_TITLE = "byTitle"; public static final String ROOT_BY_TAG = "byTag"; public static final String ROOT_FILE_TREE = "fileTree"; public static ZLResource resource() { return ZLResource.resource("libraryView"); } private final List<Book> myBooks = new LinkedList<Book>(); private final Set<Book> myExternalBooks = new HashSet<Book>(); private final Map<String,RootTree> myRootTrees = new HashMap<String,RootTree>(); private volatile int myState = STATE_NOT_INITIALIZED; private volatile boolean myInterrupted = false; public Library() { myRootTrees.put(ROOT_FAVORITES, new FavoritesTree(this, ROOT_FAVORITES)); myRootTrees.put(ROOT_FILE_TREE, new FileRootTree(this, ROOT_FILE_TREE)); } public RootTree getRootTree(String id) { RootTree root = myRootTrees.get(id); if (root == null) { root = new RootTree(this, id); myRootTrees.put(id, root); } return root; } public LibraryTree getLibraryTree(LibraryTree.Key key) { if (key == null) { return null; } if (key.Parent == null) { return getRootTree(key.Id); } final LibraryTree parentTree = getLibraryTree(key.Parent); return parentTree != null ? (LibraryTree)parentTree.getSubTree(key.Id) : null; } boolean hasState(int state) { return myState >= state || myInterrupted; } void waitForState(int state) { while (myState < state && !myInterrupted) { synchronized(this) { if (myState < state && !myInterrupted) { try { wait(); } catch (InterruptedException e) { } } } } } public static ZLResourceFile getHelpFile() { final Locale locale = Locale.getDefault(); ZLResourceFile file = ZLResourceFile.createResourceFile( "data/help/MiniHelp." + locale.getLanguage() + "_" + locale.getCountry() + ".fb2" ); if (file.exists()) { return file; } file = ZLResourceFile.createResourceFile( "data/help/MiniHelp." + locale.getLanguage() + ".fb2" ); if (file.exists()) { return file; } return ZLResourceFile.createResourceFile("data/help/MiniHelp.en.fb2"); } private static Book getBook(ZLFile bookFile, FileInfoSet fileInfos, Map<Long,Book> saved, boolean doReadMetaInfo) { Book book = saved.remove(fileInfos.getId(bookFile)); if (book == null) { doReadMetaInfo = true; book = new Book(bookFile); } if (doReadMetaInfo && !book.readMetaInfo()) { return null; } return book; } private void collectBooks( ZLFile file, FileInfoSet fileInfos, Map<Long,Book> savedBooks, boolean doReadMetaInfo ) { Book book = getBook(file, fileInfos, savedBooks, doReadMetaInfo); if (book != null) { myBooks.add(book); } else if (file.isArchive()) { for (ZLFile entry : fileInfos.archiveEntries(file)) { collectBooks(entry, fileInfos, savedBooks, doReadMetaInfo); } } } private void collectExternalBooks(FileInfoSet fileInfos, Map<Long,Book> savedBooks) { final HashSet<ZLPhysicalFile> myUpdatedFiles = new HashSet<ZLPhysicalFile>(); final HashSet<Long> files = new HashSet<Long>(savedBooks.keySet()); for (Long fileId: files) { final ZLFile bookFile = fileInfos.getFile(fileId); if (bookFile == null) { continue; } final ZLPhysicalFile physicalFile = bookFile.getPhysicalFile(); if (physicalFile == null || !physicalFile.exists()) { continue; } boolean reloadMetaInfo = false; if (myUpdatedFiles.contains(physicalFile)) { reloadMetaInfo = true; } else if (!fileInfos.check(physicalFile, physicalFile != bookFile)) { reloadMetaInfo = true; myUpdatedFiles.add(physicalFile); } final Book book = getBook(bookFile, fileInfos, savedBooks, reloadMetaInfo); if (book == null) { continue; } final long bookId = book.getId(); if (bookId != -1 && BooksDatabase.Instance().checkBookList(bookId)) { myBooks.add(book); myExternalBooks.add(book); } } } private List<ZLPhysicalFile> collectPhysicalFiles() { final Queue<ZLFile> dirQueue = new LinkedList<ZLFile>(); final HashSet<ZLFile> dirSet = new HashSet<ZLFile>(); final LinkedList<ZLPhysicalFile> fileList = new LinkedList<ZLPhysicalFile>(); dirQueue.offer(new ZLPhysicalFile(new File(Paths.BooksDirectoryOption().getValue()))); while (!dirQueue.isEmpty()) { for (ZLFile file : dirQueue.poll().children()) { if (file.isDirectory()) { if (!dirSet.contains(file)) { dirQueue.add(file); dirSet.add(file); } } else { file.setCached(true); fileList.add((ZLPhysicalFile)file); } } } return fileList; } private void collectBooks() { final List<ZLPhysicalFile> physicalFilesList = collectPhysicalFiles(); FileInfoSet fileInfos = new FileInfoSet(); final Map<Long,Book> savedBooks = BooksDatabase.Instance().loadBooks(fileInfos); for (ZLPhysicalFile file : physicalFilesList) { // TODO: better value for this flag final boolean flag = !"epub".equals(file.getExtension()); collectBooks(file, fileInfos, savedBooks, !fileInfos.check(file, flag)); file.setCached(false); } final Book helpBook = getBook(getHelpFile(), fileInfos, savedBooks, false); if (helpBook != null) { myBooks.add(helpBook); } collectExternalBooks(fileInfos, savedBooks); fileInfos.save(); } private static class AuthorSeriesPair { private final Author myAuthor; private final String mySeries; AuthorSeriesPair(Author author, String series) { myAuthor = author; mySeries = series; } public boolean equals(Object object) { if (this == object) { return true; } if (!(object instanceof AuthorSeriesPair)) { return false; } AuthorSeriesPair pair = (AuthorSeriesPair)object; return ZLMiscUtil.equals(myAuthor, pair.myAuthor) && mySeries.equals(pair.mySeries); } public int hashCode() { return Author.hashCode(myAuthor) + mySeries.hashCode(); } } private final ArrayList<?> myNullList = new ArrayList<Object>(1); { myNullList.add(null); } private TagTree getTagTree(Tag tag, HashMap<Tag,TagTree> tagTreeMap) { TagTree tagTree = tagTreeMap.get(tag); if (tagTree == null) { LibraryTree parent = ((tag != null) && (tag.Parent != null)) ? getTagTree(tag.Parent, tagTreeMap) : getRootTree(ROOT_BY_TAG); tagTree = parent.createTagSubTree(tag); tagTreeMap.put(tag, tagTree); } return tagTree; } private void build() { final HashMap<Tag,TagTree> tagTreeMap = new HashMap<Tag,TagTree>(); final HashMap<Author,AuthorTree> authorTreeMap = new HashMap<Author,AuthorTree>(); final HashMap<AuthorSeriesPair,SeriesTree> seriesTreeMap = new HashMap<AuthorSeriesPair,SeriesTree>(); final HashMap<Long,Book> bookById = new HashMap<Long,Book>(); collectBooks(); for (Book book : myBooks) { bookById.put(book.getId(), book); List<Author> authors = book.authors(); if (authors.isEmpty()) { authors = (List<Author>)myNullList; } final SeriesInfo seriesInfo = book.getSeriesInfo(); for (Author a : authors) { AuthorTree authorTree = authorTreeMap.get(a); if (authorTree == null) { authorTree = getRootTree(ROOT_BY_AUTHOR).createAuthorSubTree(a); authorTreeMap.put(a, authorTree); } if (seriesInfo == null) { authorTree.createBookSubTree(book, false); } else { final String series = seriesInfo.Name; final AuthorSeriesPair pair = new AuthorSeriesPair(a, series); SeriesTree seriesTree = seriesTreeMap.get(pair); if (seriesTree == null) { seriesTree = authorTree.createSeriesSubTree(series); seriesTreeMap.put(pair, seriesTree); } seriesTree.createBookInSeriesSubTree(book); } } List<Tag> tags = book.tags(); if (tags.isEmpty()) { tags = (List<Tag>)myNullList; } for (Tag t : tags) { getTagTree(t, tagTreeMap).createBookSubTree(book, true); } } boolean doGroupTitlesByFirstLetter = false; if (myBooks.size() > 10) { final HashSet<Character> letterSet = new HashSet<Character>(); for (Book book : myBooks) { String title = book.getTitle(); if (title != null) { title = title.trim(); if (!"".equals(title)) { letterSet.add(title.charAt(0)); } } } - doGroupTitlesByFirstLetter = letterSet.size() > myBooks.size() + 4; + doGroupTitlesByFirstLetter = myBooks.size() > letterSet.size() * 5 / 4; } if (doGroupTitlesByFirstLetter) { final HashMap<Character,TitleTree> letterTrees = new HashMap<Character,TitleTree>(); for (Book book : myBooks) { String title = book.getTitle(); if (title == null) { continue; } title = title.trim(); if ("".equals(title)) { continue; } Character c = title.charAt(0); TitleTree tree = letterTrees.get(c); if (tree == null) { tree = getRootTree(ROOT_BY_TITLE).createTitleSubTree(c.toString()); letterTrees.put(c, tree); } tree.createBookSubTree(book, true); } } else { for (Book book : myBooks) { getRootTree(ROOT_BY_TITLE).createBookSubTree(book, true); } } final BooksDatabase db = BooksDatabase.Instance(); for (long id : db.loadRecentBookIds()) { Book book = bookById.get(id); if (book != null) { getRootTree(ROOT_RECENT).createBookSubTree(book, true); } } for (long id : db.loadFavoritesIds()) { Book book = bookById.get(id); if (book != null) { getRootTree(ROOT_FAVORITES).createBookSubTree(book, true); } } getRootTree(ROOT_FAVORITES).sortAllChildren(); getRootTree(ROOT_BY_AUTHOR).sortAllChildren(); getRootTree(ROOT_BY_TITLE).sortAllChildren(); getRootTree(ROOT_BY_TAG).sortAllChildren(); db.executeAsATransaction(new Runnable() { public void run() { for (Book book : myBooks) { book.save(); } } }); myState = STATE_FULLY_INITIALIZED; } public synchronized void synchronize() { if (myState == STATE_NOT_INITIALIZED) { try { myInterrupted = false; build(); } catch (Throwable t) { myInterrupted = true; } notifyAll(); } } public static Book getRecentBook() { List<Long> recentIds = BooksDatabase.Instance().loadRecentBookIds(); return (recentIds.size() > 0) ? Book.getById(recentIds.get(0)) : null; } public static Book getPreviousBook() { List<Long> recentIds = BooksDatabase.Instance().loadRecentBookIds(); return (recentIds.size() > 1) ? Book.getById(recentIds.get(1)) : null; } public LibraryTree searchResults() { return getRootTree(ROOT_SEARCH_RESULTS); } public LibraryTree searchBooks(String pattern) { waitForState(STATE_FULLY_INITIALIZED); final RootTree newSearchResults = new SearchResultsTree(this, ROOT_SEARCH_RESULTS, pattern); if (pattern != null) { pattern = pattern.toLowerCase(); for (Book book : myBooks) { if (book.matches(pattern)) { newSearchResults.createBookSubTree(book, true); } } newSearchResults.sortAllChildren(); if (newSearchResults.hasChildren()) { myRootTrees.put(ROOT_SEARCH_RESULTS, newSearchResults); } } return newSearchResults; } public static void addBookToRecentList(Book book) { final BooksDatabase db = BooksDatabase.Instance(); final List<Long> ids = db.loadRecentBookIds(); final Long bookId = book.getId(); ids.remove(bookId); ids.add(0, bookId); if (ids.size() > 12) { ids.remove(12); } db.saveRecentBookIds(ids); } public boolean isBookInFavorites(Book book) { waitForState(STATE_FULLY_INITIALIZED); return getRootTree(ROOT_FAVORITES).containsBook(book); } public void addBookToFavorites(Book book) { waitForState(STATE_FULLY_INITIALIZED); final LibraryTree rootFavorites = getRootTree(ROOT_FAVORITES); if (!rootFavorites.containsBook(book)) { rootFavorites.createBookSubTree(book, true); rootFavorites.sortAllChildren(); BooksDatabase.Instance().addToFavorites(book.getId()); } } public void removeBookFromFavorites(Book book) { waitForState(STATE_FULLY_INITIALIZED); if (getRootTree(ROOT_FAVORITES).removeBook(book)) { BooksDatabase.Instance().removeFromFavorites(book.getId()); } } public static final int REMOVE_DONT_REMOVE = 0x00; public static final int REMOVE_FROM_LIBRARY = 0x01; public static final int REMOVE_FROM_DISK = 0x02; public static final int REMOVE_FROM_LIBRARY_AND_DISK = REMOVE_FROM_LIBRARY | REMOVE_FROM_DISK; public int getRemoveBookMode(Book book) { waitForState(STATE_FULLY_INITIALIZED); return (myExternalBooks.contains(book) ? REMOVE_FROM_LIBRARY : REMOVE_DONT_REMOVE) | (canDeleteBookFile(book) ? REMOVE_FROM_DISK : REMOVE_DONT_REMOVE); } private boolean canDeleteBookFile(Book book) { ZLFile file = book.File; if (file.getPhysicalFile() == null) { return false; } while (file instanceof ZLArchiveEntryFile) { file = file.getParent(); if (file.children().size() != 1) { return false; } } return true; } public void removeBook(Book book, int removeMode) { if (removeMode == REMOVE_DONT_REMOVE) { return; } waitForState(STATE_FULLY_INITIALIZED); myBooks.remove(book); if (getRootTree(ROOT_RECENT).removeBook(book)) { final BooksDatabase db = BooksDatabase.Instance(); final List<Long> ids = db.loadRecentBookIds(); ids.remove(book.getId()); db.saveRecentBookIds(ids); } for (LibraryTree root : myRootTrees.values()) { root.removeBook(book); } BooksDatabase.Instance().deleteFromBookList(book.getId()); if ((removeMode & REMOVE_FROM_DISK) != 0) { book.File.getPhysicalFile().delete(); } } private static final HashMap<String,WeakReference<ZLImage>> ourCoverMap = new HashMap<String,WeakReference<ZLImage>>(); private static final WeakReference<ZLImage> NULL_IMAGE = new WeakReference<ZLImage>(null); public static ZLImage getCover(ZLFile file) { if (file == null) { return null; } synchronized(ourCoverMap) { final String path = file.getPath(); final WeakReference<ZLImage> ref = ourCoverMap.get(path); if (ref == NULL_IMAGE) { return null; } else if (ref != null) { final ZLImage image = ref.get(); if (image != null) { return image; } } ZLImage image = null; final FormatPlugin plugin = PluginCollection.Instance().getPlugin(file); if (plugin != null) { image = plugin.readCover(file); } if (image == null) { ourCoverMap.put(path, NULL_IMAGE); } else { ourCoverMap.put(path, new WeakReference<ZLImage>(image)); } return image; } } public static String getAnnotation(ZLFile file) { final FormatPlugin plugin = PluginCollection.Instance().getPlugin(file); return plugin != null ? plugin.readAnnotation(file) : null; } }
true
true
private void build() { final HashMap<Tag,TagTree> tagTreeMap = new HashMap<Tag,TagTree>(); final HashMap<Author,AuthorTree> authorTreeMap = new HashMap<Author,AuthorTree>(); final HashMap<AuthorSeriesPair,SeriesTree> seriesTreeMap = new HashMap<AuthorSeriesPair,SeriesTree>(); final HashMap<Long,Book> bookById = new HashMap<Long,Book>(); collectBooks(); for (Book book : myBooks) { bookById.put(book.getId(), book); List<Author> authors = book.authors(); if (authors.isEmpty()) { authors = (List<Author>)myNullList; } final SeriesInfo seriesInfo = book.getSeriesInfo(); for (Author a : authors) { AuthorTree authorTree = authorTreeMap.get(a); if (authorTree == null) { authorTree = getRootTree(ROOT_BY_AUTHOR).createAuthorSubTree(a); authorTreeMap.put(a, authorTree); } if (seriesInfo == null) { authorTree.createBookSubTree(book, false); } else { final String series = seriesInfo.Name; final AuthorSeriesPair pair = new AuthorSeriesPair(a, series); SeriesTree seriesTree = seriesTreeMap.get(pair); if (seriesTree == null) { seriesTree = authorTree.createSeriesSubTree(series); seriesTreeMap.put(pair, seriesTree); } seriesTree.createBookInSeriesSubTree(book); } } List<Tag> tags = book.tags(); if (tags.isEmpty()) { tags = (List<Tag>)myNullList; } for (Tag t : tags) { getTagTree(t, tagTreeMap).createBookSubTree(book, true); } } boolean doGroupTitlesByFirstLetter = false; if (myBooks.size() > 10) { final HashSet<Character> letterSet = new HashSet<Character>(); for (Book book : myBooks) { String title = book.getTitle(); if (title != null) { title = title.trim(); if (!"".equals(title)) { letterSet.add(title.charAt(0)); } } } doGroupTitlesByFirstLetter = letterSet.size() > myBooks.size() + 4; } if (doGroupTitlesByFirstLetter) { final HashMap<Character,TitleTree> letterTrees = new HashMap<Character,TitleTree>(); for (Book book : myBooks) { String title = book.getTitle(); if (title == null) { continue; } title = title.trim(); if ("".equals(title)) { continue; } Character c = title.charAt(0); TitleTree tree = letterTrees.get(c); if (tree == null) { tree = getRootTree(ROOT_BY_TITLE).createTitleSubTree(c.toString()); letterTrees.put(c, tree); } tree.createBookSubTree(book, true); } } else { for (Book book : myBooks) { getRootTree(ROOT_BY_TITLE).createBookSubTree(book, true); } } final BooksDatabase db = BooksDatabase.Instance(); for (long id : db.loadRecentBookIds()) { Book book = bookById.get(id); if (book != null) { getRootTree(ROOT_RECENT).createBookSubTree(book, true); } } for (long id : db.loadFavoritesIds()) { Book book = bookById.get(id); if (book != null) { getRootTree(ROOT_FAVORITES).createBookSubTree(book, true); } } getRootTree(ROOT_FAVORITES).sortAllChildren(); getRootTree(ROOT_BY_AUTHOR).sortAllChildren(); getRootTree(ROOT_BY_TITLE).sortAllChildren(); getRootTree(ROOT_BY_TAG).sortAllChildren(); db.executeAsATransaction(new Runnable() { public void run() { for (Book book : myBooks) { book.save(); } } }); myState = STATE_FULLY_INITIALIZED; }
private void build() { final HashMap<Tag,TagTree> tagTreeMap = new HashMap<Tag,TagTree>(); final HashMap<Author,AuthorTree> authorTreeMap = new HashMap<Author,AuthorTree>(); final HashMap<AuthorSeriesPair,SeriesTree> seriesTreeMap = new HashMap<AuthorSeriesPair,SeriesTree>(); final HashMap<Long,Book> bookById = new HashMap<Long,Book>(); collectBooks(); for (Book book : myBooks) { bookById.put(book.getId(), book); List<Author> authors = book.authors(); if (authors.isEmpty()) { authors = (List<Author>)myNullList; } final SeriesInfo seriesInfo = book.getSeriesInfo(); for (Author a : authors) { AuthorTree authorTree = authorTreeMap.get(a); if (authorTree == null) { authorTree = getRootTree(ROOT_BY_AUTHOR).createAuthorSubTree(a); authorTreeMap.put(a, authorTree); } if (seriesInfo == null) { authorTree.createBookSubTree(book, false); } else { final String series = seriesInfo.Name; final AuthorSeriesPair pair = new AuthorSeriesPair(a, series); SeriesTree seriesTree = seriesTreeMap.get(pair); if (seriesTree == null) { seriesTree = authorTree.createSeriesSubTree(series); seriesTreeMap.put(pair, seriesTree); } seriesTree.createBookInSeriesSubTree(book); } } List<Tag> tags = book.tags(); if (tags.isEmpty()) { tags = (List<Tag>)myNullList; } for (Tag t : tags) { getTagTree(t, tagTreeMap).createBookSubTree(book, true); } } boolean doGroupTitlesByFirstLetter = false; if (myBooks.size() > 10) { final HashSet<Character> letterSet = new HashSet<Character>(); for (Book book : myBooks) { String title = book.getTitle(); if (title != null) { title = title.trim(); if (!"".equals(title)) { letterSet.add(title.charAt(0)); } } } doGroupTitlesByFirstLetter = myBooks.size() > letterSet.size() * 5 / 4; } if (doGroupTitlesByFirstLetter) { final HashMap<Character,TitleTree> letterTrees = new HashMap<Character,TitleTree>(); for (Book book : myBooks) { String title = book.getTitle(); if (title == null) { continue; } title = title.trim(); if ("".equals(title)) { continue; } Character c = title.charAt(0); TitleTree tree = letterTrees.get(c); if (tree == null) { tree = getRootTree(ROOT_BY_TITLE).createTitleSubTree(c.toString()); letterTrees.put(c, tree); } tree.createBookSubTree(book, true); } } else { for (Book book : myBooks) { getRootTree(ROOT_BY_TITLE).createBookSubTree(book, true); } } final BooksDatabase db = BooksDatabase.Instance(); for (long id : db.loadRecentBookIds()) { Book book = bookById.get(id); if (book != null) { getRootTree(ROOT_RECENT).createBookSubTree(book, true); } } for (long id : db.loadFavoritesIds()) { Book book = bookById.get(id); if (book != null) { getRootTree(ROOT_FAVORITES).createBookSubTree(book, true); } } getRootTree(ROOT_FAVORITES).sortAllChildren(); getRootTree(ROOT_BY_AUTHOR).sortAllChildren(); getRootTree(ROOT_BY_TITLE).sortAllChildren(); getRootTree(ROOT_BY_TAG).sortAllChildren(); db.executeAsATransaction(new Runnable() { public void run() { for (Book book : myBooks) { book.save(); } } }); myState = STATE_FULLY_INITIALIZED; }
diff --git a/src/main/java/org/apache/vysper/xmpp/modules/servicediscovery/handler/DiscoInfoIQHandler.java b/src/main/java/org/apache/vysper/xmpp/modules/servicediscovery/handler/DiscoInfoIQHandler.java index 1f4c9291..989c4073 100644 --- a/src/main/java/org/apache/vysper/xmpp/modules/servicediscovery/handler/DiscoInfoIQHandler.java +++ b/src/main/java/org/apache/vysper/xmpp/modules/servicediscovery/handler/DiscoInfoIQHandler.java @@ -1,141 +1,143 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.vysper.xmpp.modules.servicediscovery.handler; import org.apache.vysper.xmpp.addressing.Entity; import org.apache.vysper.xmpp.modules.core.base.handler.DefaultIQHandler; import org.apache.vysper.xmpp.modules.servicediscovery.collection.ServiceCollector; import org.apache.vysper.xmpp.modules.servicediscovery.collection.ServiceDiscoveryRequestListenerRegistry; import org.apache.vysper.xmpp.modules.servicediscovery.management.InfoElement; import org.apache.vysper.xmpp.modules.servicediscovery.management.InfoRequest; import org.apache.vysper.xmpp.modules.servicediscovery.management.ServiceDiscoveryRequestException; import org.apache.vysper.xmpp.protocol.NamespaceURIs; import org.apache.vysper.xmpp.server.ServerRuntimeContext; import org.apache.vysper.xmpp.server.SessionContext; import org.apache.vysper.xmpp.server.response.ServerErrorResponses; import org.apache.vysper.xmpp.stanza.IQStanza; import org.apache.vysper.xmpp.stanza.IQStanzaType; import org.apache.vysper.xmpp.stanza.Stanza; import org.apache.vysper.xmpp.stanza.StanzaBuilder; import org.apache.vysper.xmpp.stanza.StanzaErrorCondition; import org.apache.vysper.xmpp.stanza.StanzaErrorType; import org.apache.vysper.xmpp.xmlfragment.XMLElement; import org.apache.vysper.compliance.SpecCompliant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * handles IQ info queries * * @author The Apache MINA Project ([email protected]) */ @SpecCompliant(spec="xep-0030", status= SpecCompliant.ComplianceStatus.IN_PROGRESS, coverage = SpecCompliant.ComplianceCoverage.PARTIAL, comment = "handles disco info queries") public class DiscoInfoIQHandler extends DefaultIQHandler { final Logger logger = LoggerFactory.getLogger(DiscoInfoIQHandler.class); @Override protected boolean verifyNamespace(Stanza stanza) { return verifyInnerNamespace(stanza, NamespaceURIs.XEP0030_SERVICE_DISCOVERY_INFO); } @Override protected boolean verifyInnerElement(Stanza stanza) { return verifyInnerElementWorker(stanza, "query"); } @Override protected Stanza handleGet(IQStanza stanza, ServerRuntimeContext serverRuntimeContext, SessionContext sessionContext) { ServiceCollector serviceCollector = null; // TODO if the target entity does not exist, return error/cancel/item-not-found // TODO more strictly, server can also return error/cancel/service-unaivable // retrieve the service collector try { serviceCollector = (ServiceCollector)serverRuntimeContext.getServerRuntimeContextService(ServiceDiscoveryRequestListenerRegistry.SERVICE_DISCOVERY_REQUEST_LISTENER_REGISTRY); } catch (Exception e) { logger.error("error retrieving ServiceCollector service {}", e); serviceCollector = null; } if (serviceCollector == null) { return ServerErrorResponses.getInstance().getStanzaError(StanzaErrorCondition.INTERNAL_SERVER_ERROR, stanza, StanzaErrorType.CANCEL, "cannot retrieve IQ-get-info result from internal components", getErrorLanguage(serverRuntimeContext, sessionContext), null); } + // if "vysper.org" is the server entity, 'to' can either be "vysper.org", "[email protected]", "service.vysper.org". Entity to = stanza.getTo(); boolean isServerInfoRequest = false; - if (to == null || to.equals(serverRuntimeContext.getServerEnitity())) { + Entity serviceEntity = serverRuntimeContext.getServerEnitity(); + if (to == null || to.equals(serviceEntity)) { isServerInfoRequest = true; // this can only be meant to query the server - } else if (!to.isNodeSet()) { - isServerInfoRequest = serverRuntimeContext.getServerEnitity().equals(to); + } else if (!to.isNodeSet() && !to.getDomain().endsWith(serviceEntity.getDomain())) { + isServerInfoRequest = serviceEntity.equals(to); if (!isServerInfoRequest) { return ServerErrorResponses.getInstance().getStanzaError(StanzaErrorCondition.ITEM_NOT_FOUND, stanza, StanzaErrorType.CANCEL, "server does not handle info query requests for " + to.getFullQualifiedName(), getErrorLanguage(serverRuntimeContext, sessionContext), null); } } XMLElement queryElement = stanza.getFirstInnerElement(); String node = queryElement != null ? queryElement.getAttributeValue("node") : null; // collect all the info response elements List<InfoElement> elements = null; try { if (isServerInfoRequest) { elements = serviceCollector.processServerInfoRequest(new InfoRequest(stanza.getFrom(), to, node)); } else { elements = serviceCollector.processInfoRequest(new InfoRequest(stanza.getFrom(), to, node)); } } catch (ServiceDiscoveryRequestException e) { // the request yields an error StanzaErrorCondition stanzaErrorCondition = e.getErrorCondition(); if (stanzaErrorCondition == null) stanzaErrorCondition = StanzaErrorCondition.INTERNAL_SERVER_ERROR; return ServerErrorResponses.getInstance().getStanzaError(stanzaErrorCondition, stanza, StanzaErrorType.CANCEL, "disco info request failed.", getErrorLanguage(serverRuntimeContext, sessionContext), null); } //TODO check that elementSet contains at least one identity element and on feature element! // render the stanza with information collected StanzaBuilder stanzaBuilder = StanzaBuilder.createIQStanza(to, stanza.getFrom(), IQStanzaType.RESULT, stanza.getID()). startInnerElement("query"). addNamespaceAttribute(NamespaceURIs.XEP0030_SERVICE_DISCOVERY_INFO); if (node != null) { stanzaBuilder.addAttribute("node", node); } for (InfoElement infoElement : elements) { infoElement.insertElement(stanzaBuilder); } stanzaBuilder.endInnerElement(); return stanzaBuilder.getFinalStanza(); } }
false
true
protected Stanza handleGet(IQStanza stanza, ServerRuntimeContext serverRuntimeContext, SessionContext sessionContext) { ServiceCollector serviceCollector = null; // TODO if the target entity does not exist, return error/cancel/item-not-found // TODO more strictly, server can also return error/cancel/service-unaivable // retrieve the service collector try { serviceCollector = (ServiceCollector)serverRuntimeContext.getServerRuntimeContextService(ServiceDiscoveryRequestListenerRegistry.SERVICE_DISCOVERY_REQUEST_LISTENER_REGISTRY); } catch (Exception e) { logger.error("error retrieving ServiceCollector service {}", e); serviceCollector = null; } if (serviceCollector == null) { return ServerErrorResponses.getInstance().getStanzaError(StanzaErrorCondition.INTERNAL_SERVER_ERROR, stanza, StanzaErrorType.CANCEL, "cannot retrieve IQ-get-info result from internal components", getErrorLanguage(serverRuntimeContext, sessionContext), null); } Entity to = stanza.getTo(); boolean isServerInfoRequest = false; if (to == null || to.equals(serverRuntimeContext.getServerEnitity())) { isServerInfoRequest = true; // this can only be meant to query the server } else if (!to.isNodeSet()) { isServerInfoRequest = serverRuntimeContext.getServerEnitity().equals(to); if (!isServerInfoRequest) { return ServerErrorResponses.getInstance().getStanzaError(StanzaErrorCondition.ITEM_NOT_FOUND, stanza, StanzaErrorType.CANCEL, "server does not handle info query requests for " + to.getFullQualifiedName(), getErrorLanguage(serverRuntimeContext, sessionContext), null); } } XMLElement queryElement = stanza.getFirstInnerElement(); String node = queryElement != null ? queryElement.getAttributeValue("node") : null; // collect all the info response elements List<InfoElement> elements = null; try { if (isServerInfoRequest) { elements = serviceCollector.processServerInfoRequest(new InfoRequest(stanza.getFrom(), to, node)); } else { elements = serviceCollector.processInfoRequest(new InfoRequest(stanza.getFrom(), to, node)); } } catch (ServiceDiscoveryRequestException e) { // the request yields an error StanzaErrorCondition stanzaErrorCondition = e.getErrorCondition(); if (stanzaErrorCondition == null) stanzaErrorCondition = StanzaErrorCondition.INTERNAL_SERVER_ERROR; return ServerErrorResponses.getInstance().getStanzaError(stanzaErrorCondition, stanza, StanzaErrorType.CANCEL, "disco info request failed.", getErrorLanguage(serverRuntimeContext, sessionContext), null); } //TODO check that elementSet contains at least one identity element and on feature element! // render the stanza with information collected StanzaBuilder stanzaBuilder = StanzaBuilder.createIQStanza(to, stanza.getFrom(), IQStanzaType.RESULT, stanza.getID()). startInnerElement("query"). addNamespaceAttribute(NamespaceURIs.XEP0030_SERVICE_DISCOVERY_INFO); if (node != null) { stanzaBuilder.addAttribute("node", node); } for (InfoElement infoElement : elements) { infoElement.insertElement(stanzaBuilder); } stanzaBuilder.endInnerElement(); return stanzaBuilder.getFinalStanza(); }
protected Stanza handleGet(IQStanza stanza, ServerRuntimeContext serverRuntimeContext, SessionContext sessionContext) { ServiceCollector serviceCollector = null; // TODO if the target entity does not exist, return error/cancel/item-not-found // TODO more strictly, server can also return error/cancel/service-unaivable // retrieve the service collector try { serviceCollector = (ServiceCollector)serverRuntimeContext.getServerRuntimeContextService(ServiceDiscoveryRequestListenerRegistry.SERVICE_DISCOVERY_REQUEST_LISTENER_REGISTRY); } catch (Exception e) { logger.error("error retrieving ServiceCollector service {}", e); serviceCollector = null; } if (serviceCollector == null) { return ServerErrorResponses.getInstance().getStanzaError(StanzaErrorCondition.INTERNAL_SERVER_ERROR, stanza, StanzaErrorType.CANCEL, "cannot retrieve IQ-get-info result from internal components", getErrorLanguage(serverRuntimeContext, sessionContext), null); } // if "vysper.org" is the server entity, 'to' can either be "vysper.org", "[email protected]", "service.vysper.org". Entity to = stanza.getTo(); boolean isServerInfoRequest = false; Entity serviceEntity = serverRuntimeContext.getServerEnitity(); if (to == null || to.equals(serviceEntity)) { isServerInfoRequest = true; // this can only be meant to query the server } else if (!to.isNodeSet() && !to.getDomain().endsWith(serviceEntity.getDomain())) { isServerInfoRequest = serviceEntity.equals(to); if (!isServerInfoRequest) { return ServerErrorResponses.getInstance().getStanzaError(StanzaErrorCondition.ITEM_NOT_FOUND, stanza, StanzaErrorType.CANCEL, "server does not handle info query requests for " + to.getFullQualifiedName(), getErrorLanguage(serverRuntimeContext, sessionContext), null); } } XMLElement queryElement = stanza.getFirstInnerElement(); String node = queryElement != null ? queryElement.getAttributeValue("node") : null; // collect all the info response elements List<InfoElement> elements = null; try { if (isServerInfoRequest) { elements = serviceCollector.processServerInfoRequest(new InfoRequest(stanza.getFrom(), to, node)); } else { elements = serviceCollector.processInfoRequest(new InfoRequest(stanza.getFrom(), to, node)); } } catch (ServiceDiscoveryRequestException e) { // the request yields an error StanzaErrorCondition stanzaErrorCondition = e.getErrorCondition(); if (stanzaErrorCondition == null) stanzaErrorCondition = StanzaErrorCondition.INTERNAL_SERVER_ERROR; return ServerErrorResponses.getInstance().getStanzaError(stanzaErrorCondition, stanza, StanzaErrorType.CANCEL, "disco info request failed.", getErrorLanguage(serverRuntimeContext, sessionContext), null); } //TODO check that elementSet contains at least one identity element and on feature element! // render the stanza with information collected StanzaBuilder stanzaBuilder = StanzaBuilder.createIQStanza(to, stanza.getFrom(), IQStanzaType.RESULT, stanza.getID()). startInnerElement("query"). addNamespaceAttribute(NamespaceURIs.XEP0030_SERVICE_DISCOVERY_INFO); if (node != null) { stanzaBuilder.addAttribute("node", node); } for (InfoElement infoElement : elements) { infoElement.insertElement(stanzaBuilder); } stanzaBuilder.endInnerElement(); return stanzaBuilder.getFinalStanza(); }
diff --git a/MyTrack/src/com/asksven/mytrack/utils/LocationWriter.java b/MyTrack/src/com/asksven/mytrack/utils/LocationWriter.java index e0dbb7b..253f22c 100644 --- a/MyTrack/src/com/asksven/mytrack/utils/LocationWriter.java +++ b/MyTrack/src/com/asksven/mytrack/utils/LocationWriter.java @@ -1,99 +1,98 @@ /** * */ package com.asksven.mytrack.utils; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import android.content.Context; import android.content.SharedPreferences; import android.location.Location; import android.net.Uri; import android.os.Environment; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import com.asksven.andoid.common.contrib.Util; import com.asksven.android.common.utils.DataStorage; import com.asksven.android.common.utils.DateUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * @author sven * */ public class LocationWriter { private static final String TAG = "LocationWriter"; private static final String FILENAME = "MyTrack"; public static void LogLocationToFile(Context context, Location myLoc) { Uri fileUri = null; SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(context); if (!DataStorage.isExternalStorageWritable()) { Log.e(TAG, "External storage can not be written"); Toast.makeText(context, "External Storage can not be written", Toast.LENGTH_SHORT).show(); } try { // open file for writing File root; try { root = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); } catch (Exception e) { root = Environment.getExternalStorageDirectory(); } String path = root.getAbsolutePath(); // check if file can be written if (root.canWrite()) { String timestamp = DateUtils.now("yyyy-MM-dd_HHmmssSSS"); File textFile = new File(root, FILENAME + ".txt"); FileWriter fw = new FileWriter(textFile); BufferedWriter out = new BufferedWriter(fw); out.append(timestamp + ": " + "LAT=" + myLoc.getLatitude() + "LONG=" + myLoc.getLongitude() + "\n"); out.close(); File jsonFile = new File(root, FILENAME + ".json"); fw = new FileWriter(jsonFile); out = new BufferedWriter(fw); - out.append(timestamp + ": " - + "LAT=" + myLoc.getLatitude() - + "LONG=" + myLoc.getLongitude() + "\n"); + out.append("TrackEntry\n"); Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); out.append(gson.toJson(new TrackEntry(myLoc))); + out.append("\n"); out.close(); } else { Log.i(TAG, "Write error. " + Environment.getExternalStorageDirectory() + " couldn't be written"); } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } } }
false
true
public static void LogLocationToFile(Context context, Location myLoc) { Uri fileUri = null; SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(context); if (!DataStorage.isExternalStorageWritable()) { Log.e(TAG, "External storage can not be written"); Toast.makeText(context, "External Storage can not be written", Toast.LENGTH_SHORT).show(); } try { // open file for writing File root; try { root = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); } catch (Exception e) { root = Environment.getExternalStorageDirectory(); } String path = root.getAbsolutePath(); // check if file can be written if (root.canWrite()) { String timestamp = DateUtils.now("yyyy-MM-dd_HHmmssSSS"); File textFile = new File(root, FILENAME + ".txt"); FileWriter fw = new FileWriter(textFile); BufferedWriter out = new BufferedWriter(fw); out.append(timestamp + ": " + "LAT=" + myLoc.getLatitude() + "LONG=" + myLoc.getLongitude() + "\n"); out.close(); File jsonFile = new File(root, FILENAME + ".json"); fw = new FileWriter(jsonFile); out = new BufferedWriter(fw); out.append(timestamp + ": " + "LAT=" + myLoc.getLatitude() + "LONG=" + myLoc.getLongitude() + "\n"); Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); out.append(gson.toJson(new TrackEntry(myLoc))); out.close(); } else { Log.i(TAG, "Write error. " + Environment.getExternalStorageDirectory() + " couldn't be written"); } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } }
public static void LogLocationToFile(Context context, Location myLoc) { Uri fileUri = null; SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(context); if (!DataStorage.isExternalStorageWritable()) { Log.e(TAG, "External storage can not be written"); Toast.makeText(context, "External Storage can not be written", Toast.LENGTH_SHORT).show(); } try { // open file for writing File root; try { root = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS); } catch (Exception e) { root = Environment.getExternalStorageDirectory(); } String path = root.getAbsolutePath(); // check if file can be written if (root.canWrite()) { String timestamp = DateUtils.now("yyyy-MM-dd_HHmmssSSS"); File textFile = new File(root, FILENAME + ".txt"); FileWriter fw = new FileWriter(textFile); BufferedWriter out = new BufferedWriter(fw); out.append(timestamp + ": " + "LAT=" + myLoc.getLatitude() + "LONG=" + myLoc.getLongitude() + "\n"); out.close(); File jsonFile = new File(root, FILENAME + ".json"); fw = new FileWriter(jsonFile); out = new BufferedWriter(fw); out.append("TrackEntry\n"); Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); out.append(gson.toJson(new TrackEntry(myLoc))); out.append("\n"); out.close(); } else { Log.i(TAG, "Write error. " + Environment.getExternalStorageDirectory() + " couldn't be written"); } } catch (Exception e) { Log.e(TAG, "Exception: " + e.getMessage()); } }
diff --git a/src/uk/me/parabola/imgfmt/sys/ImgFS.java b/src/uk/me/parabola/imgfmt/sys/ImgFS.java index 5539f024..7dbb43b7 100644 --- a/src/uk/me/parabola/imgfmt/sys/ImgFS.java +++ b/src/uk/me/parabola/imgfmt/sys/ImgFS.java @@ -1,199 +1,207 @@ /* * Copyright (C) 2006 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * Author: Steve Ratcliffe * Create date: 26-Nov-2006 */ package uk.me.parabola.imgfmt.sys; import uk.me.parabola.log.Logger; import java.io.RandomAccessFile; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import java.util.List; import java.nio.channels.FileChannel; import uk.me.parabola.imgfmt.fs.FileSystem; import uk.me.parabola.imgfmt.fs.DirectoryEntry; import uk.me.parabola.imgfmt.fs.ImgChannel; import uk.me.parabola.imgfmt.FileSystemParam; import uk.me.parabola.imgfmt.FileExistsException; /** * The img file is really a filesystem containing several files. * It is made up of a header, a directory area and a data area which * occur in the filesystem in that order. * * @author steve */ public class ImgFS implements FileSystem { private static final Logger log = Logger.getLogger(ImgFS.class); private int blockSize = 512; private FileChannel file; // A file system consists of a header, a directory and a data area. private ImgHeader header; // There is only one directory that holds all filename and block allocation // information. private Directory directory; // The filesystem is responsible for allocating blocks private BlockManager blockManager; /** * Create an IMG file from its external filesystem name and optionally some * parameters. * * @param filename The filename eg 'gmapsupp.img' * @param params File system parameters. Can be null. * @throws FileNotFoundException If the file cannot be created. */ public ImgFS(String filename, FileSystemParam params) throws FileNotFoundException { log.info("Creating file system"); RandomAccessFile rafile = new RandomAccessFile(filename, "rw"); + try { + // Set length to zero because if you don't you can get a + // map that doesn't work. Not clear why. + rafile.setLength(0); + } catch (IOException e) { + // It doesn't matter that much. + log.warn("Could not set file length to zero"); + } file = rafile.getChannel(); header = new ImgHeader(file); header.setDirectoryStartBlock(2); // could be from params // Set the times. Date date = new Date(); header.setCreationTime(date); header.setUpdateTime(date); // The block manager allocates blocks for files. blockManager = new BlockManager(blockSize, header.getDirectoryStartBlock()); directory = new Directory(file, blockManager); if (params != null) setParams(params); // Initialise the directory. directory.init(); } /** * Set various parameters of the file system. Anything that * has not been set in <tt>params</tt> (ie is zero or null) * will not have any effect. * * @param params A set of parameters. */ private void setParams(FileSystemParam params) { int bs = params.getBlockSize(); if (bs > 0) { blockSize = bs; header.setBlockSize(bs); directory.setBlockSize(bs); } String mapdesc = params.getMapDescription(); if (mapdesc != null) header.setDescription(mapdesc); } /** * Create a new file it must not allready exist. * * @param name The file name. * @return A directory entry for the new file. */ public ImgChannel create(String name) throws FileExistsException { Dirent dir = directory.create(name); FileNode f = new FileNode(file, blockManager, dir, "w"); return f; } /** * Open a file. The returned file object can be used to read and write the * underlying file. * * @param name The file name to open. * @param mode Either "r" for read access, "w" for write access or "rw" * for both read and write. * @return A file descriptor. * @throws FileNotFoundException When the file does not exist. */ public ImgChannel open(String name, String mode) throws FileNotFoundException { if (name == null || mode == null) throw new IllegalArgumentException("null argument"); // Its wrong to do this as this routine should not throw an exception // when the file exists. Needs lookup(). // if (mode.indexOf('w') >= 0) // return create(name); throw new FileNotFoundException("File not found because it isn't implemented yet"); } /** * Lookup the file and return a directory entry for it. * * @param name The filename to look up. * @return A directory entry. * @throws IOException If an error occurs reading the directory. */ public DirectoryEntry lookup(String name) throws IOException { if (name == null) throw new IllegalArgumentException("null name argument"); throw new IOException("not implemented"); } /** * List all the files in the directory. * * @return A List of directory entries. * @throws IOException If an error occurs reading the directory. */ public List<DirectoryEntry> list() throws IOException { throw new IOException("not implemented yet"); } /** * Sync with the underlying file. All unwritten data is written out to * the underlying file. * * @throws IOException If an error occurs during the write. */ public void sync() throws IOException { header.sync(); file.position((long) header.getDirectoryStartBlock() * header.getBlockSize()); directory.sync(); } /** * Close the filesystem. Any saved data is flushed out. It is better * to explicitly sync the data out first, to be sure that it has worked. */ public void close() { try { sync(); } catch (IOException e) { log.debug("could not sync filesystem"); } } }
true
true
public ImgFS(String filename, FileSystemParam params) throws FileNotFoundException { log.info("Creating file system"); RandomAccessFile rafile = new RandomAccessFile(filename, "rw"); file = rafile.getChannel(); header = new ImgHeader(file); header.setDirectoryStartBlock(2); // could be from params // Set the times. Date date = new Date(); header.setCreationTime(date); header.setUpdateTime(date); // The block manager allocates blocks for files. blockManager = new BlockManager(blockSize, header.getDirectoryStartBlock()); directory = new Directory(file, blockManager); if (params != null) setParams(params); // Initialise the directory. directory.init(); }
public ImgFS(String filename, FileSystemParam params) throws FileNotFoundException { log.info("Creating file system"); RandomAccessFile rafile = new RandomAccessFile(filename, "rw"); try { // Set length to zero because if you don't you can get a // map that doesn't work. Not clear why. rafile.setLength(0); } catch (IOException e) { // It doesn't matter that much. log.warn("Could not set file length to zero"); } file = rafile.getChannel(); header = new ImgHeader(file); header.setDirectoryStartBlock(2); // could be from params // Set the times. Date date = new Date(); header.setCreationTime(date); header.setUpdateTime(date); // The block manager allocates blocks for files. blockManager = new BlockManager(blockSize, header.getDirectoryStartBlock()); directory = new Directory(file, blockManager); if (params != null) setParams(params); // Initialise the directory. directory.init(); }
diff --git a/com/gravitoids/helper/GravityHelper.java b/com/gravitoids/helper/GravityHelper.java index 0c74330..84e9e5f 100644 --- a/com/gravitoids/helper/GravityHelper.java +++ b/com/gravitoids/helper/GravityHelper.java @@ -1,133 +1,133 @@ package com.gravitoids.helper; import com.gravitoids.bean.GravitoidsObject; /** * Copyright (c) 2008, Michael Cook * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Michael Cook nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Michael Cook ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Michael Cook BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class GravityHelper { private static GravityHelper instance = null; private double maxInfluence = 5.0d; private double gravitationalConstant; public static synchronized GravityHelper getInstance() { if (instance == null) instance = new GravityHelper(10.0d); return instance; } public GravityHelper(double gravitationalConstant) { this.gravitationalConstant = gravitationalConstant; } private void simulateGravity(GravitoidsObject one, GravitoidsObject two, boolean moveObjectTwo) { /* * Fg = G * (M1 * M2) / R^2 (Force Gravity = constant * masses / distance squared) * Vt = V0 + At (Velocity = old velocity + acceleration) * F = M * A (Force = Mass * Acceleration) * * thus * * A = ((G * M1 * M2) / R^2) / M (Acceleration due to gravity) */ // First, make sure that there is something to move if ((!one.isMoveable()) && (!two.isMoveable())) { return; // Nothing to do } // Now the straight distance between them double distance = WrappingHelper.calculateDistanceToObject(one, two); // Figure out the force from gravity double massProduct = one.getMass() * two.getMass(); double forceOfGravity = (gravitationalConstant * massProduct) / (distance * distance); if (forceOfGravity > maxInfluence) forceOfGravity = maxInfluence; // Now the angle between the two things double angle = WrappingHelper.calculateDirectionToObject(one, two); // The numbers - double yForce = Math.sin(angle) * forceOfGravity * (one.getXPosition() > two.getXPosition() ? -1 : 1); double xForce = Math.cos(angle) * forceOfGravity * (one.getXPosition() > two.getXPosition() ? -1 : 1); + double yForce = Math.sin(angle) * forceOfGravity * (one.getYPosition() > two.getYPosition() ? -1 : 1); // Now set the new velocities, dividing by the mass so results are correct one.setXSpeed(one.getXSpeed() + (xForce / one.getMass())); one.setYSpeed(one.getYSpeed() + (yForce / one.getMass())); if (moveObjectTwo) { two.setXSpeed(two.getXSpeed() - (xForce / two.getMass())); two.setYSpeed(two.getYSpeed() - (yForce / two.getMass())); } } public void simulateGravity(GravitoidsObject one, GravitoidsObject two) { simulateGravity(one, two, true); } public void simulateGravityForOne(GravitoidsObject one, GravitoidsObject two) { simulateGravity(one, two, false); } /** * @return the maxInfluence */ public double getMaxInfluence() { return maxInfluence; } /** * @param maxInfluence the maxInfluence to set */ public void setMaxInfluence(double maxInfluence) { this.maxInfluence = maxInfluence; } /** * @return the gravitationalConstant */ public double getGravitationalConstant() { return gravitationalConstant; } /** * @param gravitationalConstant the gravitationalConstant to set */ public void setGravitationalConstant(double gravitationalConstant) { this.gravitationalConstant = gravitationalConstant; } }
false
true
private void simulateGravity(GravitoidsObject one, GravitoidsObject two, boolean moveObjectTwo) { /* * Fg = G * (M1 * M2) / R^2 (Force Gravity = constant * masses / distance squared) * Vt = V0 + At (Velocity = old velocity + acceleration) * F = M * A (Force = Mass * Acceleration) * * thus * * A = ((G * M1 * M2) / R^2) / M (Acceleration due to gravity) */ // First, make sure that there is something to move if ((!one.isMoveable()) && (!two.isMoveable())) { return; // Nothing to do } // Now the straight distance between them double distance = WrappingHelper.calculateDistanceToObject(one, two); // Figure out the force from gravity double massProduct = one.getMass() * two.getMass(); double forceOfGravity = (gravitationalConstant * massProduct) / (distance * distance); if (forceOfGravity > maxInfluence) forceOfGravity = maxInfluence; // Now the angle between the two things double angle = WrappingHelper.calculateDirectionToObject(one, two); // The numbers double yForce = Math.sin(angle) * forceOfGravity * (one.getXPosition() > two.getXPosition() ? -1 : 1); double xForce = Math.cos(angle) * forceOfGravity * (one.getXPosition() > two.getXPosition() ? -1 : 1); // Now set the new velocities, dividing by the mass so results are correct one.setXSpeed(one.getXSpeed() + (xForce / one.getMass())); one.setYSpeed(one.getYSpeed() + (yForce / one.getMass())); if (moveObjectTwo) { two.setXSpeed(two.getXSpeed() - (xForce / two.getMass())); two.setYSpeed(two.getYSpeed() - (yForce / two.getMass())); } }
private void simulateGravity(GravitoidsObject one, GravitoidsObject two, boolean moveObjectTwo) { /* * Fg = G * (M1 * M2) / R^2 (Force Gravity = constant * masses / distance squared) * Vt = V0 + At (Velocity = old velocity + acceleration) * F = M * A (Force = Mass * Acceleration) * * thus * * A = ((G * M1 * M2) / R^2) / M (Acceleration due to gravity) */ // First, make sure that there is something to move if ((!one.isMoveable()) && (!two.isMoveable())) { return; // Nothing to do } // Now the straight distance between them double distance = WrappingHelper.calculateDistanceToObject(one, two); // Figure out the force from gravity double massProduct = one.getMass() * two.getMass(); double forceOfGravity = (gravitationalConstant * massProduct) / (distance * distance); if (forceOfGravity > maxInfluence) forceOfGravity = maxInfluence; // Now the angle between the two things double angle = WrappingHelper.calculateDirectionToObject(one, two); // The numbers double xForce = Math.cos(angle) * forceOfGravity * (one.getXPosition() > two.getXPosition() ? -1 : 1); double yForce = Math.sin(angle) * forceOfGravity * (one.getYPosition() > two.getYPosition() ? -1 : 1); // Now set the new velocities, dividing by the mass so results are correct one.setXSpeed(one.getXSpeed() + (xForce / one.getMass())); one.setYSpeed(one.getYSpeed() + (yForce / one.getMass())); if (moveObjectTwo) { two.setXSpeed(two.getXSpeed() - (xForce / two.getMass())); two.setYSpeed(two.getYSpeed() - (yForce / two.getMass())); } }
diff --git a/src/java/org/apache/cassandra/cql3/statements/DropUserStatement.java b/src/java/org/apache/cassandra/cql3/statements/DropUserStatement.java index ae6cf6743..d55566c64 100644 --- a/src/java/org/apache/cassandra/cql3/statements/DropUserStatement.java +++ b/src/java/org/apache/cassandra/cql3/statements/DropUserStatement.java @@ -1,66 +1,66 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.cql3.statements; import org.apache.cassandra.auth.Auth; import org.apache.cassandra.auth.AuthenticatedUser; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.exceptions.InvalidRequestException; import org.apache.cassandra.exceptions.RequestExecutionException; import org.apache.cassandra.exceptions.RequestValidationException; import org.apache.cassandra.exceptions.UnauthorizedException; import org.apache.cassandra.service.ClientState; import org.apache.cassandra.transport.messages.ResultMessage; public class DropUserStatement extends AuthenticationStatement { private final String username; public DropUserStatement(String username) { this.username = username; } public void validate(ClientState state) throws RequestValidationException { // validate login here before checkAccess to avoid leaking user existence to anonymous users. state.ensureNotAnonymous(); if (!Auth.isExistingUser(username)) - throw new InvalidRequestException(String.format("User %s doesn't exists", username)); + throw new InvalidRequestException(String.format("User %s doesn't exist", username)); AuthenticatedUser user = state.getUser(); if (user != null && user.getName().equals(username)) throw new InvalidRequestException("Users aren't allowed to DROP themselves"); } public void checkAccess(ClientState state) throws UnauthorizedException { if (!state.getUser().isSuper()) throw new UnauthorizedException("Only superusers are allowed to perfrom DROP USER queries"); } public ResultMessage execute(ClientState state) throws RequestValidationException, RequestExecutionException { // clean up permissions after the dropped user. DatabaseDescriptor.getAuthorizer().revokeAll(username); Auth.deleteUser(username); DatabaseDescriptor.getAuthenticator().drop(username); return null; } }
true
true
public void validate(ClientState state) throws RequestValidationException { // validate login here before checkAccess to avoid leaking user existence to anonymous users. state.ensureNotAnonymous(); if (!Auth.isExistingUser(username)) throw new InvalidRequestException(String.format("User %s doesn't exists", username)); AuthenticatedUser user = state.getUser(); if (user != null && user.getName().equals(username)) throw new InvalidRequestException("Users aren't allowed to DROP themselves"); }
public void validate(ClientState state) throws RequestValidationException { // validate login here before checkAccess to avoid leaking user existence to anonymous users. state.ensureNotAnonymous(); if (!Auth.isExistingUser(username)) throw new InvalidRequestException(String.format("User %s doesn't exist", username)); AuthenticatedUser user = state.getUser(); if (user != null && user.getName().equals(username)) throw new InvalidRequestException("Users aren't allowed to DROP themselves"); }
diff --git a/src/main/java/com/moshavit/framework/CORSFilter.java b/src/main/java/com/moshavit/framework/CORSFilter.java index 959339d..1b3c082 100644 --- a/src/main/java/com/moshavit/framework/CORSFilter.java +++ b/src/main/java/com/moshavit/framework/CORSFilter.java @@ -1,29 +1,33 @@ /* User: Ophir Date: 29/04/13 Time: 10:49 */ package com.moshavit.framework; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CORSFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - ((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*"); + HttpServletResponse httpResponse = (HttpServletResponse) response; + httpResponse.addHeader("Access-Control-Allow-Origin", "*"); chain.doFilter(request, response); + httpResponse.addHeader("Access-Control-Allow-Origin", "*"); + httpResponse.addHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE"); + httpResponse.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }
false
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*"); chain.doFilter(request, response); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.addHeader("Access-Control-Allow-Origin", "*"); chain.doFilter(request, response); httpResponse.addHeader("Access-Control-Allow-Origin", "*"); httpResponse.addHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE"); httpResponse.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); }
diff --git a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java index 48c6f75..797e94f 100644 --- a/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java +++ b/src/main/java/org/dasein/cloud/openstack/nova/os/network/NovaSecurityGroup.java @@ -1,697 +1,705 @@ /** * Copyright (C) 2009-2013 Dell, Inc. * See annotations for authorship information * * ==================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ package org.dasein.cloud.openstack.nova.os.network; import org.apache.http.HttpStatus; import org.apache.log4j.Logger; import org.dasein.cloud.CloudErrorType; import org.dasein.cloud.CloudException; import org.dasein.cloud.InternalException; import org.dasein.cloud.OperationNotSupportedException; import org.dasein.cloud.Requirement; import org.dasein.cloud.ResourceStatus; import org.dasein.cloud.network.AbstractFirewallSupport; import org.dasein.cloud.network.Direction; import org.dasein.cloud.network.Firewall; import org.dasein.cloud.network.FirewallCreateOptions; import org.dasein.cloud.network.FirewallRule; import org.dasein.cloud.network.Permission; import org.dasein.cloud.network.Protocol; import org.dasein.cloud.network.RuleTarget; import org.dasein.cloud.network.RuleTargetType; import org.dasein.cloud.openstack.nova.os.NovaException; import org.dasein.cloud.openstack.nova.os.NovaMethod; import org.dasein.cloud.openstack.nova.os.NovaOpenStack; import org.dasein.cloud.util.APITrace; import org.dasein.util.CalendarWrapper; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Locale; /** * Support for OpenStack security groups. * @author George Reese ([email protected]) * @since 2011.10 * @version 2011.10 * @version 2012.04.1 Added some intelligence around features Rackspace does not support * @version 2013.04 Added API tracing */ public class NovaSecurityGroup extends AbstractFirewallSupport { static private final Logger logger = NovaOpenStack.getLogger(NovaSecurityGroup.class, "std"); NovaSecurityGroup(NovaOpenStack cloud) { super(cloud); } private @Nonnull String getTenantId() throws CloudException, InternalException { return ((NovaOpenStack)getProvider()).getAuthenticationContext().getTenantId(); } @Override public @Nonnull String authorize(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull Permission permission, @Nonnull RuleTarget sourceEndpoint, @Nonnull Protocol protocol, @Nonnull RuleTarget destinationEndpoint, int beginPort, int endPort, @Nonnegative int precedence) throws CloudException, InternalException { APITrace.begin(getProvider(), "Firewall.authorize"); try { if( direction.equals(Direction.EGRESS) ) { throw new OperationNotSupportedException(getProvider().getCloudName() + " does not support egress rules."); } HashMap<String,Object> wrapper = new HashMap<String,Object>(); HashMap<String,Object> json = new HashMap<String,Object>(); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); json.put("ip_protocol", protocol.name().toLowerCase()); json.put("from_port", beginPort); json.put("to_port", endPort); json.put("parent_group_id", firewallId); switch( sourceEndpoint.getRuleTargetType() ) { case CIDR: json.put("cidr", sourceEndpoint.getCidr()); break; case VLAN: throw new OperationNotSupportedException("Cannot target VLANs with firewall rules"); case VM: throw new OperationNotSupportedException("Cannot target virtual machines with firewall rules"); case GLOBAL: Firewall targetGroup = getFirewall(sourceEndpoint.getProviderFirewallId()); if( targetGroup == null ) { throw new CloudException("No such source endpoint firewall: " + sourceEndpoint.getProviderFirewallId()); } json.put("group_id", targetGroup.getProviderFirewallId()); break; } wrapper.put("security_group_rule", json); JSONObject result = method.postServers("/os-security-group-rules", null, new JSONObject(wrapper), false); if( result != null && result.has("security_group_rule") ) { try { JSONObject rule = result.getJSONObject("security_group_rule"); return rule.getString("id"); } catch( JSONException e ) { logger.error("Invalid JSON returned from rule creation: " + e.getMessage()); throw new CloudException(e); } } logger.error("authorize(): No firewall rule was created by the create attempt, and no error was returned"); throw new CloudException("No firewall rule was created"); } finally { APITrace.end(); } } @Override public @Nonnull String create(@Nonnull FirewallCreateOptions options) throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.create"); try { if( options.getProviderVlanId() != null ) { throw new OperationNotSupportedException("Creating IP addresses in VLANs is not supported"); } HashMap<String,Object> wrapper = new HashMap<String,Object>(); HashMap<String,Object> json = new HashMap<String,Object>(); NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); json.put("name", options.getName()); json.put("description", options.getDescription()); wrapper.put("security_group", json); JSONObject result = method.postServers("/os-security-groups", null, new JSONObject(wrapper), false); if( result != null && result.has("security_group") ) { try { JSONObject ob = result.getJSONObject("security_group"); Firewall fw = toFirewall(ob); if( fw != null ) { String id = fw.getProviderFirewallId(); if( id != null ) { return id; } } } catch( JSONException e ) { logger.error("create(): Unable to understand create response: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } } logger.error("create(): No firewall was created by the create attempt, and no error was returned"); throw new CloudException("No firewall was created"); } finally { APITrace.end(); } } @Override public void delete(@Nonnull String firewallId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.delete"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR; do { try { method.deleteServers("/os-security-groups", firewallId); return; } catch( NovaException e ) { if( e.getHttpCode() != HttpStatus.SC_CONFLICT ) { throw e; } } try { Thread.sleep(CalendarWrapper.MINUTE); } catch( InterruptedException e ) { /* ignore */ } } while( System.currentTimeMillis() < timeout ); } finally { APITrace.end(); } } @Override public @Nullable Firewall getFirewall(@Nonnull String firewallId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.getFirewall"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/os-security-groups", firewallId, false); if( ob == null ) { return null; } try { if( ob.has("security_group") ) { JSONObject json = ob.getJSONObject("security_group"); Firewall fw = toFirewall(json); if( fw != null ) { return fw; } } } catch( JSONException e ) { logger.error("getRule(): Unable to identify expected values in JSON: " + e.getMessage()); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security group"); } return null; } finally { APITrace.end(); } } @Override public @Nonnull String getProviderTermForFirewall(@Nonnull Locale locale) { return "security group"; } @Override public @Nonnull Collection<FirewallRule> getRules(@Nonnull String firewallId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.getRules"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/os-security-groups", firewallId, false); if( ob == null ) { return null; } try { if( ob.has("security_group") ) { JSONObject json = ob.getJSONObject("security_group"); if( !json.has("rules") ) { return Collections.emptyList(); } ArrayList<FirewallRule> rules = new ArrayList<FirewallRule>(); JSONArray arr = json.getJSONArray("rules"); Iterable<Firewall> myFirewalls = null; for( int i=0; i<arr.length(); i++ ) { JSONObject rule = arr.getJSONObject(i); int startPort = -1, endPort = -1; Protocol protocol = null; String ruleId = null; if( rule.has("id") ) { ruleId = rule.getString("id"); } if( ruleId == null ) { continue; } RuleTarget sourceEndpoint = null; if( rule.has("ip_range") ) { JSONObject range = rule.getJSONObject("ip_range"); if( range.has("cidr") ) { sourceEndpoint = RuleTarget.getCIDR(range.getString("cidr")); } } if( rule.has("group") ) { JSONObject g = rule.getJSONObject("group"); String id = (g.has("id") ? g.getString("id") : null); if( id != null ) { sourceEndpoint = RuleTarget.getGlobal(id); } else { String o = (g.has("tenant_id") ? g.getString("tenant_id") : null); if( getTenantId().equals(o) ) { String n = (g.has("name") ? g.getString("name") : null); if( n != null ) { if( myFirewalls == null ) { myFirewalls = list(); } for( Firewall fw : myFirewalls ) { if( fw.getName().equals(n) ) { sourceEndpoint = RuleTarget.getGlobal(fw.getProviderFirewallId()); break; } } } } } } if( sourceEndpoint == null ) { continue; } if( rule.has("from_port") ) { startPort = rule.getInt("from_port"); } if( rule.has("to_port") ) { endPort = rule.getInt("to_port"); } if( startPort == -1 && endPort != -1 ) { startPort = endPort; } else if( endPort == -1 && startPort != -1 ) { endPort = startPort; } if( startPort > endPort ) { int s = startPort; startPort = endPort; endPort = s; } if( rule.has("ip_protocol") ) { - protocol = Protocol.valueOf(rule.getString("ip_protocol").toUpperCase()); + /* + * Note: the nova api returns null for 'Any' + */ + String testAny = rule.getString("ip_protocol"); + if (testAny == null || testAny.equalsIgnoreCase("null")) { + protocol = Protocol.ANY; + } else { + protocol = Protocol.valueOf(rule.getString("ip_protocol").toUpperCase()); + } } if( protocol == null ) { protocol = Protocol.TCP; } rules.add(FirewallRule.getInstance(ruleId, firewallId, sourceEndpoint, Direction.INGRESS, protocol, Permission.ALLOW, RuleTarget.getGlobal(firewallId), startPort, endPort)); } return rules; } } catch( JSONException e ) { logger.error("getRules(): Unable to identify expected values in JSON: " + e.getMessage()); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups"); } return null; } finally { APITrace.end(); } } @Override public @Nonnull Requirement identifyPrecedenceRequirement(boolean inVlan) throws InternalException, CloudException { return Requirement.NONE; } private boolean verifySupport() throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.verifySupport"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); try { method.getServers("/os-security-groups", null, false); return true; } catch( CloudException e ) { if( e.getHttpCode() == 404 ) { return false; } throw e; } } finally { APITrace.end(); } } @SuppressWarnings("SimplifiableIfStatement") @Override public boolean isSubscribed() throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.isSubscribed"); try { if( ((NovaOpenStack)getProvider()).getMajorVersion() > 1 && ((NovaOpenStack)getProvider()).getComputeServices().getVirtualMachineSupport().isSubscribed() ) { return verifySupport(); } if( ((NovaOpenStack)getProvider()).getMajorVersion() == 1 && ((NovaOpenStack)getProvider()).getMinorVersion() >= 1 && ((NovaOpenStack)getProvider()).getComputeServices().getVirtualMachineSupport().isSubscribed() ) { return verifySupport(); } return false; } finally { APITrace.end(); } } @Override public boolean isZeroPrecedenceHighest() throws InternalException, CloudException { return true; // nonsense since no precedence is supported } @Override public @Nonnull Collection<Firewall> list() throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.list"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/os-security-groups", null, false); ArrayList<Firewall> firewalls = new ArrayList<Firewall>(); try { if( ob != null && ob.has("security_groups") ) { JSONArray list = ob.getJSONArray("security_groups"); for( int i=0; i<list.length(); i++ ) { JSONObject json = list.getJSONObject(i); Firewall fw = toFirewall(json); if( fw != null ) { firewalls.add(fw); } } } } catch( JSONException e ) { logger.error("list(): Unable to identify expected values in JSON: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups in " + ob.toString()); } return firewalls; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<ResourceStatus> listFirewallStatus() throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.listFirewallStatus"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/os-security-groups", null, false); ArrayList<ResourceStatus> firewalls = new ArrayList<ResourceStatus>(); try { if( ob != null && ob.has("security_groups") ) { JSONArray list = ob.getJSONArray("security_groups"); for( int i=0; i<list.length(); i++ ) { JSONObject json = list.getJSONObject(i); try { ResourceStatus fw = toStatus(json); if( fw != null ) { firewalls.add(fw); } } catch( JSONException e ) { throw new CloudException("Invalid JSON from cloud: " + e.getMessage()); } } } } catch( JSONException e ) { throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups in " + ob.toString()); } return firewalls; } finally { APITrace.end(); } } @Override public @Nonnull Iterable<RuleTargetType> listSupportedDestinationTypes(boolean inVlan) throws InternalException, CloudException { if( inVlan ) { return Collections.emptyList(); } return Collections.singletonList(RuleTargetType.GLOBAL); } @Override public @Nonnull Iterable<Direction> listSupportedDirections(boolean inVlan) throws InternalException, CloudException { if( inVlan ) { return Collections.emptyList(); } return Collections.singletonList(Direction.INGRESS); } @Override public @Nonnull Iterable<Permission> listSupportedPermissions(boolean inVlan) throws InternalException, CloudException { if( inVlan ) { return Collections.emptyList(); } return Collections.singletonList(Permission.ALLOW); } @Override public @Nonnull Iterable<RuleTargetType> listSupportedSourceTypes(boolean inVlan) throws InternalException, CloudException { if( inVlan ) { return Collections.emptyList(); } ArrayList<RuleTargetType> list= new ArrayList<RuleTargetType>(); list.add(RuleTargetType.CIDR); list.add(RuleTargetType.GLOBAL); return list; } @Override public void revoke(@Nonnull String providerFirewallRuleId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.revoke"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR; do { try { method.deleteServers("/os-security-group-rules", providerFirewallRuleId); return; } catch( NovaException e ) { if( e.getHttpCode() != HttpStatus.SC_CONFLICT ) { throw e; } } try { Thread.sleep(CalendarWrapper.MINUTE); } catch( InterruptedException e ) { /* ignore */ } } while( System.currentTimeMillis() < timeout ); } finally { APITrace.end(); } } @Override @Deprecated public void revoke(@Nonnull String firewallId, @Nonnull String cidr, @Nonnull Protocol protocol, int beginPort, int endPort) throws CloudException, InternalException { revoke(firewallId, Direction.INGRESS, Permission.ALLOW, cidr, protocol, RuleTarget.getGlobal(firewallId), beginPort, endPort); } @Override @Deprecated public void revoke(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull String cidr, @Nonnull Protocol protocol, int beginPort, int endPort) throws CloudException, InternalException { revoke(firewallId, direction, Permission.ALLOW, cidr, protocol, RuleTarget.getGlobal(firewallId), beginPort, endPort); } @Override @Deprecated public void revoke(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull Permission permission, @Nonnull String source, @Nonnull Protocol protocol, int beginPort, int endPort) throws CloudException, InternalException { revoke(firewallId, direction, permission, source, protocol, RuleTarget.getGlobal(firewallId), beginPort, endPort); } @Override public void revoke(@Nonnull String firewallId, @Nonnull Direction direction, @Nonnull Permission permission, @Nonnull String source, @Nonnull Protocol protocol, @Nonnull RuleTarget target, int beginPort, int endPort) throws CloudException, InternalException { APITrace.begin(getProvider(), "Firewall.revoke"); try { if( direction.equals(Direction.EGRESS) ) { throw new OperationNotSupportedException(getProvider().getCloudName() + " does not support egress rules."); } FirewallRule targetRule = null; for( FirewallRule rule : getRules(firewallId) ) { RuleTarget t = rule.getSourceEndpoint(); if( t.getRuleTargetType().equals(RuleTargetType.CIDR) && source.equals(t.getCidr()) ) { RuleTarget rt = rule.getDestinationEndpoint(); if( target.getRuleTargetType().equals(rt.getRuleTargetType()) ) { boolean matches = false; switch( rt.getRuleTargetType() ) { case CIDR: //noinspection ConstantConditions matches = target.getCidr().equals(rt.getCidr()); break; case GLOBAL: //noinspection ConstantConditions matches = target.getProviderFirewallId().equals(rt.getProviderFirewallId()); break; case VLAN: //noinspection ConstantConditions matches = target.getProviderVlanId().equals(rt.getProviderVlanId()); break; case VM: //noinspection ConstantConditions matches = target.getProviderVirtualMachineId().equals(rt.getProviderVirtualMachineId()); break; } if( matches && rule.getProtocol().equals(protocol) && rule.getPermission().equals(permission) && rule.getDirection().equals(direction) ) { if( rule.getStartPort() == beginPort && rule.getEndPort() == endPort ) { targetRule = rule; break; } } } } else if( t.getRuleTargetType().equals(RuleTargetType.GLOBAL) && source.equals(t.getProviderFirewallId()) ) { RuleTarget rt = rule.getDestinationEndpoint(); if( target.getRuleTargetType().equals(rt.getRuleTargetType()) ) { boolean matches = false; switch( rt.getRuleTargetType() ) { case CIDR: //noinspection ConstantConditions matches = target.getCidr().equals(rt.getCidr()); break; case GLOBAL: //noinspection ConstantConditions matches = target.getProviderFirewallId().equals(rt.getProviderFirewallId()); break; case VLAN: //noinspection ConstantConditions matches = target.getProviderVlanId().equals(rt.getProviderVlanId()); break; case VM: //noinspection ConstantConditions matches = target.getProviderVirtualMachineId().equals(rt.getProviderVirtualMachineId()); break; } if( matches && rule.getProtocol().equals(protocol) && rule.getPermission().equals(permission) && rule.getDirection().equals(direction) ) { if( rule.getStartPort() == beginPort && rule.getEndPort() == endPort ) { targetRule = rule; break; } } } } } if( targetRule == null ) { throw new CloudException("No such firewall rule"); } revoke(targetRule.getProviderRuleId()); } finally { APITrace.end(); } } @Override public boolean supportsRules(@Nonnull Direction direction, @Nonnull Permission permission, boolean inVlan) throws CloudException, InternalException { return (!inVlan && Direction.INGRESS.equals(direction) && Permission.ALLOW.equals(permission)); } @Override public boolean supportsFirewallSources() throws CloudException, InternalException { return true; } private @Nullable Firewall toFirewall(@Nonnull JSONObject json) throws CloudException, InternalException { try { Firewall fw = new Firewall(); String id = null, name = null; fw.setActive(true); fw.setAvailable(true); fw.setProviderVlanId(null); String regionId = getContext().getRegionId(); fw.setRegionId(regionId == null ? "" : regionId); if( json.has("id") ) { id = json.getString("id"); } if( json.has("name") ) { name = json.getString("name"); } if( json.has("description") ) { fw.setDescription(json.getString("description")); } if( id == null ) { return null; } fw.setProviderFirewallId(id); if( name == null ) { name = id; } fw.setName(name); if( fw.getDescription() == null ) { fw.setDescription(name); } return fw; } catch( JSONException e ) { throw new InternalException(e); } } private @Nullable ResourceStatus toStatus(@Nonnull JSONObject json) throws JSONException { String id = null; if( json.has("id") ) { id = json.getString("id"); } if( id == null ) { return null; } return new ResourceStatus(id, true); } }
true
true
public @Nonnull Collection<FirewallRule> getRules(@Nonnull String firewallId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.getRules"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/os-security-groups", firewallId, false); if( ob == null ) { return null; } try { if( ob.has("security_group") ) { JSONObject json = ob.getJSONObject("security_group"); if( !json.has("rules") ) { return Collections.emptyList(); } ArrayList<FirewallRule> rules = new ArrayList<FirewallRule>(); JSONArray arr = json.getJSONArray("rules"); Iterable<Firewall> myFirewalls = null; for( int i=0; i<arr.length(); i++ ) { JSONObject rule = arr.getJSONObject(i); int startPort = -1, endPort = -1; Protocol protocol = null; String ruleId = null; if( rule.has("id") ) { ruleId = rule.getString("id"); } if( ruleId == null ) { continue; } RuleTarget sourceEndpoint = null; if( rule.has("ip_range") ) { JSONObject range = rule.getJSONObject("ip_range"); if( range.has("cidr") ) { sourceEndpoint = RuleTarget.getCIDR(range.getString("cidr")); } } if( rule.has("group") ) { JSONObject g = rule.getJSONObject("group"); String id = (g.has("id") ? g.getString("id") : null); if( id != null ) { sourceEndpoint = RuleTarget.getGlobal(id); } else { String o = (g.has("tenant_id") ? g.getString("tenant_id") : null); if( getTenantId().equals(o) ) { String n = (g.has("name") ? g.getString("name") : null); if( n != null ) { if( myFirewalls == null ) { myFirewalls = list(); } for( Firewall fw : myFirewalls ) { if( fw.getName().equals(n) ) { sourceEndpoint = RuleTarget.getGlobal(fw.getProviderFirewallId()); break; } } } } } } if( sourceEndpoint == null ) { continue; } if( rule.has("from_port") ) { startPort = rule.getInt("from_port"); } if( rule.has("to_port") ) { endPort = rule.getInt("to_port"); } if( startPort == -1 && endPort != -1 ) { startPort = endPort; } else if( endPort == -1 && startPort != -1 ) { endPort = startPort; } if( startPort > endPort ) { int s = startPort; startPort = endPort; endPort = s; } if( rule.has("ip_protocol") ) { protocol = Protocol.valueOf(rule.getString("ip_protocol").toUpperCase()); } if( protocol == null ) { protocol = Protocol.TCP; } rules.add(FirewallRule.getInstance(ruleId, firewallId, sourceEndpoint, Direction.INGRESS, protocol, Permission.ALLOW, RuleTarget.getGlobal(firewallId), startPort, endPort)); } return rules; } } catch( JSONException e ) { logger.error("getRules(): Unable to identify expected values in JSON: " + e.getMessage()); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups"); } return null; } finally { APITrace.end(); } }
public @Nonnull Collection<FirewallRule> getRules(@Nonnull String firewallId) throws InternalException, CloudException { APITrace.begin(getProvider(), "Firewall.getRules"); try { NovaMethod method = new NovaMethod((NovaOpenStack)getProvider()); JSONObject ob = method.getServers("/os-security-groups", firewallId, false); if( ob == null ) { return null; } try { if( ob.has("security_group") ) { JSONObject json = ob.getJSONObject("security_group"); if( !json.has("rules") ) { return Collections.emptyList(); } ArrayList<FirewallRule> rules = new ArrayList<FirewallRule>(); JSONArray arr = json.getJSONArray("rules"); Iterable<Firewall> myFirewalls = null; for( int i=0; i<arr.length(); i++ ) { JSONObject rule = arr.getJSONObject(i); int startPort = -1, endPort = -1; Protocol protocol = null; String ruleId = null; if( rule.has("id") ) { ruleId = rule.getString("id"); } if( ruleId == null ) { continue; } RuleTarget sourceEndpoint = null; if( rule.has("ip_range") ) { JSONObject range = rule.getJSONObject("ip_range"); if( range.has("cidr") ) { sourceEndpoint = RuleTarget.getCIDR(range.getString("cidr")); } } if( rule.has("group") ) { JSONObject g = rule.getJSONObject("group"); String id = (g.has("id") ? g.getString("id") : null); if( id != null ) { sourceEndpoint = RuleTarget.getGlobal(id); } else { String o = (g.has("tenant_id") ? g.getString("tenant_id") : null); if( getTenantId().equals(o) ) { String n = (g.has("name") ? g.getString("name") : null); if( n != null ) { if( myFirewalls == null ) { myFirewalls = list(); } for( Firewall fw : myFirewalls ) { if( fw.getName().equals(n) ) { sourceEndpoint = RuleTarget.getGlobal(fw.getProviderFirewallId()); break; } } } } } } if( sourceEndpoint == null ) { continue; } if( rule.has("from_port") ) { startPort = rule.getInt("from_port"); } if( rule.has("to_port") ) { endPort = rule.getInt("to_port"); } if( startPort == -1 && endPort != -1 ) { startPort = endPort; } else if( endPort == -1 && startPort != -1 ) { endPort = startPort; } if( startPort > endPort ) { int s = startPort; startPort = endPort; endPort = s; } if( rule.has("ip_protocol") ) { /* * Note: the nova api returns null for 'Any' */ String testAny = rule.getString("ip_protocol"); if (testAny == null || testAny.equalsIgnoreCase("null")) { protocol = Protocol.ANY; } else { protocol = Protocol.valueOf(rule.getString("ip_protocol").toUpperCase()); } } if( protocol == null ) { protocol = Protocol.TCP; } rules.add(FirewallRule.getInstance(ruleId, firewallId, sourceEndpoint, Direction.INGRESS, protocol, Permission.ALLOW, RuleTarget.getGlobal(firewallId), startPort, endPort)); } return rules; } } catch( JSONException e ) { logger.error("getRules(): Unable to identify expected values in JSON: " + e.getMessage()); throw new CloudException(CloudErrorType.COMMUNICATION, 200, "invalidJson", "Missing JSON element for security groups"); } return null; } finally { APITrace.end(); } }
diff --git a/org.aspectj.ajdt.core/src/org/aspectj/tools/ajc/Main.java b/org.aspectj.ajdt.core/src/org/aspectj/tools/ajc/Main.java index de78dbae0..de8395967 100644 --- a/org.aspectj.ajdt.core/src/org/aspectj/tools/ajc/Main.java +++ b/org.aspectj.ajdt.core/src/org/aspectj/tools/ajc/Main.java @@ -1,709 +1,709 @@ /* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.tools.ajc; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.List; import org.aspectj.bridge.AbortException; import org.aspectj.bridge.ICommand; import org.aspectj.bridge.IMessage; import org.aspectj.bridge.IMessageHandler; import org.aspectj.bridge.IMessageHolder; import org.aspectj.bridge.ISourceLocation; import org.aspectj.bridge.Message; import org.aspectj.bridge.MessageHandler; import org.aspectj.bridge.MessageUtil; import org.aspectj.bridge.ReflectionFactory; import org.aspectj.bridge.Version; import org.aspectj.util.FileUtil; import org.aspectj.util.LangUtil; /** * Programmatic and command-line interface to AspectJ compiler. * The compiler is an ICommand obtained by reflection. * Not thread-safe. * By default, messages are printed as they are emitted; * info messages go to the output stream, and * warnings and errors go to the error stream. * <p> * Clients can handle all messages by registering a holder: * <pre>Main main = new Main(); * IMessageHolder holder = new MessageHandler(); * main.setHolder(holder);</pre> * Clients can get control after each command completes * by installing a Runnable: * <pre>main.setCompletionRunner(new Runnable() {..});</pre> * */ public class Main { /** Header used when rendering exceptions for users */ public static final String THROWN_PREFIX = "Exception thrown from AspectJ "+ Version.text + LangUtil.EOL + ""+ LangUtil.EOL + "This might be logged as a bug already -- find current bugs at" + LangUtil.EOL + " http://bugs.eclipse.org/bugs/buglist.cgi?product=AspectJ&component=Compiler" + LangUtil.EOL + "" + LangUtil.EOL + "Bugs for exceptions thrown have titles File:line from the top stack, " + LangUtil.EOL + "e.g., \"SomeFile.java:243\"" + LangUtil.EOL + "" + LangUtil.EOL + "If you don't find the exception below in a bug, please add a new bug" + LangUtil.EOL + "at http://bugs.eclipse.org/bugs/enter_bug.cgi?product=AspectJ" + LangUtil.EOL + "To make the bug a priority, please include a test program" + LangUtil.EOL + "that can reproduce this exception." + LangUtil.EOL; private static final String OUT_OF_MEMORY_MSG = "AspectJ " + Version.text + " ran out of memory during compilation:" + LangUtil.EOL + LangUtil.EOL + "Please increase the memory available to ajc by editing the ajc script " + LangUtil.EOL + "found in your AspectJ installation directory. The -Xmx parameter value" + LangUtil.EOL + "should be increased from 64M (default) to 128M or even 256M." + LangUtil.EOL + LangUtil.EOL + "See the AspectJ FAQ available from the documentation link" + LangUtil.EOL + "on the AspectJ home page at http://www.eclipse.org/aspectj"; /** @param args the String[] of command-line arguments */ public static void main(String[] args) throws IOException { new Main().runMain(args, true); } /** * Convenience method to run ajc and collect String lists of messages. * This can be reflectively invoked with the * List collecting parameters supplied by a parent class loader. * The String messages take the same form as command-line messages. * @param args the String[] args to pass to the compiler * @param useSystemExit if true and errors, return System.exit(errs) * @param fails the List sink, if any, for String failure (or worse) messages * @param errors the List sink, if any, for String error messages * @param warnings the List sink, if any, for String warning messages * @param info the List sink, if any, for String info messages * @return number of messages reported with level ERROR or above * @throws any unchecked exceptions the compiler does */ public static int bareMain( String[] args, boolean useSystemExit, List fails, List errors, List warnings, List infos) { Main main = new Main(); MessageHandler holder = new MessageHandler(); main.setHolder(holder); try { main.runMain(args, useSystemExit); } finally { readMessages(holder, IMessage.FAIL, true, fails); readMessages(holder, IMessage.ERROR, false, errors); readMessages(holder, IMessage.WARNING, false, warnings); readMessages(holder, IMessage.INFO, false, infos); } return holder.numMessages(IMessage.ERROR, true); } /** Read messages of a given kind into a List as String */ private static void readMessages( IMessageHolder holder, IMessage.Kind kind, boolean orGreater, List sink) { if ((null == sink) || (null == holder)) { return; } IMessage[] messages = holder.getMessages(kind, orGreater); if (!LangUtil.isEmpty(messages)) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < messages.length; i++) { sink.add(MessagePrinter.render(messages[i])); } } } /** * @return String rendering throwable as compiler error for user/console, * including information on how to report as a bug. * @throws NullPointerException if thrown is null */ public static String renderExceptionForUser(Throwable thrown) { String m = thrown.getMessage(); return THROWN_PREFIX + (null != m ? m + "\n": "") + LangUtil.renderException(thrown, true); } /** append nothing if numItems is 0, * numItems + label + (numItems > 1? "s" : "") otherwise, * prefixing with " " if sink has content */ private static void appendNLabel(StringBuffer sink, String label, int numItems) { if (0 == numItems) { return; } if (0 < sink.length()) { sink.append(", "); } sink.append(numItems + " "); if (!LangUtil.isEmpty(label)) { sink.append(label); } if (1 < numItems) { sink.append("s"); } } /** control iteration/continuation for command (compiler) */ protected CommandController controller; /** ReflectionFactory identifier for command (compiler) */ protected String commandName; /** client-set message sink */ private IMessageHolder clientHolder; /** internally-set message sink */ protected final MessageHandler ourHandler; private int lastFails; private int lastErrors; /** if not null, run this synchronously after each compile completes */ private Runnable completionRunner; public Main() { controller = new CommandController(); commandName = ReflectionFactory.ECLIPSE; ourHandler = new MessageHandler(true); } /** * Run without throwing exceptions but optionally using System.exit(..). * This sets up a message handler which emits messages immediately, * so report(boolean, IMessageHandler) only reports total number * of errors or warnings. * @param args the String[] command line for the compiler * @param useSystemExit if true, use System.exit(int) to complete * unless one of the args is -noExit. * and signal result (0 no exceptions/error, <0 exceptions, >0 compiler errors). */ public void runMain(String[] args, boolean useSystemExit) { boolean verbose = (-1 != ("" + LangUtil.arrayAsList(args)).indexOf("-verbose")); IMessageHolder holder = clientHolder; if (null == holder) { holder = ourHandler; if (verbose) { ourHandler.setInterceptor(MessagePrinter.VERBOSE); } else { ourHandler.ignore(IMessage.INFO); ourHandler.setInterceptor(MessagePrinter.TERSE); } } // make sure we handle out of memory gracefully... try { // byte[] b = new byte[100000000]; for testing OoME only! run(args, holder); } catch (OutOfMemoryError outOfMemory) { IMessage outOfMemoryMessage = new Message(OUT_OF_MEMORY_MSG,null,true); holder.handleMessage(outOfMemoryMessage); systemExit(holder); // we can't reasonably continue from this point. } boolean skipExit = false; if (useSystemExit && !LangUtil.isEmpty(args)) { // sigh - pluck -noExit for (int i = 0; i < args.length; i++) { if ("-noExit".equals(args[i])) { skipExit = true; break; } } } if (useSystemExit && !skipExit) { systemExit(holder); } } /** * Run without using System.exit(..), putting all messages in holder: * <ul> * <li>ERROR: compiler error</li> * <li>WARNING: compiler warning</li> * <li>FAIL: command error (bad arguments, exception thrown)</li> * </ul> * This handles incremental behavior: * <ul> * <li>If args include "-incremental", repeat for every input char * until 'q' is entered.<li> * <li>If args include "-incrementalTagFile {file}", repeat every time * we detect that {file} modification time has changed. </li> * <li>Either way, list files recompiled each time if args includes "-verbose".</li> * <li>Exit when the commmand/compiler throws any Throwable.</li> * </ul> * When complete, this contains all the messages of the final * run of the command and/or any FAIL messages produced in running * the command, including any Throwable thrown by the command itself. * * @param args the String[] command line for the compiler * @param holder the MessageHandler sink for messages. */ public void run(String[] args, IMessageHolder holder) { if (LangUtil.isEmpty(args)) { args = new String[] { "-?" }; } else if (controller.running()) { fail(holder, "already running with controller: " + controller, null); return; } args = controller.init(args, holder); if (0 < holder.numMessages(IMessage.ERROR, true)) { return; } ICommand command = ReflectionFactory.makeCommand(commandName, holder); if (0 < holder.numMessages(IMessage.ERROR, true)) { return; } try { // boolean verbose = (-1 != ("" + Arrays.asList(args)).indexOf("-verbose")); outer: while (true) { boolean passed = command.runCommand(args, holder); if (report(passed, holder) && controller.incremental()) { // final boolean onCommandLine = controller.commandLineIncremental(); while (controller.doRepeatCommand()) { holder.clearMessages(); if (controller.buildFresh()) { continue outer; } else { passed = command.repeatCommand(holder); } if (!report(passed, holder)) { break; } } } break; } } catch (AbortException ae) { if (ae.isSilent()) { quit(); } else { IMessage message = ae.getIMessage(); Throwable thrown = ae.getThrown(); if (null == thrown) { // toss AbortException wrapper if (null != message) { holder.handleMessage(message); } else { fail(holder, "abort without message", ae); } } else if (null == message) { fail(holder, "aborted", thrown); } else { String mssg = MessageUtil.MESSAGE_MOST.renderToString(message); fail(holder, mssg, thrown); } } } catch (Throwable t) { fail(holder, "unexpected exception", t); } } /** call this to stop after the next iteration of incremental compile */ public void quit() { controller.quit(); } /** * Set holder to be passed all messages. * When holder is set, messages will not be printed by default. * @param holder the IMessageHolder sink for all messages * (use null to restore default behavior) */ public void setHolder(IMessageHolder holder) { clientHolder = holder; } /** * Install a Runnable to be invoked synchronously * after each compile completes. * @param runner the Runnable to invoke - null to disable */ public void setCompletionRunner(Runnable runner) { this.completionRunner = runner; } /** * Call System.exit(int) with values derived from the number * of failures/aborts or errors in messages. * @param messages the IMessageHolder to interrogate. * @param messages */ protected void systemExit(IMessageHolder messages) { int num = lastFails; // messages.numMessages(IMessage.FAIL, true); if (0 < num) { System.exit(-num); } num = lastErrors; // messages.numMessages(IMessage.ERROR, false); if (0 < num) { System.exit(num); } System.exit(0); } /** Messages to the user */ protected void outMessage(String message) { // XXX coordinate with MessagePrinter System.out.print(message); System.out.flush(); } /** * Report results from a (possibly-incremental) compile run. * This delegates to any reportHandler or otherwise * prints summary counts of errors/warnings to System.err (if any errors) * or System.out (if only warnings). * WARNING: this silently ignores other messages like FAIL, * but clears the handler of all messages when returning true. XXX false * * This implementation ignores the pass parameter but * clears the holder after reporting * on the assumption messages were handled/printed already. * (ignoring UnsupportedOperationException from holder.clearMessages()). * @param pass true result of the command * @param holder IMessageHolder with messages from the command * @see reportCommandResults(IMessageHolder) * @return false if the process should abort */ protected boolean report(boolean pass, IMessageHolder holder) { lastFails = holder.numMessages(IMessage.FAIL, true); boolean result = (0 == lastFails); final Runnable runner = completionRunner; if (null != runner) { runner.run(); } if (holder == ourHandler) { lastErrors = holder.numMessages(IMessage.ERROR, false); int warnings = holder.numMessages(IMessage.WARNING, false); StringBuffer sb = new StringBuffer(); appendNLabel(sb, "fail|abort", lastFails); appendNLabel(sb, "error", lastErrors); appendNLabel(sb, "warning", warnings); if (0 < sb.length()) { PrintStream out = (0 < (lastErrors + lastFails) ? System.err : System.out); out.println(""); // XXX "wrote class file" messages no eol? out.println(sb.toString()); } } return result; } /** convenience API to make fail messages (without MessageUtils's fail prefix) */ protected static void fail(IMessageHandler handler, String message, Throwable thrown) { handler.handleMessage(new Message(message, IMessage.FAIL, thrown, null)); } /** * interceptor IMessageHandler to print as we go. * This formats all messages to the user. */ public static class MessagePrinter implements IMessageHandler { public static final IMessageHandler VERBOSE = new MessagePrinter(true); public static final IMessageHandler TERSE = new MessagePrinter(false); final boolean verbose; protected MessagePrinter(boolean verbose) { this.verbose = verbose; } /** * Print errors and warnings to System.err, * and optionally info to System.out, * rendering message String only. * @return false always */ public boolean handleMessage(IMessage message) { if (null != message) { PrintStream out = getStreamFor(message.getKind()); if (null != out) { out.println(render(message)); } } return false; } /** * Render message differently. * If abort, then prefix stack trace with feedback request. * If the actual message is empty, then use toString on the whole. * Prefix message part with file:line; * If it has context, suffix message with context. * @param message the IMessage to render * @return String rendering IMessage (never null) */ public static String render(IMessage message) { // IMessage.Kind kind = message.getKind(); StringBuffer sb = new StringBuffer(); String text = message.getMessage(); if (text.equals(AbortException.NO_MESSAGE_TEXT)) { text = null; } boolean toString = (LangUtil.isEmpty(text)); if (toString) { text = message.toString(); } ISourceLocation loc = message.getSourceLocation(); String context = null; if (null != loc) { File file = loc.getSourceFile(); if (null != file) { String name = file.getName(); if (!toString || (-1 == text.indexOf(name))) { sb.append(FileUtil.getBestPath(file)); if (loc.getLine() > 0) { sb.append(":" + loc.getLine()); } int col = loc.getColumn(); if (0 < col) { sb.append(":" + col); } sb.append(" "); } } context = loc.getContext(); } // per Wes' suggestion on dev... if (message.getKind() == IMessage.ERROR) { - sb.append("error "); + sb.append("[error] "); } else if (message.getKind() == IMessage.WARNING) { - sb.append("warning "); + sb.append("[warning] "); } sb.append(text); if (null != context) { sb.append(LangUtil.EOL); sb.append(context); } String details = message.getDetails(); if (details != null) { sb.append(LangUtil.EOL); sb.append('\t'); sb.append(details); } Throwable thrown = message.getThrown(); if (null != thrown) { sb.append(LangUtil.EOL); sb.append(Main.renderExceptionForUser(thrown)); } if (message.getExtraSourceLocations().isEmpty()) { return sb.toString(); } else { return MessageUtil.addExtraSourceLocations(message, sb.toString()); } } public boolean isIgnoring(IMessage.Kind kind) { return (null != getStreamFor(kind)); } /** @return System.err for FAIL, ABORT, ERROR, and WARNING, * System.out for INFO if verbose. */ protected PrintStream getStreamFor(IMessage.Kind kind) { if (IMessage.WARNING.isSameOrLessThan(kind)) { return System.err; } else if (verbose && IMessage.INFO.equals(kind)) { return System.out; } else { return null; } } } /** controller for repeatable command delays until input or file changed or removed */ public static class CommandController { public static String TAG_FILE_OPTION = "-XincrementalFile"; public static String INCREMENTAL_OPTION = "-incremental"; /** maximum 10-minute delay between filesystem checks */ public static long MAX_DELAY = 1000 * 600; /** default 5-second delay between filesystem checks */ public static long DEFAULT_DELAY = 1000 * 5; /** @see init(String[]) */ private static String[][] OPTIONS = new String[][] { new String[] { INCREMENTAL_OPTION }, new String[] { TAG_FILE_OPTION, null } }; /** true between init(String[]) and doRepeatCommand() that returns false */ private boolean running; /** true after quit() called */ private boolean quit; /** true if incremental mode, waiting for input other than 'q' */ private boolean incremental; /** true if incremental mode, waiting for file to change (repeat) or disappear (quit) */ private File tagFile; /** last modification time for tagFile as of last command - 0 to start */ private long fileModTime; /** delay between filesystem checks for tagFile modification time */ private long delay; /** true just after user types 'r' for rebuild */ private boolean buildFresh; public CommandController() { delay = DEFAULT_DELAY; } /** * @param argList read and strip incremental args from this * @param sink IMessageHandler for error messages * @return String[] remainder of args */ public String[] init(String[] args, IMessageHandler sink) { running = true; // String[] unused; if (!LangUtil.isEmpty(args)) { String[][] options = LangUtil.copyStrings(OPTIONS); /*unused = */LangUtil.extractOptions(args, options); incremental = (null != options[0][0]); if (null != options[1][0]) { File file = new File(options[1][1]); if (!file.exists()) { MessageUtil.abort(sink, "tag file does not exist: " + file); } else { tagFile = file; fileModTime = tagFile.lastModified(); } } } return args; } /** @return true if init(String[]) called but doRepeatCommand has not * returned false */ public boolean running() { return running; } /** @param delay milliseconds between filesystem checks */ public void setDelay(long delay) { if ((delay > -1) && (delay < MAX_DELAY)) { this.delay = delay; } } /** @return true if INCREMENTAL_OPTION or TAG_FILE_OPTION was in args */ public boolean incremental() { return (incremental || (null != tagFile)); } /** @return true if INCREMENTAL_OPTION was in args */ public boolean commandLineIncremental() { return incremental; } public void quit() { if (!quit) { quit = true; } } /** @return true just after user typed 'r' */ boolean buildFresh() { return buildFresh; } /** @return false if we should quit, true to do another command */ boolean doRepeatCommand() { if (!running) { return false; } boolean result = false; if (quit) { result = false; } else if (incremental) { try { if (buildFresh) { // reset before input request buildFresh = false; } System.out.println(" press enter to recompile, r to rebuild, q to quit: "); System.out.flush(); // boolean doMore = false; // seek for one q or a series of [\n\r]... do { int input = System.in.read(); if ('q' == input) { break; // result = false; } else if ('r' == input) { buildFresh = true; result = true; } else if (('\n' == input) || ('\r' == input)) { result = true; } // else eat anything else } while (!result); System.in.skip(Integer.MAX_VALUE); } catch (IOException e) { // XXX silence for error? result = false; } } else if (null != tagFile) { long curModTime; while (true) { if (!tagFile.exists()) { result = false; break; } else if (fileModTime == (curModTime = tagFile.lastModified())) { fileCheckDelay(); } else { fileModTime = curModTime; result = true; break; } } } // else, not incremental - false if (!result && running) { running = false; } return result; } /** delay between filesystem checks, returning if quit is set */ protected void fileCheckDelay() { // final Thread thread = Thread.currentThread(); long targetTime = System.currentTimeMillis() + delay; // long curTime; while (targetTime > System.currentTimeMillis()) { if (quit) { return; } try { Thread.sleep(300); } // 1/3-second delta for quit check catch (InterruptedException e) {} } } } }
false
true
public static String render(IMessage message) { // IMessage.Kind kind = message.getKind(); StringBuffer sb = new StringBuffer(); String text = message.getMessage(); if (text.equals(AbortException.NO_MESSAGE_TEXT)) { text = null; } boolean toString = (LangUtil.isEmpty(text)); if (toString) { text = message.toString(); } ISourceLocation loc = message.getSourceLocation(); String context = null; if (null != loc) { File file = loc.getSourceFile(); if (null != file) { String name = file.getName(); if (!toString || (-1 == text.indexOf(name))) { sb.append(FileUtil.getBestPath(file)); if (loc.getLine() > 0) { sb.append(":" + loc.getLine()); } int col = loc.getColumn(); if (0 < col) { sb.append(":" + col); } sb.append(" "); } } context = loc.getContext(); } // per Wes' suggestion on dev... if (message.getKind() == IMessage.ERROR) { sb.append("error "); } else if (message.getKind() == IMessage.WARNING) { sb.append("warning "); } sb.append(text); if (null != context) { sb.append(LangUtil.EOL); sb.append(context); } String details = message.getDetails(); if (details != null) { sb.append(LangUtil.EOL); sb.append('\t'); sb.append(details); } Throwable thrown = message.getThrown(); if (null != thrown) { sb.append(LangUtil.EOL); sb.append(Main.renderExceptionForUser(thrown)); } if (message.getExtraSourceLocations().isEmpty()) { return sb.toString(); } else { return MessageUtil.addExtraSourceLocations(message, sb.toString()); } }
public static String render(IMessage message) { // IMessage.Kind kind = message.getKind(); StringBuffer sb = new StringBuffer(); String text = message.getMessage(); if (text.equals(AbortException.NO_MESSAGE_TEXT)) { text = null; } boolean toString = (LangUtil.isEmpty(text)); if (toString) { text = message.toString(); } ISourceLocation loc = message.getSourceLocation(); String context = null; if (null != loc) { File file = loc.getSourceFile(); if (null != file) { String name = file.getName(); if (!toString || (-1 == text.indexOf(name))) { sb.append(FileUtil.getBestPath(file)); if (loc.getLine() > 0) { sb.append(":" + loc.getLine()); } int col = loc.getColumn(); if (0 < col) { sb.append(":" + col); } sb.append(" "); } } context = loc.getContext(); } // per Wes' suggestion on dev... if (message.getKind() == IMessage.ERROR) { sb.append("[error] "); } else if (message.getKind() == IMessage.WARNING) { sb.append("[warning] "); } sb.append(text); if (null != context) { sb.append(LangUtil.EOL); sb.append(context); } String details = message.getDetails(); if (details != null) { sb.append(LangUtil.EOL); sb.append('\t'); sb.append(details); } Throwable thrown = message.getThrown(); if (null != thrown) { sb.append(LangUtil.EOL); sb.append(Main.renderExceptionForUser(thrown)); } if (message.getExtraSourceLocations().isEmpty()) { return sb.toString(); } else { return MessageUtil.addExtraSourceLocations(message, sb.toString()); } }
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/SmooksMediatorTransformer.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/SmooksMediatorTransformer.java index 91e0b56e4..f37b3cc0c 100644 --- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/SmooksMediatorTransformer.java +++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.persistence/src/org/wso2/developerstudio/eclipse/gmf/esb/internal/persistence/SmooksMediatorTransformer.java @@ -1,94 +1,98 @@ /* * Copyright (c) WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.developerstudio.eclipse.gmf.esb.internal.persistence; import java.util.List; import java.util.Map.Entry; import org.apache.synapse.endpoints.Endpoint; import org.apache.synapse.mediators.base.SequenceMediator; import org.apache.synapse.util.xpath.SynapseXPath; import org.eclipse.core.runtime.Assert; import org.eclipse.emf.ecore.EObject; import org.wso2.carbon.mediator.transform.Input; import org.wso2.carbon.mediator.transform.Output; import org.wso2.carbon.mediator.transform.SmooksMediator.TYPES; import org.wso2.developerstudio.eclipse.gmf.esb.EsbNode; import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty; import org.wso2.developerstudio.eclipse.gmf.esb.OutputMethod; import org.wso2.developerstudio.eclipse.gmf.esb.SmooksIODataType; import org.wso2.developerstudio.eclipse.gmf.esb.SmooksMediator; import org.wso2.developerstudio.eclipse.gmf.esb.persistence.TransformationInfo; public class SmooksMediatorTransformer extends AbstractEsbNodeTransformer { public void transform(TransformationInfo information, EsbNode subject) throws Exception { information.getParentSequence().addChild(createSmooksMediator(information,subject)); // Transform the property mediator output data flow path. doTransform(information, ((SmooksMediator) subject).getOutputConnector()); } public void createSynapseObject(TransformationInfo info, EObject subject, List<Endpoint> endPoints) { } public void transformWithinSequence(TransformationInfo information, EsbNode subject, SequenceMediator sequence) throws Exception { sequence.addChild(createSmooksMediator(information,subject)); doTransformWithinSequence(information,((SmooksMediator) subject).getOutputConnector().getOutgoingLink(),sequence); } private org.wso2.carbon.mediator.transform.SmooksMediator createSmooksMediator(TransformationInfo information,EsbNode subject) throws Exception{ // Check subject. Assert.isTrue(subject instanceof SmooksMediator, "Invalid subject."); SmooksMediator visualSmooks = (SmooksMediator) subject; org.wso2.carbon.mediator.transform.SmooksMediator smooksMediator=new org.wso2.carbon.mediator.transform.SmooksMediator(); { Input input = new Input(); - input.setExpression(new SynapseXPath(visualSmooks.getInputExpression() - .getPropertyValue())); + NamespacedProperty inputExp = visualSmooks.getInputExpression(); + SynapseXPath inputExpression = new SynapseXPath(inputExp.getPropertyValue()); + for (Entry<String, String> entry : inputExp.getNamespaces().entrySet()) { + inputExpression.addNamespace(entry.getKey(), entry.getValue()); + } + input.setExpression(inputExpression); input.setType((visualSmooks.getInputType().equals(SmooksIODataType.XML)) ? TYPES.XML : TYPES.TEXT); smooksMediator.setInput(input); Output output = new Output(); output.setType((visualSmooks.getOutputType().equals(SmooksIODataType.XML)) ? TYPES.XML : TYPES.TEXT); if (visualSmooks.getOutputMethod().equals(OutputMethod.PROPERTY)) { output.setProperty(visualSmooks.getOutputProperty()); } else if (visualSmooks.getOutputMethod().equals(OutputMethod.EXPRESSION)) { output.setAction(visualSmooks.getOutputAction().getLiteral().toLowerCase()); NamespacedProperty namespacedProperty = visualSmooks.getOutputExpression(); SynapseXPath expression = new SynapseXPath(namespacedProperty.getPropertyValue()); for (Entry<String, String> entry : namespacedProperty.getNamespaces().entrySet()) { expression.addNamespace(entry.getKey(), entry.getValue()); } output.setExpression(expression); } smooksMediator.setOutput(output); smooksMediator.setConfigKey(visualSmooks.getConfigurationKey().getKeyValue()); } return smooksMediator; } }
true
true
private org.wso2.carbon.mediator.transform.SmooksMediator createSmooksMediator(TransformationInfo information,EsbNode subject) throws Exception{ // Check subject. Assert.isTrue(subject instanceof SmooksMediator, "Invalid subject."); SmooksMediator visualSmooks = (SmooksMediator) subject; org.wso2.carbon.mediator.transform.SmooksMediator smooksMediator=new org.wso2.carbon.mediator.transform.SmooksMediator(); { Input input = new Input(); input.setExpression(new SynapseXPath(visualSmooks.getInputExpression() .getPropertyValue())); input.setType((visualSmooks.getInputType().equals(SmooksIODataType.XML)) ? TYPES.XML : TYPES.TEXT); smooksMediator.setInput(input); Output output = new Output(); output.setType((visualSmooks.getOutputType().equals(SmooksIODataType.XML)) ? TYPES.XML : TYPES.TEXT); if (visualSmooks.getOutputMethod().equals(OutputMethod.PROPERTY)) { output.setProperty(visualSmooks.getOutputProperty()); } else if (visualSmooks.getOutputMethod().equals(OutputMethod.EXPRESSION)) { output.setAction(visualSmooks.getOutputAction().getLiteral().toLowerCase()); NamespacedProperty namespacedProperty = visualSmooks.getOutputExpression(); SynapseXPath expression = new SynapseXPath(namespacedProperty.getPropertyValue()); for (Entry<String, String> entry : namespacedProperty.getNamespaces().entrySet()) { expression.addNamespace(entry.getKey(), entry.getValue()); } output.setExpression(expression); } smooksMediator.setOutput(output); smooksMediator.setConfigKey(visualSmooks.getConfigurationKey().getKeyValue()); } return smooksMediator; }
private org.wso2.carbon.mediator.transform.SmooksMediator createSmooksMediator(TransformationInfo information,EsbNode subject) throws Exception{ // Check subject. Assert.isTrue(subject instanceof SmooksMediator, "Invalid subject."); SmooksMediator visualSmooks = (SmooksMediator) subject; org.wso2.carbon.mediator.transform.SmooksMediator smooksMediator=new org.wso2.carbon.mediator.transform.SmooksMediator(); { Input input = new Input(); NamespacedProperty inputExp = visualSmooks.getInputExpression(); SynapseXPath inputExpression = new SynapseXPath(inputExp.getPropertyValue()); for (Entry<String, String> entry : inputExp.getNamespaces().entrySet()) { inputExpression.addNamespace(entry.getKey(), entry.getValue()); } input.setExpression(inputExpression); input.setType((visualSmooks.getInputType().equals(SmooksIODataType.XML)) ? TYPES.XML : TYPES.TEXT); smooksMediator.setInput(input); Output output = new Output(); output.setType((visualSmooks.getOutputType().equals(SmooksIODataType.XML)) ? TYPES.XML : TYPES.TEXT); if (visualSmooks.getOutputMethod().equals(OutputMethod.PROPERTY)) { output.setProperty(visualSmooks.getOutputProperty()); } else if (visualSmooks.getOutputMethod().equals(OutputMethod.EXPRESSION)) { output.setAction(visualSmooks.getOutputAction().getLiteral().toLowerCase()); NamespacedProperty namespacedProperty = visualSmooks.getOutputExpression(); SynapseXPath expression = new SynapseXPath(namespacedProperty.getPropertyValue()); for (Entry<String, String> entry : namespacedProperty.getNamespaces().entrySet()) { expression.addNamespace(entry.getKey(), entry.getValue()); } output.setExpression(expression); } smooksMediator.setOutput(output); smooksMediator.setConfigKey(visualSmooks.getConfigurationKey().getKeyValue()); } return smooksMediator; }
diff --git a/tools/cooja/java/se/sics/cooja/plugins/analyzers/PcapExporter.java b/tools/cooja/java/se/sics/cooja/plugins/analyzers/PcapExporter.java index f978bbb60..4dbbe12f4 100644 --- a/tools/cooja/java/se/sics/cooja/plugins/analyzers/PcapExporter.java +++ b/tools/cooja/java/se/sics/cooja/plugins/analyzers/PcapExporter.java @@ -1,53 +1,53 @@ package se.sics.cooja.plugins.analyzers; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; public class PcapExporter { DataOutputStream out; public PcapExporter() throws IOException { } public void openPcap() throws IOException { out = new DataOutputStream(new FileOutputStream("radiolog-" + System.currentTimeMillis() + ".pcap")); /* pcap header */ out.writeInt(0xa1b2c3d4); out.writeShort(0x0002); out.writeShort(0x0004); out.writeInt(0); out.writeInt(0); out.writeInt(4096); out.writeInt(195); /* 195 for LINKTYPE_IEEE802_15_4 */ out.flush(); System.out.println("Opened pcap file!"); } public void closePcap() throws IOException { out.close(); } public void exportPacketData(byte[] data) throws IOException { if (out == null) { openPcap(); } try { /* pcap packet header */ out.writeInt((int) System.currentTimeMillis() / 1000); out.writeInt((int) ((System.currentTimeMillis() % 1000) * 1000)); out.writeInt(data.length); - out.writeInt(data.length); + out.writeInt(data.length+2); /* and the data */ out.write(data); out.flush(); } catch (Exception e) { e.printStackTrace(); } } }
true
true
public void exportPacketData(byte[] data) throws IOException { if (out == null) { openPcap(); } try { /* pcap packet header */ out.writeInt((int) System.currentTimeMillis() / 1000); out.writeInt((int) ((System.currentTimeMillis() % 1000) * 1000)); out.writeInt(data.length); out.writeInt(data.length); /* and the data */ out.write(data); out.flush(); } catch (Exception e) { e.printStackTrace(); } }
public void exportPacketData(byte[] data) throws IOException { if (out == null) { openPcap(); } try { /* pcap packet header */ out.writeInt((int) System.currentTimeMillis() / 1000); out.writeInt((int) ((System.currentTimeMillis() % 1000) * 1000)); out.writeInt(data.length); out.writeInt(data.length+2); /* and the data */ out.write(data); out.flush(); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/varviewer/client/varTable/ColumnStore.java b/src/varviewer/client/varTable/ColumnStore.java index 48db430..2df1a84 100644 --- a/src/varviewer/client/varTable/ColumnStore.java +++ b/src/varviewer/client/varTable/ColumnStore.java @@ -1,481 +1,481 @@ package varviewer.client.varTable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import varviewer.client.IGVInterface; import varviewer.shared.Variant; import com.google.gwt.cell.client.ButtonCell; import com.google.gwt.cell.client.Cell; import com.google.gwt.cell.client.ImageResourceCell; import com.google.gwt.cell.client.SafeHtmlCell; import com.google.gwt.core.shared.GWT; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.TextColumn; import com.google.gwt.user.client.ui.Image; /** * Maintains a list of all available Columns that can potentially be used in a ColumnModel * and VarTable. * This is a singleton. * @author brendan * */ public class ColumnStore { private static List<VarAnnotation<?>> cols = new ArrayList<VarAnnotation<?>>(); private static ColumnStore store; public static ColumnStore getStore() { if (store == null) { store = new ColumnStore(); } return store; } /** * Private constructor, get access to the store statically through ColumnStore.getStore() */ private ColumnStore() { initialize(); store = this; } /** * Obtain the column associated with the given key * @param key * @return */ public VarAnnotation<?> getColumnForID(String key) { for(VarAnnotation<?> col : cols) { if (col.id.equals(key)) { return col; } } return null; } /** * Obtain a reference to a list of all potential columns * @return */ public List<VarAnnotation<?>> getAllColumns() { return cols; } private void addColumn(VarAnnotation<?> col) { cols.add(col); } /** * Creates all possible columns and stores them in a list here.... */ private void initialize() { addColumn(new VarAnnotation<String>("gene", "Gene", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("gene"); return val != null ? val : "-"; } }, 1.0)); VarAnnotation<String> chrAnno = new VarAnnotation<String>("contig", "Chr", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return var.getChrom(); } }, 0.5); chrAnno.setComparator(new Comparator<Variant>() { @Override public int compare(Variant o1, Variant o2) { return o1.getChrom().compareTo(o2.getChrom()); } }); addColumn(chrAnno); VarAnnotation<String> posAnnotation = new VarAnnotation<String>("pos", "Start", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return "" + var.getPos(); } }, 1.0, new PositionComparator()); posAnnotation.setComparator(new Comparator<Variant>() { @Override public int compare(Variant v0, Variant v1) { if (v0.getChrom().equals(v1.getChrom())) { return v1.getPos() - v0.getPos(); } else { return v0.getChrom().compareTo(v1.getChrom()); } } }); addColumn(posAnnotation); // addColumn(new VarAnnotation<String>("zygosity", "Zygosity", new TextColumn<Variant>() { // // @Override // public String getValue(Variant var) { // String val = var.getAnnotation("zygosity"); // // if (val == null || val.length()<2) // return "?"; // // return val; // } // }, 1.0, false)); addColumn(new VarAnnotation<ImageResource>("zygosity", "Zygosity", new Column<Variant, ImageResource>(new ImageResourceCell()) { @Override public ImageResource getValue(Variant var) { String zyg = var.getAnnotationStr("zygosity"); if (zyg == null || zyg.equals("ref")) return resources.refImage(); if (zyg.equals("het")) return resources.hetImage(); if (zyg.equals("hom")) return resources.homImage(); return resources.refImage(); } }, 0.6)); addColumn(new VarAnnotation<String>("exon.function", "Exon effect", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("exon.function"); if (val == null || val.equals("-")) { val = var.getAnnotationStr("variant.type"); } return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("nm.number", "NM Number", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("nm.number"); return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("cdot", "c.dot", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("cdot"); return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("pdot", "p.dot", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("pdot"); return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("ref", "Ref.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return var.getRef(); } }, 1.0)); addColumn(new VarAnnotation<String>("alt", "Alt.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return var.getAlt(); } }, 1.0)); addColumn(new VarAnnotation<String>("quality", "Quality", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("quality"); return val != null ? val.toString() : "-"; } }, 1.0)); addColumn(new VarAnnotation<String>("depth", "Depth", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("depth"); return val != null ? val.toString() : "-"; } }, 1.0)); addColumn(new VarAnnotation<String>("var.freq", "Alt. Freq", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double tot = var.getAnnotationDouble("depth"); Double alt = var.getAnnotationDouble("var.depth"); if (tot != null && alt != null && tot > 0) { double freq = alt / tot; String freqStr = "" + freq; if (freqStr.length() > 5) { freqStr = freqStr.substring(0, 4); } return freqStr; } return "-"; } }, 1.0)); addColumn(new VarAnnotation<SafeHtml>("varbin.bin", "VarBin", new Column<Variant, SafeHtml>(new SafeHtmlCell()) { @Override public SafeHtml getValue(Variant var) { SafeHtmlBuilder bldr = new SafeHtmlBuilder(); Double val = var.getAnnotationDouble("varbin.bin"); if (val == null) { bldr.appendEscaped("-"); } else { if (val.equals(1)) { bldr.appendHtmlConstant("<span style=\"color: #003300;\"><b>1</b></span>"); } if (val.equals(2)) { bldr.appendHtmlConstant("<span style=\"color: #996600;\"><b>2</b></span>"); } if (val.equals(3)) { bldr.appendHtmlConstant("<span style=\"color: #990000;\"><b>3</b></span>"); } if (val.equals(4)) { bldr.appendHtmlConstant("<span style=\"color: #FF0000;\"><b>4</b></span>"); } } return bldr.toSafeHtml(); } }, 1.0)); addColumn(new VarAnnotation<String>("pop.freq", "Pop. Freq.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("pop.freq"); return val != null ? val.toString() : "0"; } }, 1.0)); addColumn(new VarAnnotation<String>("arup.freq", "ARUP Freq.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("ARUP.freq"); if (val.equals("-")) val = "0"; return val != null ? val : "0"; } }, 2.0)); addColumn(new VarAnnotation<String>("sift.score", "SIFT score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("sift.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<String>("mt.score", "MutationTaster score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("mt.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<String>("gerp.score", "GERP++ score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("gerp.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<SafeHtml>("rsnum", "dbSNP #", new Column<Variant, SafeHtml>(new SafeHtmlCell()) { @Override public SafeHtml getValue(Variant var) { SafeHtmlBuilder bldr = new SafeHtmlBuilder(); String val = var.getAnnotationStr("rsnum"); if (val == null || val.length() < 2) { bldr.appendEscaped("-"); } else { - bldr.appendHtmlConstant("<a href=\"http://www.ncbi.nlm.nih.gov/projects/SNP/snp_ref.cgi?rs=1063736\" target=\"_blank\">" + val + "</a>" ); + bldr.appendHtmlConstant("<a href=\"http://www.ncbi.nlm.nih.gov/projects/SNP/snp_ref.cgi?rs=" + val.replace("rs", "") + "\" target=\"_blank\">" + val + "</a>" ); } return bldr.toSafeHtml(); } }, 1.0)); addColumn(new VarAnnotation<String>("pp.score", "PolyPhen-2 score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("pp.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<String>("omim.num", "OMIM #", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("omim.disease.ids"); return val != null ? val : "0"; } }, 2.0)); addColumn(new VarAnnotation<ImageResource>("disease.pics", "HGMD & OMIM", new Column<Variant, ImageResource>(new ImageResourceCell()) { @Override public ImageResource getValue(Variant var) { String hgmdExact = var.getAnnotationStr("hgmd.hit"); String hgmdGeneMatch = var.getAnnotationStr("hgmd.info"); String omimGeneMatch = var.getAnnotationStr("omim.disease"); boolean hasHGMDExact = hgmdExact != null && hgmdExact.length() > 3; boolean hasHGMDGene = hgmdGeneMatch != null && hgmdGeneMatch.length() > 3; boolean hasOmim = omimGeneMatch != null && omimGeneMatch.length() > 3; ImageResource img = null; if (hasHGMDExact) { if (hasOmim) { //Has all 3 img = resources.hgmdHitHgmdOmimImage(); } else { //No omim, but has hgmd exact and gene match img = resources.hgmdHitHgmdImage(); } } else { //No exact hit if (hasHGMDGene) { if (hasOmim) { img = resources.hgmdOmimImage(); } else { //No OMIM, just hgmd gene match img = resources.hgmdOnlyImage(); } } else { if (hasOmim) { img = resources.omimOnlyImage(); } else { //nothing, img is null } } } return img; } }, 1.0, null)); // ButtonImageCell commentButton = new ButtonImageCell(new Image("images/comment-icon.png")); // VarAnnotation<String> commentVarAnno =new VarAnnotation<String>("comment", "Notes", new Column<Variant, String>(commentButton) { // // @Override // public String getValue(Variant var) { // //Somehow get comment info from Variant - is it an annotation? // // return "huh?"; // } // // }, 0.6); // // commentVarAnno.col.setFieldUpdater(new FieldUpdater<Variant, String>() { // // @Override // public void update(int index, Variant var, String value) { // //TODO Show comment popup? // } // // }); // addColumn(commentVarAnno); IGVCell igvCell = new IGVCell(); addColumn(new VarAnnotation<String>("igv.link", "IGV", new Column<Variant, String>(igvCell) { @Override public String getValue(Variant var) { String locus = "chr" + var.getChrom() + ":" + var.getPos(); return locus; } }, 1.0, null)); } public class ButtonImageCell extends ButtonCell{ final Image image; public ButtonImageCell(Image image) { this.image = image; } @Override public void render(com.google.gwt.cell.client.Cell.Context context, String value, SafeHtmlBuilder sb) { SafeHtml html = SafeHtmlUtils.fromTrustedString(image.toString()); sb.append(html); } } static class IGVCell extends ButtonCell { public void render(Cell.Context context, String value, SafeHtmlBuilder sb) { sb.appendHtmlConstant("<a href=\"" + IGVInterface.baseURL + "goto?locus=" + value + "\" target=\"_self\"><img src=\"images/linkIcon.png\"/></a>" ); } } static final VarPageResources resources = (VarPageResources) GWT.create(VarPageResources.class); }
true
true
private void initialize() { addColumn(new VarAnnotation<String>("gene", "Gene", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("gene"); return val != null ? val : "-"; } }, 1.0)); VarAnnotation<String> chrAnno = new VarAnnotation<String>("contig", "Chr", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return var.getChrom(); } }, 0.5); chrAnno.setComparator(new Comparator<Variant>() { @Override public int compare(Variant o1, Variant o2) { return o1.getChrom().compareTo(o2.getChrom()); } }); addColumn(chrAnno); VarAnnotation<String> posAnnotation = new VarAnnotation<String>("pos", "Start", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return "" + var.getPos(); } }, 1.0, new PositionComparator()); posAnnotation.setComparator(new Comparator<Variant>() { @Override public int compare(Variant v0, Variant v1) { if (v0.getChrom().equals(v1.getChrom())) { return v1.getPos() - v0.getPos(); } else { return v0.getChrom().compareTo(v1.getChrom()); } } }); addColumn(posAnnotation); // addColumn(new VarAnnotation<String>("zygosity", "Zygosity", new TextColumn<Variant>() { // // @Override // public String getValue(Variant var) { // String val = var.getAnnotation("zygosity"); // // if (val == null || val.length()<2) // return "?"; // // return val; // } // }, 1.0, false)); addColumn(new VarAnnotation<ImageResource>("zygosity", "Zygosity", new Column<Variant, ImageResource>(new ImageResourceCell()) { @Override public ImageResource getValue(Variant var) { String zyg = var.getAnnotationStr("zygosity"); if (zyg == null || zyg.equals("ref")) return resources.refImage(); if (zyg.equals("het")) return resources.hetImage(); if (zyg.equals("hom")) return resources.homImage(); return resources.refImage(); } }, 0.6)); addColumn(new VarAnnotation<String>("exon.function", "Exon effect", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("exon.function"); if (val == null || val.equals("-")) { val = var.getAnnotationStr("variant.type"); } return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("nm.number", "NM Number", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("nm.number"); return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("cdot", "c.dot", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("cdot"); return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("pdot", "p.dot", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("pdot"); return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("ref", "Ref.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return var.getRef(); } }, 1.0)); addColumn(new VarAnnotation<String>("alt", "Alt.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return var.getAlt(); } }, 1.0)); addColumn(new VarAnnotation<String>("quality", "Quality", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("quality"); return val != null ? val.toString() : "-"; } }, 1.0)); addColumn(new VarAnnotation<String>("depth", "Depth", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("depth"); return val != null ? val.toString() : "-"; } }, 1.0)); addColumn(new VarAnnotation<String>("var.freq", "Alt. Freq", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double tot = var.getAnnotationDouble("depth"); Double alt = var.getAnnotationDouble("var.depth"); if (tot != null && alt != null && tot > 0) { double freq = alt / tot; String freqStr = "" + freq; if (freqStr.length() > 5) { freqStr = freqStr.substring(0, 4); } return freqStr; } return "-"; } }, 1.0)); addColumn(new VarAnnotation<SafeHtml>("varbin.bin", "VarBin", new Column<Variant, SafeHtml>(new SafeHtmlCell()) { @Override public SafeHtml getValue(Variant var) { SafeHtmlBuilder bldr = new SafeHtmlBuilder(); Double val = var.getAnnotationDouble("varbin.bin"); if (val == null) { bldr.appendEscaped("-"); } else { if (val.equals(1)) { bldr.appendHtmlConstant("<span style=\"color: #003300;\"><b>1</b></span>"); } if (val.equals(2)) { bldr.appendHtmlConstant("<span style=\"color: #996600;\"><b>2</b></span>"); } if (val.equals(3)) { bldr.appendHtmlConstant("<span style=\"color: #990000;\"><b>3</b></span>"); } if (val.equals(4)) { bldr.appendHtmlConstant("<span style=\"color: #FF0000;\"><b>4</b></span>"); } } return bldr.toSafeHtml(); } }, 1.0)); addColumn(new VarAnnotation<String>("pop.freq", "Pop. Freq.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("pop.freq"); return val != null ? val.toString() : "0"; } }, 1.0)); addColumn(new VarAnnotation<String>("arup.freq", "ARUP Freq.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("ARUP.freq"); if (val.equals("-")) val = "0"; return val != null ? val : "0"; } }, 2.0)); addColumn(new VarAnnotation<String>("sift.score", "SIFT score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("sift.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<String>("mt.score", "MutationTaster score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("mt.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<String>("gerp.score", "GERP++ score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("gerp.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<SafeHtml>("rsnum", "dbSNP #", new Column<Variant, SafeHtml>(new SafeHtmlCell()) { @Override public SafeHtml getValue(Variant var) { SafeHtmlBuilder bldr = new SafeHtmlBuilder(); String val = var.getAnnotationStr("rsnum"); if (val == null || val.length() < 2) { bldr.appendEscaped("-"); } else { bldr.appendHtmlConstant("<a href=\"http://www.ncbi.nlm.nih.gov/projects/SNP/snp_ref.cgi?rs=1063736\" target=\"_blank\">" + val + "</a>" ); } return bldr.toSafeHtml(); } }, 1.0)); addColumn(new VarAnnotation<String>("pp.score", "PolyPhen-2 score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("pp.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<String>("omim.num", "OMIM #", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("omim.disease.ids"); return val != null ? val : "0"; } }, 2.0)); addColumn(new VarAnnotation<ImageResource>("disease.pics", "HGMD & OMIM", new Column<Variant, ImageResource>(new ImageResourceCell()) { @Override public ImageResource getValue(Variant var) { String hgmdExact = var.getAnnotationStr("hgmd.hit"); String hgmdGeneMatch = var.getAnnotationStr("hgmd.info"); String omimGeneMatch = var.getAnnotationStr("omim.disease"); boolean hasHGMDExact = hgmdExact != null && hgmdExact.length() > 3; boolean hasHGMDGene = hgmdGeneMatch != null && hgmdGeneMatch.length() > 3; boolean hasOmim = omimGeneMatch != null && omimGeneMatch.length() > 3; ImageResource img = null; if (hasHGMDExact) { if (hasOmim) { //Has all 3 img = resources.hgmdHitHgmdOmimImage(); } else { //No omim, but has hgmd exact and gene match img = resources.hgmdHitHgmdImage(); } } else { //No exact hit if (hasHGMDGene) { if (hasOmim) { img = resources.hgmdOmimImage(); } else { //No OMIM, just hgmd gene match img = resources.hgmdOnlyImage(); } } else { if (hasOmim) { img = resources.omimOnlyImage(); } else { //nothing, img is null } } } return img; } }, 1.0, null)); // ButtonImageCell commentButton = new ButtonImageCell(new Image("images/comment-icon.png")); // VarAnnotation<String> commentVarAnno =new VarAnnotation<String>("comment", "Notes", new Column<Variant, String>(commentButton) { // // @Override // public String getValue(Variant var) { // //Somehow get comment info from Variant - is it an annotation? // // return "huh?"; // } // // }, 0.6); // // commentVarAnno.col.setFieldUpdater(new FieldUpdater<Variant, String>() { // // @Override // public void update(int index, Variant var, String value) { // //TODO Show comment popup? // } // // }); // addColumn(commentVarAnno); IGVCell igvCell = new IGVCell(); addColumn(new VarAnnotation<String>("igv.link", "IGV", new Column<Variant, String>(igvCell) { @Override public String getValue(Variant var) { String locus = "chr" + var.getChrom() + ":" + var.getPos(); return locus; } }, 1.0, null)); }
private void initialize() { addColumn(new VarAnnotation<String>("gene", "Gene", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("gene"); return val != null ? val : "-"; } }, 1.0)); VarAnnotation<String> chrAnno = new VarAnnotation<String>("contig", "Chr", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return var.getChrom(); } }, 0.5); chrAnno.setComparator(new Comparator<Variant>() { @Override public int compare(Variant o1, Variant o2) { return o1.getChrom().compareTo(o2.getChrom()); } }); addColumn(chrAnno); VarAnnotation<String> posAnnotation = new VarAnnotation<String>("pos", "Start", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return "" + var.getPos(); } }, 1.0, new PositionComparator()); posAnnotation.setComparator(new Comparator<Variant>() { @Override public int compare(Variant v0, Variant v1) { if (v0.getChrom().equals(v1.getChrom())) { return v1.getPos() - v0.getPos(); } else { return v0.getChrom().compareTo(v1.getChrom()); } } }); addColumn(posAnnotation); // addColumn(new VarAnnotation<String>("zygosity", "Zygosity", new TextColumn<Variant>() { // // @Override // public String getValue(Variant var) { // String val = var.getAnnotation("zygosity"); // // if (val == null || val.length()<2) // return "?"; // // return val; // } // }, 1.0, false)); addColumn(new VarAnnotation<ImageResource>("zygosity", "Zygosity", new Column<Variant, ImageResource>(new ImageResourceCell()) { @Override public ImageResource getValue(Variant var) { String zyg = var.getAnnotationStr("zygosity"); if (zyg == null || zyg.equals("ref")) return resources.refImage(); if (zyg.equals("het")) return resources.hetImage(); if (zyg.equals("hom")) return resources.homImage(); return resources.refImage(); } }, 0.6)); addColumn(new VarAnnotation<String>("exon.function", "Exon effect", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("exon.function"); if (val == null || val.equals("-")) { val = var.getAnnotationStr("variant.type"); } return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("nm.number", "NM Number", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("nm.number"); return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("cdot", "c.dot", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("cdot"); return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("pdot", "p.dot", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("pdot"); return val != null ? val : "-"; } }, 2.0)); addColumn(new VarAnnotation<String>("ref", "Ref.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return var.getRef(); } }, 1.0)); addColumn(new VarAnnotation<String>("alt", "Alt.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { return var.getAlt(); } }, 1.0)); addColumn(new VarAnnotation<String>("quality", "Quality", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("quality"); return val != null ? val.toString() : "-"; } }, 1.0)); addColumn(new VarAnnotation<String>("depth", "Depth", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("depth"); return val != null ? val.toString() : "-"; } }, 1.0)); addColumn(new VarAnnotation<String>("var.freq", "Alt. Freq", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double tot = var.getAnnotationDouble("depth"); Double alt = var.getAnnotationDouble("var.depth"); if (tot != null && alt != null && tot > 0) { double freq = alt / tot; String freqStr = "" + freq; if (freqStr.length() > 5) { freqStr = freqStr.substring(0, 4); } return freqStr; } return "-"; } }, 1.0)); addColumn(new VarAnnotation<SafeHtml>("varbin.bin", "VarBin", new Column<Variant, SafeHtml>(new SafeHtmlCell()) { @Override public SafeHtml getValue(Variant var) { SafeHtmlBuilder bldr = new SafeHtmlBuilder(); Double val = var.getAnnotationDouble("varbin.bin"); if (val == null) { bldr.appendEscaped("-"); } else { if (val.equals(1)) { bldr.appendHtmlConstant("<span style=\"color: #003300;\"><b>1</b></span>"); } if (val.equals(2)) { bldr.appendHtmlConstant("<span style=\"color: #996600;\"><b>2</b></span>"); } if (val.equals(3)) { bldr.appendHtmlConstant("<span style=\"color: #990000;\"><b>3</b></span>"); } if (val.equals(4)) { bldr.appendHtmlConstant("<span style=\"color: #FF0000;\"><b>4</b></span>"); } } return bldr.toSafeHtml(); } }, 1.0)); addColumn(new VarAnnotation<String>("pop.freq", "Pop. Freq.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("pop.freq"); return val != null ? val.toString() : "0"; } }, 1.0)); addColumn(new VarAnnotation<String>("arup.freq", "ARUP Freq.", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("ARUP.freq"); if (val.equals("-")) val = "0"; return val != null ? val : "0"; } }, 2.0)); addColumn(new VarAnnotation<String>("sift.score", "SIFT score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("sift.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<String>("mt.score", "MutationTaster score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("mt.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<String>("gerp.score", "GERP++ score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("gerp.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<SafeHtml>("rsnum", "dbSNP #", new Column<Variant, SafeHtml>(new SafeHtmlCell()) { @Override public SafeHtml getValue(Variant var) { SafeHtmlBuilder bldr = new SafeHtmlBuilder(); String val = var.getAnnotationStr("rsnum"); if (val == null || val.length() < 2) { bldr.appendEscaped("-"); } else { bldr.appendHtmlConstant("<a href=\"http://www.ncbi.nlm.nih.gov/projects/SNP/snp_ref.cgi?rs=" + val.replace("rs", "") + "\" target=\"_blank\">" + val + "</a>" ); } return bldr.toSafeHtml(); } }, 1.0)); addColumn(new VarAnnotation<String>("pp.score", "PolyPhen-2 score", new TextColumn<Variant>() { @Override public String getValue(Variant var) { Double val = var.getAnnotationDouble("pp.score"); return val != null ? val.toString() : "NA"; } }, 1.0)); addColumn(new VarAnnotation<String>("omim.num", "OMIM #", new TextColumn<Variant>() { @Override public String getValue(Variant var) { String val = var.getAnnotationStr("omim.disease.ids"); return val != null ? val : "0"; } }, 2.0)); addColumn(new VarAnnotation<ImageResource>("disease.pics", "HGMD & OMIM", new Column<Variant, ImageResource>(new ImageResourceCell()) { @Override public ImageResource getValue(Variant var) { String hgmdExact = var.getAnnotationStr("hgmd.hit"); String hgmdGeneMatch = var.getAnnotationStr("hgmd.info"); String omimGeneMatch = var.getAnnotationStr("omim.disease"); boolean hasHGMDExact = hgmdExact != null && hgmdExact.length() > 3; boolean hasHGMDGene = hgmdGeneMatch != null && hgmdGeneMatch.length() > 3; boolean hasOmim = omimGeneMatch != null && omimGeneMatch.length() > 3; ImageResource img = null; if (hasHGMDExact) { if (hasOmim) { //Has all 3 img = resources.hgmdHitHgmdOmimImage(); } else { //No omim, but has hgmd exact and gene match img = resources.hgmdHitHgmdImage(); } } else { //No exact hit if (hasHGMDGene) { if (hasOmim) { img = resources.hgmdOmimImage(); } else { //No OMIM, just hgmd gene match img = resources.hgmdOnlyImage(); } } else { if (hasOmim) { img = resources.omimOnlyImage(); } else { //nothing, img is null } } } return img; } }, 1.0, null)); // ButtonImageCell commentButton = new ButtonImageCell(new Image("images/comment-icon.png")); // VarAnnotation<String> commentVarAnno =new VarAnnotation<String>("comment", "Notes", new Column<Variant, String>(commentButton) { // // @Override // public String getValue(Variant var) { // //Somehow get comment info from Variant - is it an annotation? // // return "huh?"; // } // // }, 0.6); // // commentVarAnno.col.setFieldUpdater(new FieldUpdater<Variant, String>() { // // @Override // public void update(int index, Variant var, String value) { // //TODO Show comment popup? // } // // }); // addColumn(commentVarAnno); IGVCell igvCell = new IGVCell(); addColumn(new VarAnnotation<String>("igv.link", "IGV", new Column<Variant, String>(igvCell) { @Override public String getValue(Variant var) { String locus = "chr" + var.getChrom() + ":" + var.getPos(); return locus; } }, 1.0, null)); }
diff --git a/src-pos/com/openbravo/pos/panels/JTicketsFinder.java b/src-pos/com/openbravo/pos/panels/JTicketsFinder.java index af6c2e4..715c3ee 100644 --- a/src-pos/com/openbravo/pos/panels/JTicketsFinder.java +++ b/src-pos/com/openbravo/pos/panels/JTicketsFinder.java @@ -1,688 +1,689 @@ // Openbravo POS is a point of sales application designed for touch screens. // Copyright (C) 2008 Openbravo, S.L. // http://sourceforge.net/projects/openbravopos // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth floor, Boston, MA 02110-1301 USA package com.openbravo.pos.panels; import com.openbravo.basic.BasicException; import com.openbravo.data.gui.ComboBoxValModel; import com.openbravo.data.gui.ListQBFModelNumber; import com.openbravo.data.loader.LocalRes; import com.openbravo.data.loader.QBFCompareEnum; import com.openbravo.data.loader.SentenceList; import com.openbravo.data.user.EditorCreator; import com.openbravo.data.user.ListProvider; import com.openbravo.data.user.ListProviderCreator; import com.openbravo.pos.forms.AppLocal; import com.openbravo.pos.forms.DataLogicSales; import com.openbravo.pos.inventory.TaxCategoryInfo; import com.openbravo.pos.ticket.FindTicketsInfo; import com.openbravo.pos.ticket.FindTicketsRenderer; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.Window; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.swing.JFrame; /** * * @author Mikel irurita */ public class JTicketsFinder extends javax.swing.JDialog implements EditorCreator { private ListProvider lpr; private SentenceList m_sentcat; private ComboBoxValModel m_CategoryModel; private DataLogicSales dlSales; private FindTicketsInfo selectedTicket; private Calendar cal; /** Creates new form JCustomerFinder */ private JTicketsFinder(java.awt.Frame parent, boolean modal) { super(parent, modal); } /** Creates new form JCustomerFinder */ private JTicketsFinder(java.awt.Dialog parent, boolean modal) { super(parent, modal); } public static JTicketsFinder getReceiptFinder(Component parent, DataLogicSales dlSales) { Window window = getWindow(parent); JTicketsFinder myMsg; if (window instanceof Frame) { myMsg = new JTicketsFinder((Frame) window, true); } else { myMsg = new JTicketsFinder((Dialog) window, true); } myMsg.init(dlSales); myMsg.applyComponentOrientation(parent.getComponentOrientation()); return myMsg; } public FindTicketsInfo getSelectedCustomer() { return selectedTicket; } private void init(DataLogicSales dlSales) { cal = Calendar.getInstance(); this.dlSales = dlSales; initComponents(); jScrollPane1.getVerticalScrollBar().setPreferredSize(new Dimension(35, 35)); jtxtTicketID.addEditorKeys(m_jKeys); jtxtMoney.addEditorKeys(m_jKeys); jtxtTicketID.activate(); lpr = new ListProviderCreator(dlSales.getTicketsList(), this); jListTickets.setCellRenderer(new FindTicketsRenderer()); getRootPane().setDefaultButton(jcmdOK); initCombos(); defaultValues(); selectedTicket = null; } public void executeSearch() { try { jListTickets.setModel(new MyListData(lpr.loadData())); if (jListTickets.getModel().getSize() > 0) { jListTickets.setSelectedIndex(0); } } catch (BasicException e) { e.printStackTrace(); } } private void initCombos() { int year = cal.get(Calendar.YEAR); jcboMoney.setModel(new ListQBFModelNumber()); jcboDayFrom.addItem(null); jcboMonthFrom.addItem(null); jcboYearFrom.addItem(null); jcboDayTo.addItem(null); jcboMonthTo.addItem(null); jcboYearTo.addItem(null); for (int i = 1; i < 32; i++) { jcboDayFrom.addItem(String.valueOf(i)); jcboDayTo.addItem(String.valueOf(i)); } for (int i = 1; i < 13; i++) { jcboMonthFrom.addItem(String.valueOf(i)); jcboMonthTo.addItem(String.valueOf(i)); } for (int i = year; i > year-10; i--) { jcboYearFrom.addItem(String.valueOf(i)); jcboYearTo.addItem(String.valueOf(i)); } m_sentcat = dlSales.getUserList(); m_CategoryModel = new ComboBoxValModel(); List catlist=null; try { catlist = m_sentcat.list(); } catch (BasicException ex) { ex.getMessage(); } catlist.add(0, null); m_CategoryModel = new ComboBoxValModel(catlist); jcboUser.setModel(m_CategoryModel); ComboBoxValModel cbv = new ComboBoxValModel(); cbv.add(null); cbv.add(LocalRes.getIntString("combo.today")); cbv.add(LocalRes.getIntString("combo.month")); cbv.add(LocalRes.getIntString("combo.year")); jcboTimeFrame.setModel(cbv); } private void defaultValues() { jListTickets.setModel(new MyListData(new ArrayList())); jcboUser.setSelectedItem(null); jtxtTicketID.reset(); jtxtTicketID.activate(); jCheckBoxSales.setSelected(false); jCheckBoxRefunds.setSelected(false); jcboTimeFrame.setSelectedItem(null); jcboDayFrom.setSelectedItem(null); jcboMonthFrom.setSelectedItem(null); jcboYearFrom.setSelectedItem(null); jcboDayTo.setSelectedItem(null); jcboMonthTo.setSelectedItem(null); jcboYearTo.setSelectedItem(null); jcboUser.setSelectedItem(null); jcboMoney.setSelectedItem( ((ListQBFModelNumber)jcboMoney.getModel()).getElementAt(0) ); jcboMoney.revalidate(); jcboMoney.repaint(); jtxtMoney.reset(); } @Override public Object createValue() throws BasicException { boolean dateRange = false; Object[] afilter = new Object[12]; // Ticket ID if (jtxtTicketID.getText() == null || jtxtTicketID.getText().equals("")) { afilter[0] = QBFCompareEnum.COMP_NONE; afilter[1] = null; } else { afilter[0] = QBFCompareEnum.COMP_EQUALS; afilter[1] = jtxtTicketID.getValueInteger(); } // Sale and refund checkbox if (jCheckBoxSales.isSelected() && jCheckBoxRefunds.isSelected() || !jCheckBoxSales.isSelected() && !jCheckBoxRefunds.isSelected()) { afilter[2] = QBFCompareEnum.COMP_NONE; afilter[3] = null; } else if (jCheckBoxSales.isSelected()) { afilter[2] = QBFCompareEnum.COMP_EQUALS; afilter[3] = 0; } else if (jCheckBoxRefunds.isSelected()) { afilter[2] = QBFCompareEnum.COMP_EQUALS; afilter[3] = 1; } // Receipt money afilter[5] = jtxtMoney.getDoubleValue(); afilter[4] = afilter[5] == null ? QBFCompareEnum.COMP_NONE : jcboMoney.getSelectedItem(); //Timeframe if (jcboTimeFrame.getSelectedItem() == null) { dateRange = true; afilter[6] = QBFCompareEnum.COMP_NONE; afilter[7] = null; afilter[8] = QBFCompareEnum.COMP_NONE; afilter[9] = null; } else { int year = cal.get(Calendar.YEAR); String month = (cal.get(Calendar.MONTH) + 1 < 10) ? "0"+(cal.get(Calendar.MONTH) + 1) : Integer.toString(cal.get(Calendar.MONTH) + 1); String day = (cal.get(Calendar.DAY_OF_MONTH) < 10) ? "0"+cal.get(Calendar.DAY_OF_MONTH) : Integer.toString(cal.get(Calendar.DAY_OF_MONTH)); if (jcboTimeFrame.getSelectedItem() == LocalRes.getIntString("combo.today")) { afilter[6] = QBFCompareEnum.COMP_RE; afilter[7] = "%" + year +"-"+ month +"-"+ day + "%" ; afilter[8] = QBFCompareEnum.COMP_NONE; afilter[9] = null; } else if (jcboTimeFrame.getSelectedItem() == LocalRes.getIntString("combo.month")) { afilter[6] = QBFCompareEnum.COMP_RE; afilter[7] = "%" + year +"-"+ month + "%"; afilter[8] = QBFCompareEnum.COMP_NONE; afilter[9] = null; } else if (jcboTimeFrame.getSelectedItem() == LocalRes.getIntString("combo.year")) { afilter[6] = QBFCompareEnum.COMP_RE; afilter[7] = "%" + Integer.toString(year) + "%"; afilter[8] = QBFCompareEnum.COMP_NONE; afilter[9] = null; } } // Date range if (dateRange) { String dayF = (jcboDayFrom.getSelectedItem() == null) ? "0" : (String)jcboDayFrom.getSelectedItem(); String monthF = (jcboMonthFrom.getSelectedItem() == null) ? "1" : (String)jcboMonthFrom.getSelectedItem(); String dayT = (jcboDayTo.getSelectedItem() == null) ? "32" : String.valueOf( Integer.parseInt((String)jcboDayTo.getSelectedItem()) + 1 ); String monthT = (jcboMonthTo.getSelectedItem() == null) ? "12" : (String)jcboMonthTo.getSelectedItem(); if (jcboYearFrom.getSelectedItem() == null && jcboYearTo.getSelectedItem() == null) { afilter[6] = QBFCompareEnum.COMP_NONE; afilter[7] = null; afilter[8] = QBFCompareEnum.COMP_NONE; afilter[9] = null; } else if (jcboYearFrom.getSelectedItem() == null && jcboYearTo.getSelectedItem() != null) { afilter[6] = QBFCompareEnum.COMP_NONE; afilter[7] = null; afilter[8] = QBFCompareEnum.COMP_LESSOREQUALS; afilter[9] = jcboYearTo.getSelectedItem() +"-"+ monthT +"-"+ dayT; } else if (jcboYearFrom.getSelectedItem() != null && jcboYearTo.getSelectedItem() == null) { afilter[6] = QBFCompareEnum.COMP_GREATEROREQUALS; afilter[7] = jcboYearFrom.getSelectedItem() +"-"+ monthF +"-"+ dayF; afilter[8] = QBFCompareEnum.COMP_NONE; afilter[9] = null; } else { afilter[6] = QBFCompareEnum.COMP_GREATEROREQUALS; afilter[7] = jcboYearFrom.getSelectedItem() +"-"+ monthF +"-"+ dayF; afilter[8] = QBFCompareEnum.COMP_LESSOREQUALS; afilter[9] = jcboYearTo.getSelectedItem() +"-"+ monthT +"-"+ dayT; } } //User if (jcboUser.getSelectedItem() == null) { afilter[10] = QBFCompareEnum.COMP_NONE; afilter[11] = null; } else { afilter[10] = QBFCompareEnum.COMP_EQUALS; afilter[11] = ((TaxCategoryInfo)jcboUser.getSelectedItem()).getName(); } return afilter; } private static Window getWindow(Component parent) { if (parent == null) { return new JFrame(); } else if (parent instanceof Frame || parent instanceof Dialog) { return (Window) parent; } else { return getWindow(parent.getParent()); } } private static class MyListData extends javax.swing.AbstractListModel { private java.util.List m_data; public MyListData(java.util.List data) { m_data = data; } @Override public Object getElementAt(int index) { return m_data.get(index); } @Override public int getSize() { return m_data.size(); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jCheckBoxSales = new javax.swing.JCheckBox(); jCheckBoxRefunds = new javax.swing.JCheckBox(); jPanel9 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jcboYearFrom = new javax.swing.JComboBox(); jcboMonthFrom = new javax.swing.JComboBox(); jcboDayFrom = new javax.swing.JComboBox(); jcboYearTo = new javax.swing.JComboBox(); jcboMonthTo = new javax.swing.JComboBox(); jcboDayTo = new javax.swing.JComboBox(); jcboTimeFrame = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jtxtMoney = new com.openbravo.editor.JEditorCurrency(); jcboUser = new javax.swing.JComboBox(); jcboMoney = new javax.swing.JComboBox(); m_jKeys = new com.openbravo.editor.JEditorKeys(); jtxtTicketID = new com.openbravo.editor.JEditorIntegerPositive(); jPanel6 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jListTickets = new javax.swing.JList(); jPanel8 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jcmdOK = new javax.swing.JButton(); jcmdCancel = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); - setTitle(AppLocal.getIntString("form.customertitle")); // NOI18N + setTitle(AppLocal.getIntString("form.tickettitle")); // NOI18N + setBackground(java.awt.Color.white); jPanel3.setLayout(new java.awt.BorderLayout()); jPanel5.setLayout(new java.awt.BorderLayout()); jPanel7.setPreferredSize(new java.awt.Dimension(0, 270)); jLabel1.setText(AppLocal.getIntString("label.ticketid")); // NOI18N jLabel2.setText(AppLocal.getIntString("label.tickettype")); // NOI18N jCheckBoxSales.setText(AppLocal.getIntString("label.sales")); // NOI18N jCheckBoxRefunds.setText(AppLocal.getIntString("label.refunds")); // NOI18N jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder(AppLocal.getIntString("label.timeperiod"))); // NOI18N jLabel4.setText(AppLocal.getIntString("label.to")); // NOI18N jLabel3.setText(AppLocal.getIntString("label.timeframe")); // NOI18N jLabel5.setText(AppLocal.getIntString("label.from")); // NOI18N javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel5) .addComponent(jLabel4)) .addGap(39, 39, 39) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jcboYearTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboMonthTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboDayTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jcboYearFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboMonthFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboDayFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jcboTimeFrame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(169, Short.MAX_VALUE)) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jLabel3)) .addComponent(jcboTimeFrame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4)) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcboYearFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboMonthFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboDayFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcboYearTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboMonthTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboDayTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel6.setText(AppLocal.getIntString("label.user")); // NOI18N jLabel7.setText(AppLocal.getIntString("label.money")); // NOI18N javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(50, 50, 50) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(jCheckBoxSales) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxRefunds)) .addComponent(jtxtTicketID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(42, 42, 42)) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel6)) .addGap(80, 80, 80) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtxtMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jcboUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(m_jKeys, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(jtxtTicketID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jCheckBoxSales) .addComponent(jCheckBoxRefunds)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jcboUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jtxtMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcboMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)))) .addComponent(m_jKeys, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel5.add(jPanel7, java.awt.BorderLayout.CENTER); jButton1.setText(AppLocal.getIntString("button.clean")); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel6.add(jButton1); jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/launch.png"))); // NOI18N jButton3.setText(AppLocal.getIntString("button.executefilter")); // NOI18N jButton3.setFocusPainted(false); jButton3.setFocusable(false); jButton3.setRequestFocusEnabled(false); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jPanel6.add(jButton3); jPanel5.add(jPanel6, java.awt.BorderLayout.SOUTH); jPanel3.add(jPanel5, java.awt.BorderLayout.PAGE_START); jPanel4.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5)); jPanel4.setLayout(new java.awt.BorderLayout()); jListTickets.setFocusable(false); jListTickets.setRequestFocusEnabled(false); jListTickets.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jListTicketsMouseClicked(evt); } }); jListTickets.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { jListTicketsValueChanged(evt); } }); jScrollPane1.setViewportView(jListTickets); jPanel4.add(jScrollPane1, java.awt.BorderLayout.CENTER); jPanel3.add(jPanel4, java.awt.BorderLayout.CENTER); jPanel8.setLayout(new java.awt.BorderLayout()); jcmdOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N jcmdOK.setText(AppLocal.getIntString("Button.OK")); // NOI18N jcmdOK.setEnabled(false); jcmdOK.setFocusPainted(false); jcmdOK.setFocusable(false); jcmdOK.setMargin(new java.awt.Insets(8, 16, 8, 16)); jcmdOK.setRequestFocusEnabled(false); jcmdOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcmdOKActionPerformed(evt); } }); jPanel1.add(jcmdOK); jcmdCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N jcmdCancel.setText(AppLocal.getIntString("Button.Cancel")); // NOI18N jcmdCancel.setFocusPainted(false); jcmdCancel.setFocusable(false); jcmdCancel.setMargin(new java.awt.Insets(8, 16, 8, 16)); jcmdCancel.setRequestFocusEnabled(false); jcmdCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcmdCancelActionPerformed(evt); } }); jPanel1.add(jcmdCancel); jPanel8.add(jPanel1, java.awt.BorderLayout.LINE_END); jPanel3.add(jPanel8, java.awt.BorderLayout.SOUTH); getContentPane().add(jPanel3, java.awt.BorderLayout.CENTER); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-645)/2, (screenSize.height-684)/2, 645, 684); }// </editor-fold>//GEN-END:initComponents private void jcmdOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcmdOKActionPerformed selectedTicket = (FindTicketsInfo) jListTickets.getSelectedValue(); dispose(); }//GEN-LAST:event_jcmdOKActionPerformed private void jcmdCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcmdCancelActionPerformed dispose(); }//GEN-LAST:event_jcmdCancelActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed executeSearch(); }//GEN-LAST:event_jButton3ActionPerformed private void jListTicketsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jListTicketsValueChanged jcmdOK.setEnabled(jListTickets.getSelectedValue() != null); }//GEN-LAST:event_jListTicketsValueChanged private void jListTicketsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListTicketsMouseClicked if (evt.getClickCount() == 2) { selectedTicket = (FindTicketsInfo) jListTickets.getSelectedValue(); dispose(); } }//GEN-LAST:event_jListTicketsMouseClicked private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed defaultValues(); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton3; private javax.swing.JCheckBox jCheckBoxRefunds; private javax.swing.JCheckBox jCheckBoxSales; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JList jListTickets; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JComboBox jcboDayFrom; private javax.swing.JComboBox jcboDayTo; private javax.swing.JComboBox jcboMoney; private javax.swing.JComboBox jcboMonthFrom; private javax.swing.JComboBox jcboMonthTo; private javax.swing.JComboBox jcboTimeFrame; private javax.swing.JComboBox jcboUser; private javax.swing.JComboBox jcboYearFrom; private javax.swing.JComboBox jcboYearTo; private javax.swing.JButton jcmdCancel; private javax.swing.JButton jcmdOK; private com.openbravo.editor.JEditorCurrency jtxtMoney; private com.openbravo.editor.JEditorIntegerPositive jtxtTicketID; private com.openbravo.editor.JEditorKeys m_jKeys; // End of variables declaration//GEN-END:variables }
true
true
private void initComponents() { jPanel3 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jCheckBoxSales = new javax.swing.JCheckBox(); jCheckBoxRefunds = new javax.swing.JCheckBox(); jPanel9 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jcboYearFrom = new javax.swing.JComboBox(); jcboMonthFrom = new javax.swing.JComboBox(); jcboDayFrom = new javax.swing.JComboBox(); jcboYearTo = new javax.swing.JComboBox(); jcboMonthTo = new javax.swing.JComboBox(); jcboDayTo = new javax.swing.JComboBox(); jcboTimeFrame = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jtxtMoney = new com.openbravo.editor.JEditorCurrency(); jcboUser = new javax.swing.JComboBox(); jcboMoney = new javax.swing.JComboBox(); m_jKeys = new com.openbravo.editor.JEditorKeys(); jtxtTicketID = new com.openbravo.editor.JEditorIntegerPositive(); jPanel6 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jListTickets = new javax.swing.JList(); jPanel8 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jcmdOK = new javax.swing.JButton(); jcmdCancel = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle(AppLocal.getIntString("form.customertitle")); // NOI18N jPanel3.setLayout(new java.awt.BorderLayout()); jPanel5.setLayout(new java.awt.BorderLayout()); jPanel7.setPreferredSize(new java.awt.Dimension(0, 270)); jLabel1.setText(AppLocal.getIntString("label.ticketid")); // NOI18N jLabel2.setText(AppLocal.getIntString("label.tickettype")); // NOI18N jCheckBoxSales.setText(AppLocal.getIntString("label.sales")); // NOI18N jCheckBoxRefunds.setText(AppLocal.getIntString("label.refunds")); // NOI18N jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder(AppLocal.getIntString("label.timeperiod"))); // NOI18N jLabel4.setText(AppLocal.getIntString("label.to")); // NOI18N jLabel3.setText(AppLocal.getIntString("label.timeframe")); // NOI18N jLabel5.setText(AppLocal.getIntString("label.from")); // NOI18N javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel5) .addComponent(jLabel4)) .addGap(39, 39, 39) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jcboYearTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboMonthTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboDayTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jcboYearFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboMonthFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboDayFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jcboTimeFrame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(169, Short.MAX_VALUE)) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jLabel3)) .addComponent(jcboTimeFrame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4)) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcboYearFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboMonthFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboDayFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcboYearTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboMonthTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboDayTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel6.setText(AppLocal.getIntString("label.user")); // NOI18N jLabel7.setText(AppLocal.getIntString("label.money")); // NOI18N javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(50, 50, 50) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(jCheckBoxSales) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxRefunds)) .addComponent(jtxtTicketID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(42, 42, 42)) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel6)) .addGap(80, 80, 80) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtxtMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jcboUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(m_jKeys, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(jtxtTicketID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jCheckBoxSales) .addComponent(jCheckBoxRefunds)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jcboUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jtxtMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcboMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)))) .addComponent(m_jKeys, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel5.add(jPanel7, java.awt.BorderLayout.CENTER); jButton1.setText(AppLocal.getIntString("button.clean")); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel6.add(jButton1); jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/launch.png"))); // NOI18N jButton3.setText(AppLocal.getIntString("button.executefilter")); // NOI18N jButton3.setFocusPainted(false); jButton3.setFocusable(false); jButton3.setRequestFocusEnabled(false); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jPanel6.add(jButton3); jPanel5.add(jPanel6, java.awt.BorderLayout.SOUTH); jPanel3.add(jPanel5, java.awt.BorderLayout.PAGE_START); jPanel4.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5)); jPanel4.setLayout(new java.awt.BorderLayout()); jListTickets.setFocusable(false); jListTickets.setRequestFocusEnabled(false); jListTickets.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jListTicketsMouseClicked(evt); } }); jListTickets.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { jListTicketsValueChanged(evt); } }); jScrollPane1.setViewportView(jListTickets); jPanel4.add(jScrollPane1, java.awt.BorderLayout.CENTER); jPanel3.add(jPanel4, java.awt.BorderLayout.CENTER); jPanel8.setLayout(new java.awt.BorderLayout()); jcmdOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N jcmdOK.setText(AppLocal.getIntString("Button.OK")); // NOI18N jcmdOK.setEnabled(false); jcmdOK.setFocusPainted(false); jcmdOK.setFocusable(false); jcmdOK.setMargin(new java.awt.Insets(8, 16, 8, 16)); jcmdOK.setRequestFocusEnabled(false); jcmdOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcmdOKActionPerformed(evt); } }); jPanel1.add(jcmdOK); jcmdCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N jcmdCancel.setText(AppLocal.getIntString("Button.Cancel")); // NOI18N jcmdCancel.setFocusPainted(false); jcmdCancel.setFocusable(false); jcmdCancel.setMargin(new java.awt.Insets(8, 16, 8, 16)); jcmdCancel.setRequestFocusEnabled(false); jcmdCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcmdCancelActionPerformed(evt); } }); jPanel1.add(jcmdCancel); jPanel8.add(jPanel1, java.awt.BorderLayout.LINE_END); jPanel3.add(jPanel8, java.awt.BorderLayout.SOUTH); getContentPane().add(jPanel3, java.awt.BorderLayout.CENTER); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-645)/2, (screenSize.height-684)/2, 645, 684); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { jPanel3 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jCheckBoxSales = new javax.swing.JCheckBox(); jCheckBoxRefunds = new javax.swing.JCheckBox(); jPanel9 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jcboYearFrom = new javax.swing.JComboBox(); jcboMonthFrom = new javax.swing.JComboBox(); jcboDayFrom = new javax.swing.JComboBox(); jcboYearTo = new javax.swing.JComboBox(); jcboMonthTo = new javax.swing.JComboBox(); jcboDayTo = new javax.swing.JComboBox(); jcboTimeFrame = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jtxtMoney = new com.openbravo.editor.JEditorCurrency(); jcboUser = new javax.swing.JComboBox(); jcboMoney = new javax.swing.JComboBox(); m_jKeys = new com.openbravo.editor.JEditorKeys(); jtxtTicketID = new com.openbravo.editor.JEditorIntegerPositive(); jPanel6 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jListTickets = new javax.swing.JList(); jPanel8 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jcmdOK = new javax.swing.JButton(); jcmdCancel = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle(AppLocal.getIntString("form.tickettitle")); // NOI18N setBackground(java.awt.Color.white); jPanel3.setLayout(new java.awt.BorderLayout()); jPanel5.setLayout(new java.awt.BorderLayout()); jPanel7.setPreferredSize(new java.awt.Dimension(0, 270)); jLabel1.setText(AppLocal.getIntString("label.ticketid")); // NOI18N jLabel2.setText(AppLocal.getIntString("label.tickettype")); // NOI18N jCheckBoxSales.setText(AppLocal.getIntString("label.sales")); // NOI18N jCheckBoxRefunds.setText(AppLocal.getIntString("label.refunds")); // NOI18N jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder(AppLocal.getIntString("label.timeperiod"))); // NOI18N jLabel4.setText(AppLocal.getIntString("label.to")); // NOI18N jLabel3.setText(AppLocal.getIntString("label.timeframe")); // NOI18N jLabel5.setText(AppLocal.getIntString("label.from")); // NOI18N javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9); jPanel9.setLayout(jPanel9Layout); jPanel9Layout.setHorizontalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel5) .addComponent(jLabel4)) .addGap(39, 39, 39) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jcboYearTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboMonthTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboDayTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createSequentialGroup() .addComponent(jcboYearFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboMonthFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboDayFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jcboTimeFrame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(169, Short.MAX_VALUE)) ); jPanel9Layout.setVerticalGroup( jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jLabel3)) .addComponent(jcboTimeFrame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4)) .addGroup(jPanel9Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcboYearFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboMonthFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboDayFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(6, 6, 6) .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcboYearTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboMonthTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcboDayTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jLabel6.setText(AppLocal.getIntString("label.user")); // NOI18N jLabel7.setText(AppLocal.getIntString("label.money")); // NOI18N javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7); jPanel7.setLayout(jPanel7Layout); jPanel7Layout.setHorizontalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(50, 50, 50) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addComponent(jCheckBoxSales) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jCheckBoxRefunds)) .addComponent(jtxtTicketID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(42, 42, 42)) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel6)) .addGap(80, 80, 80) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel7Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jcboMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jtxtMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jcboUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(m_jKeys, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel7Layout.setVerticalGroup( jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel7Layout.createSequentialGroup() .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(jtxtTicketID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jCheckBoxSales) .addComponent(jCheckBoxRefunds)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jcboUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jtxtMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jcboMoney, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7)))) .addComponent(m_jKeys, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jPanel5.add(jPanel7, java.awt.BorderLayout.CENTER); jButton1.setText(AppLocal.getIntString("button.clean")); // NOI18N jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel6.add(jButton1); jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/launch.png"))); // NOI18N jButton3.setText(AppLocal.getIntString("button.executefilter")); // NOI18N jButton3.setFocusPainted(false); jButton3.setFocusable(false); jButton3.setRequestFocusEnabled(false); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jPanel6.add(jButton3); jPanel5.add(jPanel6, java.awt.BorderLayout.SOUTH); jPanel3.add(jPanel5, java.awt.BorderLayout.PAGE_START); jPanel4.setBorder(javax.swing.BorderFactory.createEmptyBorder(5, 5, 5, 5)); jPanel4.setLayout(new java.awt.BorderLayout()); jListTickets.setFocusable(false); jListTickets.setRequestFocusEnabled(false); jListTickets.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jListTicketsMouseClicked(evt); } }); jListTickets.addListSelectionListener(new javax.swing.event.ListSelectionListener() { public void valueChanged(javax.swing.event.ListSelectionEvent evt) { jListTicketsValueChanged(evt); } }); jScrollPane1.setViewportView(jListTickets); jPanel4.add(jScrollPane1, java.awt.BorderLayout.CENTER); jPanel3.add(jPanel4, java.awt.BorderLayout.CENTER); jPanel8.setLayout(new java.awt.BorderLayout()); jcmdOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N jcmdOK.setText(AppLocal.getIntString("Button.OK")); // NOI18N jcmdOK.setEnabled(false); jcmdOK.setFocusPainted(false); jcmdOK.setFocusable(false); jcmdOK.setMargin(new java.awt.Insets(8, 16, 8, 16)); jcmdOK.setRequestFocusEnabled(false); jcmdOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcmdOKActionPerformed(evt); } }); jPanel1.add(jcmdOK); jcmdCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N jcmdCancel.setText(AppLocal.getIntString("Button.Cancel")); // NOI18N jcmdCancel.setFocusPainted(false); jcmdCancel.setFocusable(false); jcmdCancel.setMargin(new java.awt.Insets(8, 16, 8, 16)); jcmdCancel.setRequestFocusEnabled(false); jcmdCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcmdCancelActionPerformed(evt); } }); jPanel1.add(jcmdCancel); jPanel8.add(jPanel1, java.awt.BorderLayout.LINE_END); jPanel3.add(jPanel8, java.awt.BorderLayout.SOUTH); getContentPane().add(jPanel3, java.awt.BorderLayout.CENTER); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-645)/2, (screenSize.height-684)/2, 645, 684); }// </editor-fold>//GEN-END:initComponents
diff --git a/obdalib/obdalib-core/src/main/java/inf/unibz/it/obda/codec/xml/DatalogConjunctiveQueryCodec.java b/obdalib/obdalib-core/src/main/java/inf/unibz/it/obda/codec/xml/DatalogConjunctiveQueryCodec.java index 4624f9ba7..0b434d3dc 100644 --- a/obdalib/obdalib-core/src/main/java/inf/unibz/it/obda/codec/xml/DatalogConjunctiveQueryCodec.java +++ b/obdalib/obdalib-core/src/main/java/inf/unibz/it/obda/codec/xml/DatalogConjunctiveQueryCodec.java @@ -1,125 +1,125 @@ package inf.unibz.it.obda.codec.xml; import inf.unibz.it.obda.api.controller.APIController; import inf.unibz.it.utils.codec.ObjectXMLCodec; import inf.unibz.it.utils.codec.TargetQeryToTextCodec; import java.util.ArrayList; import java.util.Collection; import org.antlr.runtime.RecognitionException; import org.obda.query.domain.CQIE; import org.obda.query.tools.parser.DatalogProgramParser; import org.obda.query.tools.parser.DatalogQueryHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; /** * The DatalogConjunctiveQueryCodec can be used to encode a conjunctive query * into XML or to decode a conjunctive query from XML * * @author Manfred Gerstgrasser * */ public class DatalogConjunctiveQueryCodec extends ObjectXMLCodec<CQIE> { /** * The tag used to represent a conjunctive query in XML */ private static final String TAG = "CQ"; /** * the current api controller */ APIController apic = null; DatalogProgramParser datalogParser = new DatalogProgramParser(); private final Logger log = LoggerFactory.getLogger(this.getClass()); public DatalogConjunctiveQueryCodec(APIController apic){ this.apic = apic; } /** * Decodes the given XML element into an conjunctive query. */ @Override public CQIE decode(Element input) { String query = input.getAttribute("string"); return decode(query); } /** * Encodes the given conjunctive query int XML. */ @Override public Element encode(CQIE hq) { Element mappingheadelement = createElement(TAG); TargetQeryToTextCodec codec = new TargetQeryToTextCodec(apic); mappingheadelement.setAttribute("string", codec.encode(hq)); return mappingheadelement; } /** * Returns all attributes used in conjunctive query element. */ @Override public Collection<String> getAttributes() { ArrayList<String> fixedAttributes = new ArrayList<String>(); fixedAttributes.add("string"); return fixedAttributes; } /** * Returns the tag name for conjunctive queries */ @Override public String getElementTag() { // TODO Auto-generated method stub return TAG; } /** * Decodes the given String into an conjunctive query. */ public CQIE decode(String input) { return parse(input); } private CQIE parse(String query) { CQIE cq = null; query = prepareQuery(query); try { datalogParser.parse(query); cq = datalogParser.getRule(0); } catch (RecognitionException e) { log.warn(e.getMessage()); } return cq; } private String prepareQuery(String input) { - String query = ""; + String query = input; DatalogQueryHelper queryHelper = new DatalogQueryHelper(apic.getIOManager().getPrefixManager()); String[] atoms = input.split(DatalogQueryHelper.DATALOG_IMPLY_SYMBOL, 2); if (atoms.length == 1) // if no head query = queryHelper.getDefaultHead() + " " + DatalogQueryHelper.DATALOG_IMPLY_SYMBOL + " " + - input; + query; // Append the prefixes query = queryHelper.getPrefixes() + query; return query; } }
false
true
private String prepareQuery(String input) { String query = ""; DatalogQueryHelper queryHelper = new DatalogQueryHelper(apic.getIOManager().getPrefixManager()); String[] atoms = input.split(DatalogQueryHelper.DATALOG_IMPLY_SYMBOL, 2); if (atoms.length == 1) // if no head query = queryHelper.getDefaultHead() + " " + DatalogQueryHelper.DATALOG_IMPLY_SYMBOL + " " + input; // Append the prefixes query = queryHelper.getPrefixes() + query; return query; }
private String prepareQuery(String input) { String query = input; DatalogQueryHelper queryHelper = new DatalogQueryHelper(apic.getIOManager().getPrefixManager()); String[] atoms = input.split(DatalogQueryHelper.DATALOG_IMPLY_SYMBOL, 2); if (atoms.length == 1) // if no head query = queryHelper.getDefaultHead() + " " + DatalogQueryHelper.DATALOG_IMPLY_SYMBOL + " " + query; // Append the prefixes query = queryHelper.getPrefixes() + query; return query; }
diff --git a/openelis/src/us/mn/state/health/lims/common/formfields/BahmniFormFields.java b/openelis/src/us/mn/state/health/lims/common/formfields/BahmniFormFields.java index 824d7293..0ef23387 100644 --- a/openelis/src/us/mn/state/health/lims/common/formfields/BahmniFormFields.java +++ b/openelis/src/us/mn/state/health/lims/common/formfields/BahmniFormFields.java @@ -1,62 +1,63 @@ /** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations under * the License. * * The Original Code is OpenELIS code. * * Copyright (C) The Minnesota Department of Health. All Rights Reserved. * * Contributor(s): CIRG, University of Washington, Seattle WA. */ package us.mn.state.health.lims.common.formfields; import us.mn.state.health.lims.common.formfields.FormFields.Field; import java.util.HashMap; public class BahmniFormFields implements IFormFieldsForImplementation { public HashMap<Field, Boolean> getImplementationAttributes() { HashMap<Field, Boolean> settings = new HashMap<Field, Boolean>(); settings.put(Field.OrgState, Boolean.FALSE); settings.put(Field.ZipCode, Boolean.FALSE); settings.put(Field.MLS, Boolean.FALSE); settings.put(Field.OrganizationCLIA, Boolean.FALSE); settings.put(Field.OrganizationParent, Boolean.FALSE); settings.put(Field.InlineOrganizationTypes, Boolean.TRUE); settings.put(Field.DepersonalizedResults, Boolean.TRUE); settings.put(Field.OrgLocalAbrev, Boolean.FALSE); settings.put(Field.OrganizationShortName, Boolean.TRUE); settings.put(Field.OrganizationMultiUnit, Boolean.FALSE); settings.put(Field.OrganizationOrgId, Boolean.FALSE); settings.put(Field.AddressCity, Boolean.FALSE); settings.put(Field.AddressCommune, Boolean.FALSE); settings.put(Field.AddressDepartment, Boolean.FALSE); settings.put(Field.AddressVillage, Boolean.FALSE); settings.put(Field.PatientRequired, Boolean.TRUE); settings.put(Field.DynamicAddress, Boolean.TRUE); settings.put(Field.SampleCondition, Boolean.TRUE); settings.put(Field.NON_CONFORMITY_SITE_LIST, Boolean.TRUE); settings.put(Field.ValueHozSpaceOnResults, Boolean.TRUE); settings.put(Field.FirstNameFirst,Boolean.TRUE); settings.put(Field.NationalID,Boolean.FALSE); settings.put(Field.HealthCenter, Boolean.TRUE); settings.put(Field.ResultsReferral, Boolean.TRUE); settings.put(Field.PatientType, Boolean.FALSE); settings.put(Field.UseSampleSource, Boolean.TRUE); settings.put(Field.AllowEditOrRemoveTests, Boolean.FALSE); settings.put(Field.MothersName, Boolean.FALSE); settings.put(Field.SupportPrimaryRelative, Boolean.TRUE); + settings.put(Field.StNumber, Boolean.TRUE); return settings; } }
true
true
public HashMap<Field, Boolean> getImplementationAttributes() { HashMap<Field, Boolean> settings = new HashMap<Field, Boolean>(); settings.put(Field.OrgState, Boolean.FALSE); settings.put(Field.ZipCode, Boolean.FALSE); settings.put(Field.MLS, Boolean.FALSE); settings.put(Field.OrganizationCLIA, Boolean.FALSE); settings.put(Field.OrganizationParent, Boolean.FALSE); settings.put(Field.InlineOrganizationTypes, Boolean.TRUE); settings.put(Field.DepersonalizedResults, Boolean.TRUE); settings.put(Field.OrgLocalAbrev, Boolean.FALSE); settings.put(Field.OrganizationShortName, Boolean.TRUE); settings.put(Field.OrganizationMultiUnit, Boolean.FALSE); settings.put(Field.OrganizationOrgId, Boolean.FALSE); settings.put(Field.AddressCity, Boolean.FALSE); settings.put(Field.AddressCommune, Boolean.FALSE); settings.put(Field.AddressDepartment, Boolean.FALSE); settings.put(Field.AddressVillage, Boolean.FALSE); settings.put(Field.PatientRequired, Boolean.TRUE); settings.put(Field.DynamicAddress, Boolean.TRUE); settings.put(Field.SampleCondition, Boolean.TRUE); settings.put(Field.NON_CONFORMITY_SITE_LIST, Boolean.TRUE); settings.put(Field.ValueHozSpaceOnResults, Boolean.TRUE); settings.put(Field.FirstNameFirst,Boolean.TRUE); settings.put(Field.NationalID,Boolean.FALSE); settings.put(Field.HealthCenter, Boolean.TRUE); settings.put(Field.ResultsReferral, Boolean.TRUE); settings.put(Field.PatientType, Boolean.FALSE); settings.put(Field.UseSampleSource, Boolean.TRUE); settings.put(Field.AllowEditOrRemoveTests, Boolean.FALSE); settings.put(Field.MothersName, Boolean.FALSE); settings.put(Field.SupportPrimaryRelative, Boolean.TRUE); return settings; }
public HashMap<Field, Boolean> getImplementationAttributes() { HashMap<Field, Boolean> settings = new HashMap<Field, Boolean>(); settings.put(Field.OrgState, Boolean.FALSE); settings.put(Field.ZipCode, Boolean.FALSE); settings.put(Field.MLS, Boolean.FALSE); settings.put(Field.OrganizationCLIA, Boolean.FALSE); settings.put(Field.OrganizationParent, Boolean.FALSE); settings.put(Field.InlineOrganizationTypes, Boolean.TRUE); settings.put(Field.DepersonalizedResults, Boolean.TRUE); settings.put(Field.OrgLocalAbrev, Boolean.FALSE); settings.put(Field.OrganizationShortName, Boolean.TRUE); settings.put(Field.OrganizationMultiUnit, Boolean.FALSE); settings.put(Field.OrganizationOrgId, Boolean.FALSE); settings.put(Field.AddressCity, Boolean.FALSE); settings.put(Field.AddressCommune, Boolean.FALSE); settings.put(Field.AddressDepartment, Boolean.FALSE); settings.put(Field.AddressVillage, Boolean.FALSE); settings.put(Field.PatientRequired, Boolean.TRUE); settings.put(Field.DynamicAddress, Boolean.TRUE); settings.put(Field.SampleCondition, Boolean.TRUE); settings.put(Field.NON_CONFORMITY_SITE_LIST, Boolean.TRUE); settings.put(Field.ValueHozSpaceOnResults, Boolean.TRUE); settings.put(Field.FirstNameFirst,Boolean.TRUE); settings.put(Field.NationalID,Boolean.FALSE); settings.put(Field.HealthCenter, Boolean.TRUE); settings.put(Field.ResultsReferral, Boolean.TRUE); settings.put(Field.PatientType, Boolean.FALSE); settings.put(Field.UseSampleSource, Boolean.TRUE); settings.put(Field.AllowEditOrRemoveTests, Boolean.FALSE); settings.put(Field.MothersName, Boolean.FALSE); settings.put(Field.SupportPrimaryRelative, Boolean.TRUE); settings.put(Field.StNumber, Boolean.TRUE); return settings; }
diff --git a/src/main/java/com/ids/businessLogic/FirstTimeQuery.java b/src/main/java/com/ids/businessLogic/FirstTimeQuery.java index 18b95c0..af6876f 100644 --- a/src/main/java/com/ids/businessLogic/FirstTimeQuery.java +++ b/src/main/java/com/ids/businessLogic/FirstTimeQuery.java @@ -1,298 +1,298 @@ package com.ids.businessLogic; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import org.json.JSONArray; import org.json.JSONObject; import java.util.logging.Level; import java.util.logging.Logger; import org.slf4j.LoggerFactory; import org.springframework.ui.ModelMap; import com.ids.entities.Company; import com.ids.entities.Country; import com.ids.entities.Product; import com.ids.entities.Year; import com.ids.json.ColumnModel; import com.ids.json.TitleArray; import com.ids.json.YearArray; public class FirstTimeQuery { private ModelMap model; private HashMap<String,Integer> totalLine2 = null; private HashMap<String,Integer> otherLine2 = null; private final static Logger logger = Logger.getLogger(FirstTimeEdQuery.class.getName()); public FirstTimeQuery(ModelMap model,Connection con,HttpServletRequest request, int curYear, String access){ try { Statement statement = con.createStatement(); String query=null; ResultSet resultSet = null; TitleArray titleArray= new TitleArray("Austria","Agricultural Tractor", "sales" ); int countryId = 7; //Austria String multiplier=""; if (access.equals("c")) { titleArray = new TitleArray("China","Agricultural Tractor", "sales" ); countryId = 210000; //China multiplier="*10000"; } if (access.equals("i")) { titleArray = new TitleArray("India","Agricultural Tractor", "sales" ); countryId = 2000000; //India multiplier="*200000"; } query="SELECT YEAR(DATE_ADD( CURDATE(), INTERVAL -5 YEAR)) as year1 "; List<Year> years = new ArrayList<Year>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Year year = new Year(resultSet.getString("year1"),resultSet.getString("year1")); years.add(year); for (int i=1;i<=10;i++) { Year nextYear = new Year( Integer.toString(Integer.parseInt(year.getId())+i), Integer.toString(Integer.parseInt(year.getId())+i)); years.add(nextYear); } } YearArray yearArray = new YearArray("Company",years,"TOTAL"); ColumnModel columnModel = new ColumnModel(yearArray.getJsonYearArray()); String query2=""; if (access.equals("w")) { - query2 = " select a.year, SUM(a.quantity) as quantity, substr(b.name,1,20) as company " + + query2 = " select a.year, SUM(a.quantity) as quantity, substr(b.name,1,20) as name " + " from Facts_w a, Company b, Country c, Product d "+ " where a.companyid=b.id and a.sales_production=1 AND a.countryId NOT IN (20,21,0) "+ " and a.productId = 1 and a.year >=2008 and b.name != 'ALL COMPANIES' "+ " and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " + " and d.id = a.productId and a.access = 'w' and a.countryId = c.id "+ " group by a.year, b.name, d.name, 'EUROPE' order by b.name , a.year asc "; }else { query2 = " select a.year, a.quantity, b.name from Facts_"+access+" a, Company b, Country c " + " where a.companyid=b.id " + " and a.countryid=c.id " + " and c.id="+countryId + " and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " + " and a.sales_production= 1" + " and a.productid=1"+multiplier + " and a.access = '" + access + "' " + " and b.name!='ALL COMPANIES' " + " order by b.name , a.year asc"; } resultSet = statement.executeQuery(query2); String currentCompany=""; JSONObject obj2a = null; JSONArray array7 = new JSONArray(); totalLine2 = new HashMap<String,Integer>(); otherLine2 = new HashMap<String,Integer>(); while (resultSet.next()) { int totalQuantity=0; if (totalLine2.get(resultSet.getString("year"))!= null) { totalQuantity= totalLine2.get(resultSet.getString("year")); } totalQuantity += Integer.parseInt(resultSet.getString("quantity")); totalLine2.put(resultSet.getString("year"), totalQuantity); int otherQuantity=0; if (otherLine2.get(resultSet.getString("year"))!= null) { otherQuantity= otherLine2.get(resultSet.getString("year")); } otherQuantity += Integer.parseInt(resultSet.getString("quantity")); otherLine2.put(resultSet.getString("year"), otherQuantity); if (!currentCompany.equals(resultSet.getString("name"))) { if (!currentCompany.equals("")){ array7.put(obj2a); } obj2a = new JSONObject(); currentCompany=resultSet.getString("name"); obj2a.put("Company",currentCompany); obj2a.put(resultSet.getString("year"),resultSet.getString("quantity")); } else { obj2a.put(resultSet.getString("year"),resultSet.getString("quantity")); } } if (obj2a != null) { array7.put(obj2a); } /* JSONObject objTotal = new JSONObject(); objTotal.put("Company","TOTAL"); Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator(); while (it.hasNext()) { Entry<String, Integer> pairs = it.next(); objTotal.put(pairs.getKey(), pairs.getValue()); } objTotal.put("Total", 0); JSONArray array8 = new JSONArray(); if (objTotal != null) { array8.put(objTotal); JSONObject obj8 = new JSONObject(); obj8.put("myTotals", array8); model.addAttribute("jsonTotal",obj8); } */ JSONObject obj7 = new JSONObject(); obj7.put("myData", array7); JSONArray array4 = new JSONArray(); array4.put(columnModel.getModelObject()); array4.put(yearArray.getJsonYearObject()); array4.put(obj7); array4.put(titleArray.getJsonTitleObject()); JSONObject obj5 = new JSONObject(); obj5.put("tabData", array4); AddJsonRowTotal aj = new AddJsonRowTotal(obj5); JSONObject objTotal = new JSONObject(); objTotal.put("Company","TOTAL"); Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator(); while (it.hasNext()) { Entry<String, Integer> pairs = it.next(); objTotal.put(pairs.getKey(), pairs.getValue()); } objTotal.put("TOTAL", aj.getTotal()); JSONArray array8 = new JSONArray(); if (objTotal != null) { array8.put(objTotal); JSONObject obj8 = new JSONObject(); obj8.put("myTotals", array8); model.addAttribute("jsonTotal",obj8); } model.addAttribute("jsonData",obj5); logger.warning(obj5.toString()); if (request.getParameter("list") == null){ query = "select id, country from Country where id != 0 and access = '"+access+"' order by country asc " ; List<Country> countries = new ArrayList<Country>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Country country = new Country(resultSet.getString("id"),resultSet.getString("country")); countries.add(country); } model.addAttribute("dropdown1a",countries); model.addAttribute("dropdown2a",countries); query = "select id, name from Product where id != 0 and access = '"+access+"' order by name asc " ; List<Product> products = new ArrayList<Product>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Product product = new Product(resultSet.getString("id"),resultSet.getString("name")); products.add(product); } model.addAttribute("dropdown1b",products); model.addAttribute("dropdown2b",products); model.addAttribute("dropdown1c",years); model.addAttribute("dropdown2c",years); query = " select distinct a.id, substr(a.name,1,20) as name from Company a , Facts_"+access+" b " + " where a.id != 0" + " and b.companyid = a.id " + " and b.access = '" + access +"' and " + " a.access = '" + access + "' " + " and a.name != 'ALL COMPANIES' " + // " and b.year between "+(curYear - 5)+" and "+(curYear+5)+ " order by a.name asc " ; logger.warning(query); List<Company> companies = new ArrayList<Company>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Company company = new Company(resultSet.getString("id"),resultSet.getString("name")); companies.add(company); } model.addAttribute("dropdown1d",companies); model.addAttribute("dropdown2d",companies); model.addAttribute("firstTimeFromServer",obj5); this.model = model; } }catch(Exception e) { logger.warning("ERRRRRRRRRRROR: "+e.getMessage()); e.printStackTrace(); } } public ModelMap getModel() { return this.model; } }
true
true
public FirstTimeQuery(ModelMap model,Connection con,HttpServletRequest request, int curYear, String access){ try { Statement statement = con.createStatement(); String query=null; ResultSet resultSet = null; TitleArray titleArray= new TitleArray("Austria","Agricultural Tractor", "sales" ); int countryId = 7; //Austria String multiplier=""; if (access.equals("c")) { titleArray = new TitleArray("China","Agricultural Tractor", "sales" ); countryId = 210000; //China multiplier="*10000"; } if (access.equals("i")) { titleArray = new TitleArray("India","Agricultural Tractor", "sales" ); countryId = 2000000; //India multiplier="*200000"; } query="SELECT YEAR(DATE_ADD( CURDATE(), INTERVAL -5 YEAR)) as year1 "; List<Year> years = new ArrayList<Year>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Year year = new Year(resultSet.getString("year1"),resultSet.getString("year1")); years.add(year); for (int i=1;i<=10;i++) { Year nextYear = new Year( Integer.toString(Integer.parseInt(year.getId())+i), Integer.toString(Integer.parseInt(year.getId())+i)); years.add(nextYear); } } YearArray yearArray = new YearArray("Company",years,"TOTAL"); ColumnModel columnModel = new ColumnModel(yearArray.getJsonYearArray()); String query2=""; if (access.equals("w")) { query2 = " select a.year, SUM(a.quantity) as quantity, substr(b.name,1,20) as company " + " from Facts_w a, Company b, Country c, Product d "+ " where a.companyid=b.id and a.sales_production=1 AND a.countryId NOT IN (20,21,0) "+ " and a.productId = 1 and a.year >=2008 and b.name != 'ALL COMPANIES' "+ " and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " + " and d.id = a.productId and a.access = 'w' and a.countryId = c.id "+ " group by a.year, b.name, d.name, 'EUROPE' order by b.name , a.year asc "; }else { query2 = " select a.year, a.quantity, b.name from Facts_"+access+" a, Company b, Country c " + " where a.companyid=b.id " + " and a.countryid=c.id " + " and c.id="+countryId + " and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " + " and a.sales_production= 1" + " and a.productid=1"+multiplier + " and a.access = '" + access + "' " + " and b.name!='ALL COMPANIES' " + " order by b.name , a.year asc"; } resultSet = statement.executeQuery(query2); String currentCompany=""; JSONObject obj2a = null; JSONArray array7 = new JSONArray(); totalLine2 = new HashMap<String,Integer>(); otherLine2 = new HashMap<String,Integer>(); while (resultSet.next()) { int totalQuantity=0; if (totalLine2.get(resultSet.getString("year"))!= null) { totalQuantity= totalLine2.get(resultSet.getString("year")); } totalQuantity += Integer.parseInt(resultSet.getString("quantity")); totalLine2.put(resultSet.getString("year"), totalQuantity); int otherQuantity=0; if (otherLine2.get(resultSet.getString("year"))!= null) { otherQuantity= otherLine2.get(resultSet.getString("year")); } otherQuantity += Integer.parseInt(resultSet.getString("quantity")); otherLine2.put(resultSet.getString("year"), otherQuantity); if (!currentCompany.equals(resultSet.getString("name"))) { if (!currentCompany.equals("")){ array7.put(obj2a); } obj2a = new JSONObject(); currentCompany=resultSet.getString("name"); obj2a.put("Company",currentCompany); obj2a.put(resultSet.getString("year"),resultSet.getString("quantity")); } else { obj2a.put(resultSet.getString("year"),resultSet.getString("quantity")); } } if (obj2a != null) { array7.put(obj2a); } /* JSONObject objTotal = new JSONObject(); objTotal.put("Company","TOTAL"); Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator(); while (it.hasNext()) { Entry<String, Integer> pairs = it.next(); objTotal.put(pairs.getKey(), pairs.getValue()); } objTotal.put("Total", 0); JSONArray array8 = new JSONArray(); if (objTotal != null) { array8.put(objTotal); JSONObject obj8 = new JSONObject(); obj8.put("myTotals", array8); model.addAttribute("jsonTotal",obj8); } */ JSONObject obj7 = new JSONObject(); obj7.put("myData", array7); JSONArray array4 = new JSONArray(); array4.put(columnModel.getModelObject()); array4.put(yearArray.getJsonYearObject()); array4.put(obj7); array4.put(titleArray.getJsonTitleObject()); JSONObject obj5 = new JSONObject(); obj5.put("tabData", array4); AddJsonRowTotal aj = new AddJsonRowTotal(obj5); JSONObject objTotal = new JSONObject(); objTotal.put("Company","TOTAL"); Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator(); while (it.hasNext()) { Entry<String, Integer> pairs = it.next(); objTotal.put(pairs.getKey(), pairs.getValue()); } objTotal.put("TOTAL", aj.getTotal()); JSONArray array8 = new JSONArray(); if (objTotal != null) { array8.put(objTotal); JSONObject obj8 = new JSONObject(); obj8.put("myTotals", array8); model.addAttribute("jsonTotal",obj8); } model.addAttribute("jsonData",obj5); logger.warning(obj5.toString()); if (request.getParameter("list") == null){ query = "select id, country from Country where id != 0 and access = '"+access+"' order by country asc " ; List<Country> countries = new ArrayList<Country>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Country country = new Country(resultSet.getString("id"),resultSet.getString("country")); countries.add(country); } model.addAttribute("dropdown1a",countries); model.addAttribute("dropdown2a",countries); query = "select id, name from Product where id != 0 and access = '"+access+"' order by name asc " ; List<Product> products = new ArrayList<Product>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Product product = new Product(resultSet.getString("id"),resultSet.getString("name")); products.add(product); } model.addAttribute("dropdown1b",products); model.addAttribute("dropdown2b",products); model.addAttribute("dropdown1c",years); model.addAttribute("dropdown2c",years); query = " select distinct a.id, substr(a.name,1,20) as name from Company a , Facts_"+access+" b " + " where a.id != 0" + " and b.companyid = a.id " + " and b.access = '" + access +"' and " + " a.access = '" + access + "' " + " and a.name != 'ALL COMPANIES' " + // " and b.year between "+(curYear - 5)+" and "+(curYear+5)+ " order by a.name asc " ; logger.warning(query); List<Company> companies = new ArrayList<Company>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Company company = new Company(resultSet.getString("id"),resultSet.getString("name")); companies.add(company); } model.addAttribute("dropdown1d",companies); model.addAttribute("dropdown2d",companies); model.addAttribute("firstTimeFromServer",obj5); this.model = model; } }catch(Exception e) { logger.warning("ERRRRRRRRRRROR: "+e.getMessage()); e.printStackTrace(); } }
public FirstTimeQuery(ModelMap model,Connection con,HttpServletRequest request, int curYear, String access){ try { Statement statement = con.createStatement(); String query=null; ResultSet resultSet = null; TitleArray titleArray= new TitleArray("Austria","Agricultural Tractor", "sales" ); int countryId = 7; //Austria String multiplier=""; if (access.equals("c")) { titleArray = new TitleArray("China","Agricultural Tractor", "sales" ); countryId = 210000; //China multiplier="*10000"; } if (access.equals("i")) { titleArray = new TitleArray("India","Agricultural Tractor", "sales" ); countryId = 2000000; //India multiplier="*200000"; } query="SELECT YEAR(DATE_ADD( CURDATE(), INTERVAL -5 YEAR)) as year1 "; List<Year> years = new ArrayList<Year>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Year year = new Year(resultSet.getString("year1"),resultSet.getString("year1")); years.add(year); for (int i=1;i<=10;i++) { Year nextYear = new Year( Integer.toString(Integer.parseInt(year.getId())+i), Integer.toString(Integer.parseInt(year.getId())+i)); years.add(nextYear); } } YearArray yearArray = new YearArray("Company",years,"TOTAL"); ColumnModel columnModel = new ColumnModel(yearArray.getJsonYearArray()); String query2=""; if (access.equals("w")) { query2 = " select a.year, SUM(a.quantity) as quantity, substr(b.name,1,20) as name " + " from Facts_w a, Company b, Country c, Product d "+ " where a.companyid=b.id and a.sales_production=1 AND a.countryId NOT IN (20,21,0) "+ " and a.productId = 1 and a.year >=2008 and b.name != 'ALL COMPANIES' "+ " and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " + " and d.id = a.productId and a.access = 'w' and a.countryId = c.id "+ " group by a.year, b.name, d.name, 'EUROPE' order by b.name , a.year asc "; }else { query2 = " select a.year, a.quantity, b.name from Facts_"+access+" a, Company b, Country c " + " where a.companyid=b.id " + " and a.countryid=c.id " + " and c.id="+countryId + " and a.year between "+(curYear - 5)+" and "+(curYear+5)+" " + " and a.sales_production= 1" + " and a.productid=1"+multiplier + " and a.access = '" + access + "' " + " and b.name!='ALL COMPANIES' " + " order by b.name , a.year asc"; } resultSet = statement.executeQuery(query2); String currentCompany=""; JSONObject obj2a = null; JSONArray array7 = new JSONArray(); totalLine2 = new HashMap<String,Integer>(); otherLine2 = new HashMap<String,Integer>(); while (resultSet.next()) { int totalQuantity=0; if (totalLine2.get(resultSet.getString("year"))!= null) { totalQuantity= totalLine2.get(resultSet.getString("year")); } totalQuantity += Integer.parseInt(resultSet.getString("quantity")); totalLine2.put(resultSet.getString("year"), totalQuantity); int otherQuantity=0; if (otherLine2.get(resultSet.getString("year"))!= null) { otherQuantity= otherLine2.get(resultSet.getString("year")); } otherQuantity += Integer.parseInt(resultSet.getString("quantity")); otherLine2.put(resultSet.getString("year"), otherQuantity); if (!currentCompany.equals(resultSet.getString("name"))) { if (!currentCompany.equals("")){ array7.put(obj2a); } obj2a = new JSONObject(); currentCompany=resultSet.getString("name"); obj2a.put("Company",currentCompany); obj2a.put(resultSet.getString("year"),resultSet.getString("quantity")); } else { obj2a.put(resultSet.getString("year"),resultSet.getString("quantity")); } } if (obj2a != null) { array7.put(obj2a); } /* JSONObject objTotal = new JSONObject(); objTotal.put("Company","TOTAL"); Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator(); while (it.hasNext()) { Entry<String, Integer> pairs = it.next(); objTotal.put(pairs.getKey(), pairs.getValue()); } objTotal.put("Total", 0); JSONArray array8 = new JSONArray(); if (objTotal != null) { array8.put(objTotal); JSONObject obj8 = new JSONObject(); obj8.put("myTotals", array8); model.addAttribute("jsonTotal",obj8); } */ JSONObject obj7 = new JSONObject(); obj7.put("myData", array7); JSONArray array4 = new JSONArray(); array4.put(columnModel.getModelObject()); array4.put(yearArray.getJsonYearObject()); array4.put(obj7); array4.put(titleArray.getJsonTitleObject()); JSONObject obj5 = new JSONObject(); obj5.put("tabData", array4); AddJsonRowTotal aj = new AddJsonRowTotal(obj5); JSONObject objTotal = new JSONObject(); objTotal.put("Company","TOTAL"); Iterator<Entry<String, Integer>> it = totalLine2.entrySet().iterator(); while (it.hasNext()) { Entry<String, Integer> pairs = it.next(); objTotal.put(pairs.getKey(), pairs.getValue()); } objTotal.put("TOTAL", aj.getTotal()); JSONArray array8 = new JSONArray(); if (objTotal != null) { array8.put(objTotal); JSONObject obj8 = new JSONObject(); obj8.put("myTotals", array8); model.addAttribute("jsonTotal",obj8); } model.addAttribute("jsonData",obj5); logger.warning(obj5.toString()); if (request.getParameter("list") == null){ query = "select id, country from Country where id != 0 and access = '"+access+"' order by country asc " ; List<Country> countries = new ArrayList<Country>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Country country = new Country(resultSet.getString("id"),resultSet.getString("country")); countries.add(country); } model.addAttribute("dropdown1a",countries); model.addAttribute("dropdown2a",countries); query = "select id, name from Product where id != 0 and access = '"+access+"' order by name asc " ; List<Product> products = new ArrayList<Product>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Product product = new Product(resultSet.getString("id"),resultSet.getString("name")); products.add(product); } model.addAttribute("dropdown1b",products); model.addAttribute("dropdown2b",products); model.addAttribute("dropdown1c",years); model.addAttribute("dropdown2c",years); query = " select distinct a.id, substr(a.name,1,20) as name from Company a , Facts_"+access+" b " + " where a.id != 0" + " and b.companyid = a.id " + " and b.access = '" + access +"' and " + " a.access = '" + access + "' " + " and a.name != 'ALL COMPANIES' " + // " and b.year between "+(curYear - 5)+" and "+(curYear+5)+ " order by a.name asc " ; logger.warning(query); List<Company> companies = new ArrayList<Company>(); resultSet = statement.executeQuery(query); while (resultSet.next()) { Company company = new Company(resultSet.getString("id"),resultSet.getString("name")); companies.add(company); } model.addAttribute("dropdown1d",companies); model.addAttribute("dropdown2d",companies); model.addAttribute("firstTimeFromServer",obj5); this.model = model; } }catch(Exception e) { logger.warning("ERRRRRRRRRRROR: "+e.getMessage()); e.printStackTrace(); } }
diff --git a/framework/src/org/apache/cordova/CordovaWebView.java b/framework/src/org/apache/cordova/CordovaWebView.java index 60a46a35..5dd061e4 100755 --- a/framework/src/org/apache/cordova/CordovaWebView.java +++ b/framework/src/org/apache/cordova/CordovaWebView.java @@ -1,948 +1,945 @@ /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.cordova; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Stack; import java.util.regex.Pattern; import org.apache.cordova.Config; import org.apache.cordova.api.CordovaInterface; import org.apache.cordova.api.LOG; import org.apache.cordova.api.PluginManager; import org.apache.cordova.api.PluginResult; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.webkit.WebBackForwardList; import android.webkit.WebHistoryItem; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebSettings.LayoutAlgorithm; import android.widget.FrameLayout; public class CordovaWebView extends WebView { public static final String TAG = "CordovaWebView"; private ArrayList<Integer> keyDownCodes = new ArrayList<Integer>(); private ArrayList<Integer> keyUpCodes = new ArrayList<Integer>(); public PluginManager pluginManager; private boolean paused; private BroadcastReceiver receiver; /** Activities and other important classes **/ private CordovaInterface cordova; CordovaWebViewClient viewClient; @SuppressWarnings("unused") private CordovaChromeClient chromeClient; private String url; // Flag to track that a loadUrl timeout occurred int loadUrlTimeout = 0; private boolean bound; private boolean handleButton = false; private long lastMenuEventTime = 0; NativeToJsMessageQueue jsMessageQueue; ExposedJsApi exposedJsApi; /** custom view created by the browser (a video player for example) */ private View mCustomView; private WebChromeClient.CustomViewCallback mCustomViewCallback; private ActivityResult mResult = null; class ActivityResult { int request; int result; Intent incoming; public ActivityResult(int req, int res, Intent intent) { request = req; result = res; incoming = intent; } } static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER); /** * Constructor. * * @param context */ public CordovaWebView(Context context) { super(context); if (CordovaInterface.class.isInstance(context)) { this.cordova = (CordovaInterface) context; } else { Log.d(TAG, "Your activity must implement CordovaInterface to work"); } this.loadConfiguration(); this.setup(); } /** * Constructor. * * @param context * @param attrs */ public CordovaWebView(Context context, AttributeSet attrs) { super(context, attrs); if (CordovaInterface.class.isInstance(context)) { this.cordova = (CordovaInterface) context; } else { Log.d(TAG, "Your activity must implement CordovaInterface to work"); } this.setWebChromeClient(new CordovaChromeClient(this.cordova, this)); this.initWebViewClient(this.cordova); this.loadConfiguration(); this.setup(); } /** * Constructor. * * @param context * @param attrs * @param defStyle * */ public CordovaWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); if (CordovaInterface.class.isInstance(context)) { this.cordova = (CordovaInterface) context; } else { Log.d(TAG, "Your activity must implement CordovaInterface to work"); } this.setWebChromeClient(new CordovaChromeClient(this.cordova, this)); this.loadConfiguration(); this.setup(); } /** * Constructor. * * @param context * @param attrs * @param defStyle * @param privateBrowsing */ @TargetApi(11) public CordovaWebView(Context context, AttributeSet attrs, int defStyle, boolean privateBrowsing) { super(context, attrs, defStyle, privateBrowsing); if (CordovaInterface.class.isInstance(context)) { this.cordova = (CordovaInterface) context; } else { Log.d(TAG, "Your activity must implement CordovaInterface to work"); } this.setWebChromeClient(new CordovaChromeClient(this.cordova)); this.initWebViewClient(this.cordova); this.loadConfiguration(); this.setup(); } private void initWebViewClient(CordovaInterface cordova) { if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB || android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { this.setWebViewClient(new CordovaWebViewClient(this.cordova, this)); } else { this.setWebViewClient(new IceCreamCordovaWebViewClient(this.cordova, this)); } } /** * Initialize webview. */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void setup() { this.setInitialScale(0); this.setVerticalScrollBarEnabled(false); this.requestFocusFromTouch(); // Enable JavaScript WebSettings settings = this.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); // Set the nav dump for HTC 2.x devices (disabling for ICS, deprecated entirely for Jellybean 4.2) try { Method gingerbread_getMethod = WebSettings.class.getMethod("setNavDump", new Class[] { boolean.class }); String manufacturer = android.os.Build.MANUFACTURER; Log.d(TAG, "CordovaWebView is running on device made by: " + manufacturer); if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB && android.os.Build.MANUFACTURER.contains("HTC")) { gingerbread_getMethod.invoke(settings, true); } } catch (NoSuchMethodException e) { Log.d(TAG, "We are on a modern version of Android, we will deprecate HTC 2.3 devices in 2.8"); } catch (IllegalArgumentException e) { Log.d(TAG, "Doing the NavDump failed with bad arguments"); } catch (IllegalAccessException e) { Log.d(TAG, "This should never happen: IllegalAccessException means this isn't Android anymore"); } catch (InvocationTargetException e) { Log.d(TAG, "This should never happen: InvocationTargetException means this isn't Android anymore."); } //We don't save any form data in the application settings.setSaveFormData(false); settings.setSavePassword(false); // Jellybean rightfully tried to lock this down. Too bad they didn't give us a whitelist // while we do this if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) Level16Apis.enableUniversalAccess(settings); // Enable database // We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16 String databasePath = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); - if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) - { - settings.setDatabaseEnabled(true); - settings.setDatabasePath(databasePath); - } + settings.setDatabaseEnabled(true); + settings.setDatabasePath(databasePath); settings.setGeolocationDatabasePath(databasePath); // Enable DOM storage settings.setDomStorageEnabled(true); // Enable built-in geolocation settings.setGeolocationEnabled(true); // Enable AppCache // Fix for CB-2282 settings.setAppCacheMaxSize(5 * 1048576); String pathToCache = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setAppCachePath(pathToCache); settings.setAppCacheEnabled(true); // Fix for CB-1405 // Google issue 4641 this.updateUserAgentString(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED); if (this.receiver == null) { this.receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateUserAgentString(); } }; this.cordova.getActivity().registerReceiver(this.receiver, intentFilter); } // end CB-1405 pluginManager = new PluginManager(this, this.cordova); jsMessageQueue = new NativeToJsMessageQueue(this, cordova); exposedJsApi = new ExposedJsApi(pluginManager, jsMessageQueue); exposeJsInterface(); } private void updateUserAgentString() { this.getSettings().getUserAgentString(); } private void exposeJsInterface() { int SDK_INT = Build.VERSION.SDK_INT; boolean isHoneycomb = (SDK_INT >= Build.VERSION_CODES.HONEYCOMB && SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR2); if (isHoneycomb || (SDK_INT < Build.VERSION_CODES.GINGERBREAD)) { Log.i(TAG, "Disabled addJavascriptInterface() bridge since Android version is old."); // Bug being that Java Strings do not get converted to JS strings automatically. // This isn't hard to work-around on the JS side, but it's easier to just // use the prompt bridge instead. return; } else if (SDK_INT < Build.VERSION_CODES.HONEYCOMB && Build.MANUFACTURER.equals("unknown")) { // addJavascriptInterface crashes on the 2.3 emulator. Log.i(TAG, "Disabled addJavascriptInterface() bridge callback due to a bug on the 2.3 emulator"); return; } this.addJavascriptInterface(exposedJsApi, "_cordovaNative"); } /** * Set the WebViewClient. * * @param client */ public void setWebViewClient(CordovaWebViewClient client) { this.viewClient = client; super.setWebViewClient(client); } /** * Set the WebChromeClient. * * @param client */ public void setWebChromeClient(CordovaChromeClient client) { this.chromeClient = client; super.setWebChromeClient(client); } public CordovaChromeClient getWebChromeClient() { return this.chromeClient; } /** * Load the url into the webview. * * @param url */ @Override public void loadUrl(String url) { if (url.equals("about:blank") || url.startsWith("javascript:")) { this.loadUrlNow(url); } else { String initUrl = this.getProperty("url", null); // If first page of app, then set URL to load to be the one passed in if (initUrl == null) { this.loadUrlIntoView(url); } // Otherwise use the URL specified in the activity's extras bundle else { this.loadUrlIntoView(initUrl); } } } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ public void loadUrl(final String url, int time) { String initUrl = this.getProperty("url", null); // If first page of app, then set URL to load to be the one passed in if (initUrl == null) { this.loadUrlIntoView(url, time); } // Otherwise use the URL specified in the activity's extras bundle else { this.loadUrlIntoView(initUrl); } } /** * Load the url into the webview. * * @param url */ public void loadUrlIntoView(final String url) { LOG.d(TAG, ">>> loadUrl(" + url + ")"); this.url = url; this.pluginManager.init(); // Create a timeout timer for loadUrl final CordovaWebView me = this; final int currentLoadUrlTimeout = me.loadUrlTimeout; final int loadUrlTimeoutValue = Integer.parseInt(this.getProperty("loadUrlTimeoutValue", "20000")); // Timeout error method final Runnable loadError = new Runnable() { public void run() { me.stopLoading(); LOG.e(TAG, "CordovaWebView: TIMEOUT ERROR!"); if (viewClient != null) { viewClient.onReceivedError(me, -6, "The connection to the server was unsuccessful.", url); } } }; // Timeout timer method final Runnable timeoutCheck = new Runnable() { public void run() { try { synchronized (this) { wait(loadUrlTimeoutValue); } } catch (InterruptedException e) { e.printStackTrace(); } // If timeout, then stop loading and handle error if (me.loadUrlTimeout == currentLoadUrlTimeout) { me.cordova.getActivity().runOnUiThread(loadError); } } }; // Load url this.cordova.getActivity().runOnUiThread(new Runnable() { public void run() { Thread thread = new Thread(timeoutCheck); thread.start(); me.loadUrlNow(url); } }); } /** * Load URL in webview. * * @param url */ void loadUrlNow(String url) { if (LOG.isLoggable(LOG.DEBUG) && !url.startsWith("javascript:")) { LOG.d(TAG, ">>> loadUrlNow()"); } if (url.startsWith("file://") || url.startsWith("javascript:") || Config.isUrlWhiteListed(url)) { super.loadUrl(url); } } /** * Load the url into the webview after waiting for period of time. * This is used to display the splashscreen for certain amount of time. * * @param url * @param time The number of ms to wait before loading webview */ public void loadUrlIntoView(final String url, final int time) { // If not first page of app, then load immediately // Add support for browser history if we use it. if ((url.startsWith("javascript:")) || this.canGoBack()) { } // If first page, then show splashscreen else { LOG.d(TAG, "DroidGap.loadUrl(%s, %d)", url, time); // Send message to show splashscreen now if desired this.postMessage("splashscreen", "show"); } // Load url this.loadUrlIntoView(url); } /** * Send JavaScript statement back to JavaScript. * (This is a convenience method) * * @param message */ public void sendJavascript(String statement) { this.jsMessageQueue.addJavaScript(statement); } /** * Send a plugin result back to JavaScript. * (This is a convenience method) * * @param message */ public void sendPluginResult(PluginResult result, String callbackId) { this.jsMessageQueue.addPluginResult(result, callbackId); } /** * Send a message to all plugins. * * @param id The message id * @param data The message data */ public void postMessage(String id, Object data) { if (this.pluginManager != null) { this.pluginManager.postMessage(id, data); } } /** * Go to previous page in history. (We manage our own history) * * @return true if we went back, false if we are already at top */ public boolean backHistory() { // Check webview first to see if there is a history // This is needed to support curPage#diffLink, since they are added to appView's history, but not our history url array (JQMobile behavior) if (super.canGoBack()) { printBackForwardList(); super.goBack(); return true; } return false; } /** * Load the specified URL in the Cordova webview or a new browser instance. * * NOTE: If openExternal is false, only URLs listed in whitelist can be loaded. * * @param url The url to load. * @param openExternal Load url in browser instead of Cordova webview. * @param clearHistory Clear the history stack, so new page becomes top of history * @param params DroidGap parameters for new app */ public void showWebPage(String url, boolean openExternal, boolean clearHistory, HashMap<String, Object> params) { LOG.d(TAG, "showWebPage(%s, %b, %b, HashMap", url, openExternal, clearHistory); // If clearing history if (clearHistory) { this.clearHistory(); } // If loading into our webview if (!openExternal) { // Make sure url is in whitelist if (url.startsWith("file://") || Config.isUrlWhiteListed(url)) { // TODO: What about params? // Load new URL this.loadUrl(url); } // Load in default viewer if not else { LOG.w(TAG, "showWebPage: Cannot load URL into webview since it is not in white list. Loading into browser instead. (URL=" + url + ")"); try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url " + url, e); } } } // Load in default view intent else { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); cordova.getActivity().startActivity(intent); } catch (android.content.ActivityNotFoundException e) { LOG.e(TAG, "Error loading url " + url, e); } } } /** * Check configuration parameters from Config. * Approved list of URLs that can be loaded into DroidGap * <access origin="http://server regexp" subdomains="true" /> * Log level: ERROR, WARN, INFO, DEBUG, VERBOSE (default=ERROR) * <log level="DEBUG" /> */ private void loadConfiguration() { if ("true".equals(this.getProperty("fullscreen", "false"))) { this.cordova.getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); this.cordova.getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } } /** * Get string property for activity. * * @param name * @param defaultValue * @return */ public String getProperty(String name, String defaultValue) { Bundle bundle = this.cordova.getActivity().getIntent().getExtras(); if (bundle == null) { return defaultValue; } Object p = bundle.get(name); if (p == null) { return defaultValue; } return p.toString(); } /* * onKeyDown */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyDownCodes.contains(keyCode)) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { // only override default behavior is event bound LOG.d(TAG, "Down Key Hit"); this.loadUrl("javascript:cordova.fireDocumentEvent('volumedownbutton');"); return true; } // If volumeup key else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { LOG.d(TAG, "Up Key Hit"); this.loadUrl("javascript:cordova.fireDocumentEvent('volumeupbutton');"); return true; } else { return super.onKeyDown(keyCode, event); } } else if(keyCode == KeyEvent.KEYCODE_BACK) { return !(this.startOfHistory()) || this.bound; } else if(keyCode == KeyEvent.KEYCODE_MENU) { //How did we get here? Is there a childView? View childView = this.getFocusedChild(); if(childView != null) { //Make sure we close the keyboard if it's present InputMethodManager imm = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(childView.getWindowToken(), 0); cordova.getActivity().openOptionsMenu(); } return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { // If back key if (keyCode == KeyEvent.KEYCODE_BACK) { // A custom view is currently displayed (e.g. playing a video) if(mCustomView != null) { this.hideCustomView(); } else { // The webview is currently displayed // If back key is bound, then send event to JavaScript if (this.bound) { this.loadUrl("javascript:cordova.fireDocumentEvent('backbutton');"); return true; } else { // If not bound // Go to previous page in webview if it is possible to go back if (this.backHistory()) { return true; } // If not, then invoke default behaviour else { //this.activityState = ACTIVITY_EXITING; //return false; // If they hit back button when app is initializing, app should exit instead of hang until initilazation (CB2-458) this.cordova.getActivity().finish(); } } } } // Legacy else if (keyCode == KeyEvent.KEYCODE_MENU) { if (this.lastMenuEventTime < event.getEventTime()) { this.loadUrl("javascript:cordova.fireDocumentEvent('menubutton');"); } this.lastMenuEventTime = event.getEventTime(); return super.onKeyUp(keyCode, event); } // If search key else if (keyCode == KeyEvent.KEYCODE_SEARCH) { this.loadUrl("javascript:cordova.fireDocumentEvent('searchbutton');"); return true; } else if(keyUpCodes.contains(keyCode)) { //What the hell should this do? return super.onKeyUp(keyCode, event); } //Does webkit change this behavior? return super.onKeyUp(keyCode, event); } public void bindButton(boolean override) { this.bound = override; } public void bindButton(String button, boolean override) { // TODO Auto-generated method stub if (button.compareTo("volumeup")==0) { keyDownCodes.add(KeyEvent.KEYCODE_VOLUME_UP); } else if (button.compareTo("volumedown")==0) { keyDownCodes.add(KeyEvent.KEYCODE_VOLUME_DOWN); } } public void bindButton(int keyCode, boolean keyDown, boolean override) { if(keyDown) { keyDownCodes.add(keyCode); } else { keyUpCodes.add(keyCode); } } public boolean isBackButtonBound() { return this.bound; } public void handlePause(boolean keepRunning) { LOG.d(TAG, "Handle the pause"); // Send pause event to JavaScript this.loadUrl("javascript:try{cordova.fireDocumentEvent('pause');}catch(e){console.log('exception firing pause event from native');};"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onPause(keepRunning); } // If app doesn't want to run in background if (!keepRunning) { // Pause JavaScript timers (including setInterval) this.pauseTimers(); } paused = true; } public void handleResume(boolean keepRunning, boolean activityResultKeepRunning) { this.loadUrl("javascript:try{cordova.fireDocumentEvent('resume');}catch(e){console.log('exception firing resume event from native');};"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onResume(keepRunning); } // Resume JavaScript timers (including setInterval) this.resumeTimers(); paused = false; } public void handleDestroy() { // Send destroy event to JavaScript // Since baseUrl is set in loadUrlIntoView, if user hit Back button before loadUrl was called, we'll get an NPE on baseUrl (CB-2458) this.loadUrlIntoView("javascript:try{cordova.require('cordova/channel').onDestroy.fire();}catch(e){console.log('exception firing destroy event from native');};"); // Load blank page so that JavaScript onunload is called this.loadUrl("about:blank"); // Forward to plugins if (this.pluginManager != null) { this.pluginManager.onDestroy(); } // unregister the receiver if (this.receiver != null) { try { this.cordova.getActivity().unregisterReceiver(this.receiver); } catch (Exception e) { Log.e(TAG, "Error unregistering configuration receiver: " + e.getMessage(), e); } } } public void onNewIntent(Intent intent) { //Forward to plugins if (this.pluginManager != null) { this.pluginManager.onNewIntent(intent); } } public boolean isPaused() { return paused; } public boolean hadKeyEvent() { return handleButton; } // Wrapping these functions in their own class prevents warnings in adb like: // VFY: unable to resolve virtual method 285: Landroid/webkit/WebSettings;.setAllowUniversalAccessFromFileURLs @TargetApi(16) private static class Level16Apis { static void enableUniversalAccess(WebSettings settings) { settings.setAllowUniversalAccessFromFileURLs(true); } } public void printBackForwardList() { WebBackForwardList currentList = this.copyBackForwardList(); int currentSize = currentList.getSize(); for(int i = 0; i < currentSize; ++i) { WebHistoryItem item = currentList.getItemAtIndex(i); String url = item.getUrl(); LOG.d(TAG, "The URL at index: " + Integer.toString(i) + "is " + url ); } } //Can Go Back is BROKEN! public boolean startOfHistory() { WebBackForwardList currentList = this.copyBackForwardList(); WebHistoryItem item = currentList.getItemAtIndex(0); if( item!=null){ // Null-fence in case they haven't called loadUrl yet (CB-2458) String url = item.getUrl(); String currentUrl = this.getUrl(); LOG.d(TAG, "The current URL is: " + currentUrl); LOG.d(TAG, "The URL at item 0 is:" + url); return currentUrl.equals(url); } return false; } public void showCustomView(View view, WebChromeClient.CustomViewCallback callback) { // This code is adapted from the original Android Browser code, licensed under the Apache License, Version 2.0 Log.d(TAG, "showing Custom View"); // if a view already exists then immediately terminate the new one if (mCustomView != null) { callback.onCustomViewHidden(); return; } // Store the view and its callback for later (to kill it properly) mCustomView = view; mCustomViewCallback = callback; // Add the custom view to its container. ViewGroup parent = (ViewGroup) this.getParent(); parent.addView(view, COVER_SCREEN_GRAVITY_CENTER); // Hide the content view. this.setVisibility(View.GONE); // Finally show the custom view container. parent.setVisibility(View.VISIBLE); parent.bringToFront(); } public void hideCustomView() { // This code is adapted from the original Android Browser code, licensed under the Apache License, Version 2.0 Log.d(TAG, "Hidding Custom View"); if (mCustomView == null) return; // Hide the custom view. mCustomView.setVisibility(View.GONE); // Remove the custom view from its container. ViewGroup parent = (ViewGroup) this.getParent(); parent.removeView(mCustomView); mCustomView = null; mCustomViewCallback.onCustomViewHidden(); // Show the content view. this.setVisibility(View.VISIBLE); } /** * if the video overlay is showing then we need to know * as it effects back button handling * * @return */ public boolean isCustomViewShowing() { return mCustomView != null; } public WebBackForwardList restoreState(Bundle savedInstanceState) { WebBackForwardList myList = super.restoreState(savedInstanceState); Log.d(TAG, "WebView restoration crew now restoring!"); //Initialize the plugin manager once more this.pluginManager.init(); return myList; } public void storeResult(int requestCode, int resultCode, Intent intent) { mResult = new ActivityResult(requestCode, resultCode, intent); } }
true
true
private void setup() { this.setInitialScale(0); this.setVerticalScrollBarEnabled(false); this.requestFocusFromTouch(); // Enable JavaScript WebSettings settings = this.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); // Set the nav dump for HTC 2.x devices (disabling for ICS, deprecated entirely for Jellybean 4.2) try { Method gingerbread_getMethod = WebSettings.class.getMethod("setNavDump", new Class[] { boolean.class }); String manufacturer = android.os.Build.MANUFACTURER; Log.d(TAG, "CordovaWebView is running on device made by: " + manufacturer); if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB && android.os.Build.MANUFACTURER.contains("HTC")) { gingerbread_getMethod.invoke(settings, true); } } catch (NoSuchMethodException e) { Log.d(TAG, "We are on a modern version of Android, we will deprecate HTC 2.3 devices in 2.8"); } catch (IllegalArgumentException e) { Log.d(TAG, "Doing the NavDump failed with bad arguments"); } catch (IllegalAccessException e) { Log.d(TAG, "This should never happen: IllegalAccessException means this isn't Android anymore"); } catch (InvocationTargetException e) { Log.d(TAG, "This should never happen: InvocationTargetException means this isn't Android anymore."); } //We don't save any form data in the application settings.setSaveFormData(false); settings.setSavePassword(false); // Jellybean rightfully tried to lock this down. Too bad they didn't give us a whitelist // while we do this if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) Level16Apis.enableUniversalAccess(settings); // Enable database // We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16 String databasePath = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { settings.setDatabaseEnabled(true); settings.setDatabasePath(databasePath); } settings.setGeolocationDatabasePath(databasePath); // Enable DOM storage settings.setDomStorageEnabled(true); // Enable built-in geolocation settings.setGeolocationEnabled(true); // Enable AppCache // Fix for CB-2282 settings.setAppCacheMaxSize(5 * 1048576); String pathToCache = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setAppCachePath(pathToCache); settings.setAppCacheEnabled(true); // Fix for CB-1405 // Google issue 4641 this.updateUserAgentString(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED); if (this.receiver == null) { this.receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateUserAgentString(); } }; this.cordova.getActivity().registerReceiver(this.receiver, intentFilter); } // end CB-1405 pluginManager = new PluginManager(this, this.cordova); jsMessageQueue = new NativeToJsMessageQueue(this, cordova); exposedJsApi = new ExposedJsApi(pluginManager, jsMessageQueue); exposeJsInterface(); }
private void setup() { this.setInitialScale(0); this.setVerticalScrollBarEnabled(false); this.requestFocusFromTouch(); // Enable JavaScript WebSettings settings = this.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); // Set the nav dump for HTC 2.x devices (disabling for ICS, deprecated entirely for Jellybean 4.2) try { Method gingerbread_getMethod = WebSettings.class.getMethod("setNavDump", new Class[] { boolean.class }); String manufacturer = android.os.Build.MANUFACTURER; Log.d(TAG, "CordovaWebView is running on device made by: " + manufacturer); if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB && android.os.Build.MANUFACTURER.contains("HTC")) { gingerbread_getMethod.invoke(settings, true); } } catch (NoSuchMethodException e) { Log.d(TAG, "We are on a modern version of Android, we will deprecate HTC 2.3 devices in 2.8"); } catch (IllegalArgumentException e) { Log.d(TAG, "Doing the NavDump failed with bad arguments"); } catch (IllegalAccessException e) { Log.d(TAG, "This should never happen: IllegalAccessException means this isn't Android anymore"); } catch (InvocationTargetException e) { Log.d(TAG, "This should never happen: InvocationTargetException means this isn't Android anymore."); } //We don't save any form data in the application settings.setSaveFormData(false); settings.setSavePassword(false); // Jellybean rightfully tried to lock this down. Too bad they didn't give us a whitelist // while we do this if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) Level16Apis.enableUniversalAccess(settings); // Enable database // We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16 String databasePath = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setDatabaseEnabled(true); settings.setDatabasePath(databasePath); settings.setGeolocationDatabasePath(databasePath); // Enable DOM storage settings.setDomStorageEnabled(true); // Enable built-in geolocation settings.setGeolocationEnabled(true); // Enable AppCache // Fix for CB-2282 settings.setAppCacheMaxSize(5 * 1048576); String pathToCache = this.cordova.getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); settings.setAppCachePath(pathToCache); settings.setAppCacheEnabled(true); // Fix for CB-1405 // Google issue 4641 this.updateUserAgentString(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED); if (this.receiver == null) { this.receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateUserAgentString(); } }; this.cordova.getActivity().registerReceiver(this.receiver, intentFilter); } // end CB-1405 pluginManager = new PluginManager(this, this.cordova); jsMessageQueue = new NativeToJsMessageQueue(this, cordova); exposedJsApi = new ExposedJsApi(pluginManager, jsMessageQueue); exposeJsInterface(); }
diff --git a/ThermoDataEstimator.java b/ThermoDataEstimator.java index 012031da..7fcde4a4 100644 --- a/ThermoDataEstimator.java +++ b/ThermoDataEstimator.java @@ -1,130 +1,145 @@ //////////////////////////////////////////////////////////////////////////////// // // RMG - Reaction Mechanism Generator // // Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the // RMG Team ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //////////////////////////////////////////////////////////////////////////////// import java.util.*; import java.io.*; import jing.chem.*; import jing.chemParser.*; import jing.param.*; import jing.chemUtil.*; //import bondGroups.*; import jing.rxn.*; import jing.rxnSys.*; import jing.mathTool.*; public class ThermoDataEstimator {//gmagoon 7/24/09: based off of Thermo.java rev. 1.6; this performs original functionality described in the manual //## configuration RMG::RMG //first argument will be file to read public static void main(String[] args) { initializeSystemProperties(); try { FileReader in = new FileReader(args[0]); BufferedReader data = new BufferedReader(in); Graph g = ChemParser.readChemGraph(data); in.close(); System.out.println(g); ChemGraph chemgraph = ChemGraph.make(g); Species spe = Species.make("molecule",chemgraph); + /* + * Following line added by MRH on 10Aug2009: + * After the species is made, the chemgraph is not necessarily the same + * (e.g. the species contains resonance isomers, and the adjacency list + * supplied by the user is not the most stable isomer). This was causing + * a discrepancy to be displayed to the screen: the "H=" value we were + * displaying corresponded to the chemgraph supplied by the user; the + * ThermData corresponded to the most stable isomer. + * + * An example of a troublesome chemgraph: + * 1 C 0 {2,T} + * 2 C 0 {1,T} {3,S} + * 3 O 0 {2,S} + */ + chemgraph = spe.getChemGraph(); System.out.println("The number of resonance isomers is " + spe.getResonanceIsomersHashSet().size()); System.out.println("The NASA data is \n"+ spe.getNasaThermoData()); - System.out.println("ThermoData is \n" + spe.getChemGraph().getThermoData().toString()); + System.out.println("ThermoData is \n" + chemgraph.getThermoData().toString()); //int K = chemgraph.getKekule(); int symm = chemgraph.getSymmetryNumber(); //System.out.println("number of Kekule structures = "+K); System.out.println(" symmetry number = "+symm); Temperature T = new Temperature(298.0,"K"); String chemicalFormula = chemgraph.getChemicalFormula(); System.out.println(chemicalFormula + " H=" + chemgraph.calculateH(T)); // Species species = Species.make(chemicalFormula, chemgraph); // this is equal to System.out.println(species.toString()); // System.out.println(species.toStringWithoutH()); // species.generateResonanceIsomers(); // Iterator rs = species.getResonanceIsomers(); // while (rs.hasNext()){ // ChemGraph cg = (ChemGraph)rs.next(); // Species s = cg.getSpecies(); // String string = s.toStringWithoutH(); // System.out.print(string); // } // Species species = Species.make(chemicalFormula, chemgraph); // Iterator iterator = species.getResonanceIsomers(); // System.out.println(iterator); } catch (FileNotFoundException e) { System.err.println("File was not found!\n"); } catch(IOException e){ System.err.println("Something wrong with ChemParser.readChemGraph"); } catch(ForbiddenStructureException e){ System.err.println("Something wrong with ChemGraph.make"); } System.out.println("Done!\n"); }; public static void initializeSystemProperties() { String name= "RMG_database"; String workingDir = System.getenv("RMG"); System.setProperty("RMG.workingDirectory", workingDir); // System.setProperty("jing.chem.ChemGraph.forbiddenStructureFile", // workingDir + // "database/forbiddenStructure/forbiddenStructure.txt"); System.setProperty("jing.chem.ChemGraph.forbiddenStructureFile", workingDir + "/databases/"+name+"/forbiddenStructure/ForbiddenStructure.txt"); System.setProperty("jing.chem.ThermoGAGroupLibrary.pathName", workingDir + "/databases/" + name+"/thermo"); System.setProperty("jing.rxn.ReactionTemplateLibrary.pathName", workingDir + "/databases/" + name+"/kinetics/kinetics"); // System.setProperty("jing.rxn.ReactionTemplateLibrary.pathName", // workingDir + "database/kinetics/kinetics"); // System.setProperty("jing.rxnSys.ReactionModelGenerator.conditionFile", // workingDir + "database/condition/condition.txt"); }; }
false
true
public static void main(String[] args) { initializeSystemProperties(); try { FileReader in = new FileReader(args[0]); BufferedReader data = new BufferedReader(in); Graph g = ChemParser.readChemGraph(data); in.close(); System.out.println(g); ChemGraph chemgraph = ChemGraph.make(g); Species spe = Species.make("molecule",chemgraph); System.out.println("The number of resonance isomers is " + spe.getResonanceIsomersHashSet().size()); System.out.println("The NASA data is \n"+ spe.getNasaThermoData()); System.out.println("ThermoData is \n" + spe.getChemGraph().getThermoData().toString()); //int K = chemgraph.getKekule(); int symm = chemgraph.getSymmetryNumber(); //System.out.println("number of Kekule structures = "+K); System.out.println(" symmetry number = "+symm); Temperature T = new Temperature(298.0,"K"); String chemicalFormula = chemgraph.getChemicalFormula(); System.out.println(chemicalFormula + " H=" + chemgraph.calculateH(T)); // Species species = Species.make(chemicalFormula, chemgraph); // this is equal to System.out.println(species.toString()); // System.out.println(species.toStringWithoutH()); // species.generateResonanceIsomers(); // Iterator rs = species.getResonanceIsomers(); // while (rs.hasNext()){ // ChemGraph cg = (ChemGraph)rs.next(); // Species s = cg.getSpecies(); // String string = s.toStringWithoutH(); // System.out.print(string); // } // Species species = Species.make(chemicalFormula, chemgraph); // Iterator iterator = species.getResonanceIsomers(); // System.out.println(iterator); } catch (FileNotFoundException e) { System.err.println("File was not found!\n"); } catch(IOException e){ System.err.println("Something wrong with ChemParser.readChemGraph"); } catch(ForbiddenStructureException e){ System.err.println("Something wrong with ChemGraph.make"); } System.out.println("Done!\n"); };
public static void main(String[] args) { initializeSystemProperties(); try { FileReader in = new FileReader(args[0]); BufferedReader data = new BufferedReader(in); Graph g = ChemParser.readChemGraph(data); in.close(); System.out.println(g); ChemGraph chemgraph = ChemGraph.make(g); Species spe = Species.make("molecule",chemgraph); /* * Following line added by MRH on 10Aug2009: * After the species is made, the chemgraph is not necessarily the same * (e.g. the species contains resonance isomers, and the adjacency list * supplied by the user is not the most stable isomer). This was causing * a discrepancy to be displayed to the screen: the "H=" value we were * displaying corresponded to the chemgraph supplied by the user; the * ThermData corresponded to the most stable isomer. * * An example of a troublesome chemgraph: * 1 C 0 {2,T} * 2 C 0 {1,T} {3,S} * 3 O 0 {2,S} */ chemgraph = spe.getChemGraph(); System.out.println("The number of resonance isomers is " + spe.getResonanceIsomersHashSet().size()); System.out.println("The NASA data is \n"+ spe.getNasaThermoData()); System.out.println("ThermoData is \n" + chemgraph.getThermoData().toString()); //int K = chemgraph.getKekule(); int symm = chemgraph.getSymmetryNumber(); //System.out.println("number of Kekule structures = "+K); System.out.println(" symmetry number = "+symm); Temperature T = new Temperature(298.0,"K"); String chemicalFormula = chemgraph.getChemicalFormula(); System.out.println(chemicalFormula + " H=" + chemgraph.calculateH(T)); // Species species = Species.make(chemicalFormula, chemgraph); // this is equal to System.out.println(species.toString()); // System.out.println(species.toStringWithoutH()); // species.generateResonanceIsomers(); // Iterator rs = species.getResonanceIsomers(); // while (rs.hasNext()){ // ChemGraph cg = (ChemGraph)rs.next(); // Species s = cg.getSpecies(); // String string = s.toStringWithoutH(); // System.out.print(string); // } // Species species = Species.make(chemicalFormula, chemgraph); // Iterator iterator = species.getResonanceIsomers(); // System.out.println(iterator); } catch (FileNotFoundException e) { System.err.println("File was not found!\n"); } catch(IOException e){ System.err.println("Something wrong with ChemParser.readChemGraph"); } catch(ForbiddenStructureException e){ System.err.println("Something wrong with ChemGraph.make"); } System.out.println("Done!\n"); };
diff --git a/src/main/java/org/jboss/pressgang/ccms/server/rest/v1/mapper/BaseExceptionMapper.java b/src/main/java/org/jboss/pressgang/ccms/server/rest/v1/mapper/BaseExceptionMapper.java index 690df71..34cd92f 100644 --- a/src/main/java/org/jboss/pressgang/ccms/server/rest/v1/mapper/BaseExceptionMapper.java +++ b/src/main/java/org/jboss/pressgang/ccms/server/rest/v1/mapper/BaseExceptionMapper.java @@ -1,35 +1,36 @@ package org.jboss.pressgang.ccms.server.rest.v1.mapper; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import java.lang.reflect.Method; import org.jboss.pressgang.ccms.rest.v1.constants.RESTv1Constants; import org.jboss.pressgang.ccms.rest.v1.jaxrsinterfaces.RESTInterfaceV1; import org.jboss.pressgang.ccms.server.rest.v1.RESTv1; import org.jboss.pressgang.ccms.server.utils.Constants; import org.jboss.pressgang.ccms.utils.common.VersionUtilities; import org.jboss.resteasy.spi.interception.AcceptedByMethod; public abstract class BaseExceptionMapper<T extends Throwable> implements ExceptionMapper<T>, AcceptedByMethod { protected Response buildPlainTextResponse(final Response.Status status, final T exception) { return buildPlainTextResponse(status.getStatusCode(), exception); } protected Response buildPlainTextResponse(final int status, final T exception) { return javax.ws.rs.core.Response.status(status) .entity(exception.getMessage() + "\n") .header("Content-Type", MediaType.TEXT_PLAIN) .header(RESTv1Constants.X_PRESSGANG_VERSION_HEADER, VersionUtilities.getAPIVersion(RESTInterfaceV1.class)) .header(RESTv1Constants.ACCESS_CONTROL_EXPOSE_HEADERS, RESTv1Constants.X_PRESSGANG_VERSION_HEADER) + .header(RESTv1Constants.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*") .build(); } @Override public boolean accept(Class declaring, Method method) { // Only use this interceptor for v1 endpoints. return RESTv1.class.equals(declaring); } }
true
true
protected Response buildPlainTextResponse(final int status, final T exception) { return javax.ws.rs.core.Response.status(status) .entity(exception.getMessage() + "\n") .header("Content-Type", MediaType.TEXT_PLAIN) .header(RESTv1Constants.X_PRESSGANG_VERSION_HEADER, VersionUtilities.getAPIVersion(RESTInterfaceV1.class)) .header(RESTv1Constants.ACCESS_CONTROL_EXPOSE_HEADERS, RESTv1Constants.X_PRESSGANG_VERSION_HEADER) .build(); }
protected Response buildPlainTextResponse(final int status, final T exception) { return javax.ws.rs.core.Response.status(status) .entity(exception.getMessage() + "\n") .header("Content-Type", MediaType.TEXT_PLAIN) .header(RESTv1Constants.X_PRESSGANG_VERSION_HEADER, VersionUtilities.getAPIVersion(RESTInterfaceV1.class)) .header(RESTv1Constants.ACCESS_CONTROL_EXPOSE_HEADERS, RESTv1Constants.X_PRESSGANG_VERSION_HEADER) .header(RESTv1Constants.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*") .build(); }
diff --git a/src/main/java/org/guanxi/idp/farm/attributors/SimpleAttributor.java b/src/main/java/org/guanxi/idp/farm/attributors/SimpleAttributor.java index 9d60fa9..c6b6cd3 100644 --- a/src/main/java/org/guanxi/idp/farm/attributors/SimpleAttributor.java +++ b/src/main/java/org/guanxi/idp/farm/attributors/SimpleAttributor.java @@ -1,137 +1,137 @@ //: "The contents of this file are subject to the Mozilla Public License //: Version 1.1 (the "License"); you may not use this file except in //: compliance with the License. You may obtain a copy of the License at //: http://www.mozilla.org/MPL/ //: //: Software distributed under the License is distributed on an "AS IS" //: basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the //: License for the specific language governing rights and limitations //: under the License. //: //: The Original Code is Guanxi (http://www.guanxi.uhi.ac.uk). //: //: The Initial Developer of the Original Code is Alistair Young [email protected] //: All Rights Reserved. //: package org.guanxi.idp.farm.attributors; import org.apache.log4j.Logger; import org.guanxi.idp.util.ARPEngine; import org.guanxi.idp.util.AttributeMap; import org.guanxi.idp.util.GuanxiAttribute; import org.guanxi.xal.idp.AttributorAttribute; import org.guanxi.xal.idp.UserAttributesDocument; import org.guanxi.common.GuanxiPrincipal; import org.springframework.web.context.ServletContextAware; import javax.servlet.ServletContext; import java.util.HashMap; public abstract class SimpleAttributor implements Attributor, ServletContextAware { /** The ServletContext, passed to us by Spring as we are ServletContextAware */ ServletContext servletContext = null; /** Our logger */ protected Logger logger = null; /** The path/name of our own config file */ protected String attributorConfig = null; /** Current status */ protected String errorMessage = null; /** * Passes an attribute name and value through the ARP engine. If the name/value can be * released, they will be added to the attributes document. * * @param arpEngine the ARP engine to use * @param relyingParty the entityID of the entity looking for attributes * @param attributeName the name of the attribute * @param attributeValue the value of the attribute * @param attributes the attributes document that will hold the released attribute */ protected void arp(ARPEngine arpEngine, String relyingParty, String attributeName, String attributeValue, UserAttributesDocument.UserAttributes attributes) { // Can we release the original attributes without mapping? if (arpEngine.release(relyingParty, attributeName, attributeValue)) { AttributorAttribute attribute = attributes.addNewAttribute(); attribute.setName(attributeName); attribute.setValue(attributeValue); logger.debug("Released attribute " + attributeName + " to " + relyingParty); } else { logger.debug("Attribute release blocked by ARP : " + attributeName + " to " + relyingParty); } } /** * Passes an attribute name and value through the Mapper and ARP engines. If the name/value can be * released after being mapped, they will be added to the attributes document. * * @param arpEngine the ARP engine to use * @param mapper the profile specific attribute mapper to use * @param principal the GuanxiPrincipal for the user who's attributes are being requested * @param relyingParty the entityID of the entity looking for attributes * @param attributeName the name of the attribute * @param attributeValue the value of the attribute * @param attributeSet The complete set of attributes to allow cross referencing when mapping * @param attributes the attributes document that will hold the released attribute */ protected void map(ARPEngine arpEngine, AttributeMap mapper, GuanxiPrincipal principal, String relyingParty, String attributeName, String attributeValue, HashMap<String, String[]> attributeSet, UserAttributesDocument.UserAttributes attributes) { GuanxiAttribute mappedAttribute = mapper.map(principal, relyingParty, attributeName, attributeValue, attributeSet); if (mappedAttribute != null) { for (int mapCount = 0; mapCount < mappedAttribute.getNames().size(); mapCount++) { // Release the mapped attribute if appropriate if (arpEngine.release(relyingParty, mappedAttribute.getNameAtIndex(mapCount), mappedAttribute.getValueAtIndex(mapCount))) { String mappedValue = mappedAttribute.getValueAtIndex(mapCount); AttributorAttribute attribute = attributes.addNewAttribute(); attribute.setName(mappedAttribute.getNameAtIndex(mapCount)); attribute.setValue(mappedValue); - if (mappedAttribute.getFriendlyNameAtIndex(mapCount) != null) { + if (mappedAttribute.hasFriendlyNames()) { attribute.setFriendlyName(mappedAttribute.getFriendlyNameAtIndex(mapCount)); } logger.debug("Released attribute " + mappedAttribute.getNameAtIndex(mapCount) + " -> " + mappedValue + " to " + relyingParty); } else { logger.debug("Attribute release blocked by ARP : " + mappedAttribute.getNameAtIndex(mapCount) + " to " + relyingParty); } } } } /** * Initialises the subclass */ public void init() { logger = Logger.getLogger(this.getClass().getName()); // Sort out the path to the config file if there is one if (attributorConfig != null) { if ((attributorConfig.startsWith("WEB-INF")) || (attributorConfig.startsWith("/WEB-INF"))) { attributorConfig = servletContext.getRealPath(attributorConfig); } } } public String getErrorMessage() { return errorMessage; } public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } public void setAttributorConfig(String attributorConfig) { this.attributorConfig = attributorConfig; } public String getAttributorConfig() { return attributorConfig; } }
true
true
protected void map(ARPEngine arpEngine, AttributeMap mapper, GuanxiPrincipal principal, String relyingParty, String attributeName, String attributeValue, HashMap<String, String[]> attributeSet, UserAttributesDocument.UserAttributes attributes) { GuanxiAttribute mappedAttribute = mapper.map(principal, relyingParty, attributeName, attributeValue, attributeSet); if (mappedAttribute != null) { for (int mapCount = 0; mapCount < mappedAttribute.getNames().size(); mapCount++) { // Release the mapped attribute if appropriate if (arpEngine.release(relyingParty, mappedAttribute.getNameAtIndex(mapCount), mappedAttribute.getValueAtIndex(mapCount))) { String mappedValue = mappedAttribute.getValueAtIndex(mapCount); AttributorAttribute attribute = attributes.addNewAttribute(); attribute.setName(mappedAttribute.getNameAtIndex(mapCount)); attribute.setValue(mappedValue); if (mappedAttribute.getFriendlyNameAtIndex(mapCount) != null) { attribute.setFriendlyName(mappedAttribute.getFriendlyNameAtIndex(mapCount)); } logger.debug("Released attribute " + mappedAttribute.getNameAtIndex(mapCount) + " -> " + mappedValue + " to " + relyingParty); } else { logger.debug("Attribute release blocked by ARP : " + mappedAttribute.getNameAtIndex(mapCount) + " to " + relyingParty); } } } }
protected void map(ARPEngine arpEngine, AttributeMap mapper, GuanxiPrincipal principal, String relyingParty, String attributeName, String attributeValue, HashMap<String, String[]> attributeSet, UserAttributesDocument.UserAttributes attributes) { GuanxiAttribute mappedAttribute = mapper.map(principal, relyingParty, attributeName, attributeValue, attributeSet); if (mappedAttribute != null) { for (int mapCount = 0; mapCount < mappedAttribute.getNames().size(); mapCount++) { // Release the mapped attribute if appropriate if (arpEngine.release(relyingParty, mappedAttribute.getNameAtIndex(mapCount), mappedAttribute.getValueAtIndex(mapCount))) { String mappedValue = mappedAttribute.getValueAtIndex(mapCount); AttributorAttribute attribute = attributes.addNewAttribute(); attribute.setName(mappedAttribute.getNameAtIndex(mapCount)); attribute.setValue(mappedValue); if (mappedAttribute.hasFriendlyNames()) { attribute.setFriendlyName(mappedAttribute.getFriendlyNameAtIndex(mapCount)); } logger.debug("Released attribute " + mappedAttribute.getNameAtIndex(mapCount) + " -> " + mappedValue + " to " + relyingParty); } else { logger.debug("Attribute release blocked by ARP : " + mappedAttribute.getNameAtIndex(mapCount) + " to " + relyingParty); } } } }
diff --git a/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java b/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java index 8a72fb3949..4b2a6ce724 100644 --- a/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java +++ b/hazelcast/src/main/java/com/hazelcast/transaction/impl/TransactionContextImpl.java @@ -1,147 +1,153 @@ /* * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.transaction.impl; import com.hazelcast.collection.CollectionProxyId; import com.hazelcast.collection.CollectionProxyType; import com.hazelcast.collection.CollectionService; import com.hazelcast.collection.list.ObjectListProxy; import com.hazelcast.collection.set.ObjectSetProxy; import com.hazelcast.core.*; import com.hazelcast.map.MapService; import com.hazelcast.queue.QueueService; import com.hazelcast.spi.TransactionalService; import com.hazelcast.spi.impl.NodeEngineImpl; import com.hazelcast.transaction.*; import java.util.HashMap; import java.util.Map; /** * @author mdogan 2/26/13 */ final class TransactionContextImpl implements TransactionContext { private final NodeEngineImpl nodeEngine; private final TransactionImpl transaction; private final Map<TransactionalObjectKey, TransactionalObject> txnObjectMap = new HashMap<TransactionalObjectKey, TransactionalObject>(2); TransactionContextImpl(TransactionManagerServiceImpl transactionManagerService, NodeEngineImpl nodeEngine, TransactionOptions options, String ownerUuid) { this.nodeEngine = nodeEngine; this.transaction = new TransactionImpl(transactionManagerService, nodeEngine, options, ownerUuid); } public String getTxnId() { return transaction.getTxnId(); } public void beginTransaction() { transaction.begin(); } public void commitTransaction() throws TransactionException { if (transaction.getTransactionType().equals(TransactionOptions.TransactionType.TWO_PHASE)) { transaction.prepare(); } transaction.commit(); } public void rollbackTransaction() { transaction.rollback(); } @SuppressWarnings("unchecked") public <K, V> TransactionalMap<K, V> getMap(String name) { return (TransactionalMap<K, V>) getTransactionalObject(MapService.SERVICE_NAME, name); } @SuppressWarnings("unchecked") public <E> TransactionalQueue<E> getQueue(String name) { return (TransactionalQueue<E>) getTransactionalObject(QueueService.SERVICE_NAME, name); } @SuppressWarnings("unchecked") public <K, V> TransactionalMultiMap<K, V> getMultiMap(String name) { return (TransactionalMultiMap<K, V>) getTransactionalObject(CollectionService.SERVICE_NAME, new CollectionProxyId(name, null, CollectionProxyType.MULTI_MAP)); } @SuppressWarnings("unchecked") public <E> TransactionalList<E> getList(String name) { return (TransactionalList<E>) getTransactionalObject(CollectionService.SERVICE_NAME, new CollectionProxyId(ObjectListProxy.COLLECTION_LIST_NAME, name, CollectionProxyType.LIST)); } @SuppressWarnings("unchecked") public <E> TransactionalSet<E> getSet(String name) { return (TransactionalSet<E>) getTransactionalObject(CollectionService.SERVICE_NAME, new CollectionProxyId(ObjectSetProxy.COLLECTION_SET_NAME, name, CollectionProxyType.SET)); } @SuppressWarnings("unchecked") public TransactionalObject getTransactionalObject(String serviceName, Object id) { if (transaction.getState() != Transaction.State.ACTIVE) { throw new TransactionNotActiveException("No transaction is found while accessing " + "transactional object -> " + serviceName + "[" + id + "]!"); } TransactionalObjectKey key = new TransactionalObjectKey(serviceName, id); TransactionalObject obj = txnObjectMap.get(key); if (obj == null) { final Object service = nodeEngine.getService(serviceName); if (service instanceof TransactionalService) { nodeEngine.getProxyService().initializeDistributedObject(serviceName, id); obj = ((TransactionalService) service).createTransactionalObject(id, transaction); txnObjectMap.put(key, obj); } else { + if (service == null) { + if (!nodeEngine.isActive()) { + throw new HazelcastInstanceNotActiveException(); + } + throw new IllegalArgumentException("Unknown Service[" + serviceName + "]!"); + } throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!"); } } return obj; } Transaction getTransaction() { return transaction; } private class TransactionalObjectKey { private final String serviceName; private final Object id; TransactionalObjectKey(String serviceName, Object id) { this.serviceName = serviceName; this.id = id; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TransactionalObjectKey)) return false; TransactionalObjectKey that = (TransactionalObjectKey) o; if (!id.equals(that.id)) return false; if (!serviceName.equals(that.serviceName)) return false; return true; } public int hashCode() { int result = serviceName.hashCode(); result = 31 * result + id.hashCode(); return result; } } }
true
true
public TransactionalObject getTransactionalObject(String serviceName, Object id) { if (transaction.getState() != Transaction.State.ACTIVE) { throw new TransactionNotActiveException("No transaction is found while accessing " + "transactional object -> " + serviceName + "[" + id + "]!"); } TransactionalObjectKey key = new TransactionalObjectKey(serviceName, id); TransactionalObject obj = txnObjectMap.get(key); if (obj == null) { final Object service = nodeEngine.getService(serviceName); if (service instanceof TransactionalService) { nodeEngine.getProxyService().initializeDistributedObject(serviceName, id); obj = ((TransactionalService) service).createTransactionalObject(id, transaction); txnObjectMap.put(key, obj); } else { throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!"); } } return obj; }
public TransactionalObject getTransactionalObject(String serviceName, Object id) { if (transaction.getState() != Transaction.State.ACTIVE) { throw new TransactionNotActiveException("No transaction is found while accessing " + "transactional object -> " + serviceName + "[" + id + "]!"); } TransactionalObjectKey key = new TransactionalObjectKey(serviceName, id); TransactionalObject obj = txnObjectMap.get(key); if (obj == null) { final Object service = nodeEngine.getService(serviceName); if (service instanceof TransactionalService) { nodeEngine.getProxyService().initializeDistributedObject(serviceName, id); obj = ((TransactionalService) service).createTransactionalObject(id, transaction); txnObjectMap.put(key, obj); } else { if (service == null) { if (!nodeEngine.isActive()) { throw new HazelcastInstanceNotActiveException(); } throw new IllegalArgumentException("Unknown Service[" + serviceName + "]!"); } throw new IllegalArgumentException("Service[" + serviceName + "] is not transactional!"); } } return obj; }
diff --git a/liquibase-core/src/main/java/liquibase/servicelocator/ServiceLocator.java b/liquibase-core/src/main/java/liquibase/servicelocator/ServiceLocator.java index 4f4fec5f..fa36cb3f 100644 --- a/liquibase-core/src/main/java/liquibase/servicelocator/ServiceLocator.java +++ b/liquibase-core/src/main/java/liquibase/servicelocator/ServiceLocator.java @@ -1,235 +1,241 @@ package liquibase.servicelocator; import liquibase.exception.ServiceNotFoundException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.logging.Logger; import liquibase.logging.core.DefaultLogger; import liquibase.resource.ClassLoaderResourceAccessor; import liquibase.resource.ResourceAccessor; import liquibase.util.StringUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Modifier; import java.net.URL; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.ZipException; public class ServiceLocator { private static ServiceLocator instance; static { try { Class<?> scanner = Class.forName("LiquiBase.ServiceLocator.ClrServiceLocator, LiquiBase"); instance = (ServiceLocator) scanner.newInstance(); } catch (Exception e) { instance = new ServiceLocator(); } } private ResourceAccessor resourceAccessor; private Map<Class, List<Class>> classesBySuperclass; private List<String> packagesToScan; private Logger logger = new DefaultLogger(); //cannot look up regular logger because you get a stackoverflow since we are in the servicelocator protected ServiceLocator() { setResourceAccessor(new ClassLoaderResourceAccessor()); } protected ServiceLocator(ResourceAccessor accessor) { setResourceAccessor(accessor); } public static ServiceLocator getInstance() { return instance; } public void setResourceAccessor(ResourceAccessor resourceAccessor) { this.resourceAccessor = resourceAccessor; this.classesBySuperclass = new HashMap<Class, List<Class>>(); packagesToScan = new ArrayList<String>(); Enumeration<URL> manifests = null; try { manifests = resourceAccessor.getResources("META-INF/MANIFEST.MF"); while (manifests.hasMoreElements()) { URL url = manifests.nextElement(); InputStream is = url.openStream(); Manifest manifest = new Manifest(is); String attributes = StringUtils.trimToNull(manifest.getMainAttributes().getValue("LiquiBase-Package")); if (attributes != null) { for (Object value : attributes.split(",")) { addPackageToScan(value.toString()); } } is.close(); } } catch (IOException e) { throw new UnexpectedLiquibaseException(e); } } public void addPackageToScan(String packageName) { packagesToScan.add(packageName); } public Class findClass(Class requiredInterface) throws ServiceNotFoundException { Class[] classes = findClasses(requiredInterface); if (PrioritizedService.class.isAssignableFrom(requiredInterface)) { PrioritizedService returnObject = null; for (Class clazz : classes) { PrioritizedService newInstance; try { newInstance = (PrioritizedService) clazz.newInstance(); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } if (returnObject == null || newInstance.getPriority() > returnObject.getPriority()) { returnObject = newInstance; } } if (returnObject == null) { throw new ServiceNotFoundException("Could not find implementation of " + requiredInterface.getName()); } return returnObject.getClass(); } if (classes.length != 1) { throw new ServiceNotFoundException("Could not find unique implementation of " + requiredInterface.getName() + ". Found " + classes.length + " implementations"); } return classes[0]; } public Class[] findClasses(Class requiredInterface) throws ServiceNotFoundException { logger.debug("ServiceLocator.findClasses for "+requiredInterface.getName()); try { Class.forName(requiredInterface.getName()); if (!classesBySuperclass.containsKey(requiredInterface)) { classesBySuperclass.put(requiredInterface, new ArrayList<Class>()); for (String packageName : packagesToScan) { logger.debug("ServiceLocator scanning "+packageName+" with resoureAccessor "+resourceAccessor.getClass().getName()); String path = packageName.replace('.', '/'); Enumeration<URL> resources = resourceAccessor.getResources(path); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); logger.debug("Found "+packageName+" in "+resource.toExternalForm()); classesBySuperclass.get(requiredInterface).addAll(findClasses(resource, packageName, requiredInterface)); } } } } catch (Exception e) { throw new ServiceNotFoundException(e); } List<Class> classes = classesBySuperclass.get(requiredInterface); HashSet<Class> uniqueClasses = new HashSet<Class>(classes); return uniqueClasses.toArray(new Class[uniqueClasses.size()]); } public Object newInstance(Class requiredInterface) throws ServiceNotFoundException { try { return findClass(requiredInterface).newInstance(); } catch (Exception e) { throw new ServiceNotFoundException(e); } } private List<Class> findClasses(URL resource, String packageName, Class requiredInterface) throws Exception { logger.debug("ServiceLocator finding " + packageName + " classes in " + resource.toExternalForm() + " matching interface " + requiredInterface.getName()); List<Class> classes = new ArrayList<Class>(); // if (directory.toURI().toString().startsWith("jar:")) { // System.out.println("have a jar: "+directory.toString()); // } List<String> potentialClassNames = new ArrayList<String>(); if (resource.getProtocol().equals("jar")) { - File zipfile = new File(resource.getFile().split("!")[0].replaceFirst("file:\\/", "")); + String path = resource.getFile().split("!")[0]; + if(path.matches("file:\\/[A-Za-z]:\\/.*")) { + path = path.replaceFirst("file:\\/", ""); + }else { + path = path.replaceFirst("file:", ""); + } + File zipfile = new File(path); try { JarFile jarFile = new JarFile(zipfile); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith(packageName.replaceAll("\\.", "/")) && entry.getName().endsWith(".class")) { potentialClassNames.add(entry.getName().replaceAll("\\/", ".").substring(0, entry.getName().length() - ".class".length())); } } } catch(ZipException e) { throw (ZipException) new ZipException(e.getMessage() + " for " + zipfile).initCause(e); } } else if (resource.getProtocol().equals("file")) { File directory = new File(resource.getFile().replace("%20", " ")); if (!directory.exists()) { // System.out.println(directory + " does not exist"); return classes; } for (File file : directory.listFiles()) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file.toURL(), packageName + "." + file.getName(), requiredInterface)); } else if (file.getName().endsWith(".class")) { potentialClassNames.add(packageName + '.' + file.getName().substring(0, file.getName().length() - ".class".length())); } } } else { throw new UnexpectedLiquibaseException("Cannot read plugin classes from protocol " + resource.getProtocol()); } for (String potentialClassName : potentialClassNames) { Class<?> clazz = null; try { clazz = Class.forName(potentialClassName, true, resourceAccessor.toClassLoader()); } catch (NoClassDefFoundError e) { logger.warning("Could not configure extension class " + potentialClassName + ": Missing dependency " + e.getMessage()); continue; } catch (Throwable e) { logger.warning("Could not configure extension class " + potentialClassName + ": " + e.getMessage()); continue; } if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()) && isCorrectType(clazz, requiredInterface)) { logger.debug(potentialClassName + " matches "+requiredInterface.getName()); try { clazz.getConstructor(); classes.add(clazz); } catch (NoSuchMethodException e) { URL classAsUrl = resourceAccessor.toClassLoader().getResource(clazz.getName().replaceAll("\\.", "/") + ".class"); if (!clazz.getName().equals("liquibase.database.core.HibernateDatabase") && !clazz.getName().equals("liquibase.executor.LoggingExecutor") && (classAsUrl != null && !classAsUrl.toExternalForm().contains("build-test/liquibase/"))) { //keeps the logs down logger.warning("Class " + clazz.getName() + " does not have a public no-arg constructor, so it can't be used as a " + requiredInterface.getName() + " service"); } } // } else { // System.out.println(potentialClassName + " does not match"); } } return classes; } private boolean isCorrectType(Class<?> clazz, Class requiredInterface) { return !clazz.equals(Object.class) && (requiredInterface.isAssignableFrom(clazz) || isCorrectType(clazz.getSuperclass(), requiredInterface)); } public static void reset() { instance = new ServiceLocator(); } }
true
true
private List<Class> findClasses(URL resource, String packageName, Class requiredInterface) throws Exception { logger.debug("ServiceLocator finding " + packageName + " classes in " + resource.toExternalForm() + " matching interface " + requiredInterface.getName()); List<Class> classes = new ArrayList<Class>(); // if (directory.toURI().toString().startsWith("jar:")) { // System.out.println("have a jar: "+directory.toString()); // } List<String> potentialClassNames = new ArrayList<String>(); if (resource.getProtocol().equals("jar")) { File zipfile = new File(resource.getFile().split("!")[0].replaceFirst("file:\\/", "")); try { JarFile jarFile = new JarFile(zipfile); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith(packageName.replaceAll("\\.", "/")) && entry.getName().endsWith(".class")) { potentialClassNames.add(entry.getName().replaceAll("\\/", ".").substring(0, entry.getName().length() - ".class".length())); } } } catch(ZipException e) { throw (ZipException) new ZipException(e.getMessage() + " for " + zipfile).initCause(e); } } else if (resource.getProtocol().equals("file")) { File directory = new File(resource.getFile().replace("%20", " ")); if (!directory.exists()) { // System.out.println(directory + " does not exist"); return classes; } for (File file : directory.listFiles()) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file.toURL(), packageName + "." + file.getName(), requiredInterface)); } else if (file.getName().endsWith(".class")) { potentialClassNames.add(packageName + '.' + file.getName().substring(0, file.getName().length() - ".class".length())); } } } else { throw new UnexpectedLiquibaseException("Cannot read plugin classes from protocol " + resource.getProtocol()); } for (String potentialClassName : potentialClassNames) { Class<?> clazz = null; try { clazz = Class.forName(potentialClassName, true, resourceAccessor.toClassLoader()); } catch (NoClassDefFoundError e) { logger.warning("Could not configure extension class " + potentialClassName + ": Missing dependency " + e.getMessage()); continue; } catch (Throwable e) { logger.warning("Could not configure extension class " + potentialClassName + ": " + e.getMessage()); continue; } if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()) && isCorrectType(clazz, requiredInterface)) { logger.debug(potentialClassName + " matches "+requiredInterface.getName()); try { clazz.getConstructor(); classes.add(clazz); } catch (NoSuchMethodException e) { URL classAsUrl = resourceAccessor.toClassLoader().getResource(clazz.getName().replaceAll("\\.", "/") + ".class"); if (!clazz.getName().equals("liquibase.database.core.HibernateDatabase") && !clazz.getName().equals("liquibase.executor.LoggingExecutor") && (classAsUrl != null && !classAsUrl.toExternalForm().contains("build-test/liquibase/"))) { //keeps the logs down logger.warning("Class " + clazz.getName() + " does not have a public no-arg constructor, so it can't be used as a " + requiredInterface.getName() + " service"); } } // } else { // System.out.println(potentialClassName + " does not match"); } } return classes; }
private List<Class> findClasses(URL resource, String packageName, Class requiredInterface) throws Exception { logger.debug("ServiceLocator finding " + packageName + " classes in " + resource.toExternalForm() + " matching interface " + requiredInterface.getName()); List<Class> classes = new ArrayList<Class>(); // if (directory.toURI().toString().startsWith("jar:")) { // System.out.println("have a jar: "+directory.toString()); // } List<String> potentialClassNames = new ArrayList<String>(); if (resource.getProtocol().equals("jar")) { String path = resource.getFile().split("!")[0]; if(path.matches("file:\\/[A-Za-z]:\\/.*")) { path = path.replaceFirst("file:\\/", ""); }else { path = path.replaceFirst("file:", ""); } File zipfile = new File(path); try { JarFile jarFile = new JarFile(zipfile); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith(packageName.replaceAll("\\.", "/")) && entry.getName().endsWith(".class")) { potentialClassNames.add(entry.getName().replaceAll("\\/", ".").substring(0, entry.getName().length() - ".class".length())); } } } catch(ZipException e) { throw (ZipException) new ZipException(e.getMessage() + " for " + zipfile).initCause(e); } } else if (resource.getProtocol().equals("file")) { File directory = new File(resource.getFile().replace("%20", " ")); if (!directory.exists()) { // System.out.println(directory + " does not exist"); return classes; } for (File file : directory.listFiles()) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file.toURL(), packageName + "." + file.getName(), requiredInterface)); } else if (file.getName().endsWith(".class")) { potentialClassNames.add(packageName + '.' + file.getName().substring(0, file.getName().length() - ".class".length())); } } } else { throw new UnexpectedLiquibaseException("Cannot read plugin classes from protocol " + resource.getProtocol()); } for (String potentialClassName : potentialClassNames) { Class<?> clazz = null; try { clazz = Class.forName(potentialClassName, true, resourceAccessor.toClassLoader()); } catch (NoClassDefFoundError e) { logger.warning("Could not configure extension class " + potentialClassName + ": Missing dependency " + e.getMessage()); continue; } catch (Throwable e) { logger.warning("Could not configure extension class " + potentialClassName + ": " + e.getMessage()); continue; } if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()) && isCorrectType(clazz, requiredInterface)) { logger.debug(potentialClassName + " matches "+requiredInterface.getName()); try { clazz.getConstructor(); classes.add(clazz); } catch (NoSuchMethodException e) { URL classAsUrl = resourceAccessor.toClassLoader().getResource(clazz.getName().replaceAll("\\.", "/") + ".class"); if (!clazz.getName().equals("liquibase.database.core.HibernateDatabase") && !clazz.getName().equals("liquibase.executor.LoggingExecutor") && (classAsUrl != null && !classAsUrl.toExternalForm().contains("build-test/liquibase/"))) { //keeps the logs down logger.warning("Class " + clazz.getName() + " does not have a public no-arg constructor, so it can't be used as a " + requiredInterface.getName() + " service"); } } // } else { // System.out.println(potentialClassName + " does not match"); } } return classes; }
diff --git a/classpath/ikvm/internal/stubgen/StubGenerator.java b/classpath/ikvm/internal/stubgen/StubGenerator.java index c035d949..a0c6d708 100644 --- a/classpath/ikvm/internal/stubgen/StubGenerator.java +++ b/classpath/ikvm/internal/stubgen/StubGenerator.java @@ -1,1688 +1,1669 @@ /* Copyright (C) 2006, 2007 Jeroen Frijters This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters [email protected] */ package ikvm.internal.stubgen; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectStreamClass; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; public final class StubGenerator implements PrivilegedAction<byte[]> { private Class c; private StubGenerator(Class c) { this.c = c; } @ikvm.lang.Internal public static byte[] generateStub(Class c) { return AccessController.doPrivileged(new StubGenerator(c)); } public byte[] run() { boolean includeSerialVersionUIDs = "true".equalsIgnoreCase(System.getProperty("ikvm.stubgen.serialver")); Class outer = c.getDeclaringClass(); String name = c.getName().replace('.', '/'); String superClass = null; if(c.getSuperclass() != null) { superClass = c.getSuperclass().getName().replace('.', '/'); } if(c.isInterface()) { superClass = "java/lang/Object"; } int classmods = getModifiers(c); if(outer != null) { // protected inner classes are actually public and private inner classes are actually package if((classmods & Modifiers.Protected) != 0) { classmods |= Modifiers.Public; } classmods &= ~(Modifiers.Static | Modifiers.Private | Modifiers.Protected); } ClassFileWriter f = new ClassFileWriter(classmods, name, superClass, 0, 49); String genericSignature = BuildGenericSignature(c); if(genericSignature != null) { f.AddStringAttribute("Signature", genericSignature); } f.AddStringAttribute("IKVM.NET.Assembly", getAssemblyName(c)); if(isClassDeprecated(c)) { f.AddAttribute(new DeprecatedAttribute(f)); } InnerClassesAttribute innerClassesAttribute = null; if(outer != null) { innerClassesAttribute = new InnerClassesAttribute(f); String innername = name; // TODO instead of mangling the name, maybe we chould use the new Class APIs (e.g. getSimpleName()) int idx = name.lastIndexOf('$'); if(idx >= 0) { innername = innername.substring(idx + 1); } innerClassesAttribute.Add(name, outer.getName().replace('.', '/'), innername, getModifiers(c)); } Class[] interfaces = c.getInterfaces(); for(int i = 0; i < interfaces.length; i++) { f.AddInterface(interfaces[i].getName().replace('.', '/')); } Class[] innerClasses = c.getDeclaredClasses(); for(int i = 0; i < innerClasses.length; i++) { // TODO add private export support (for bcel) int mods = getModifiers(innerClasses[i]); if((mods & (Modifiers.Public | Modifiers.Protected)) != 0) { if(innerClassesAttribute == null) { innerClassesAttribute = new InnerClassesAttribute(f); } String namePart = innerClasses[i].getName(); // TODO name mangling namePart = namePart.substring(namePart.lastIndexOf('$') + 1); innerClassesAttribute.Add(innerClasses[i].getName().replace('.', '/'), name, namePart, mods); } } java.lang.reflect.Constructor[] constructors = c.getDeclaredConstructors(); for(int i = 0; i < constructors.length; i++) { int mods = constructors[i].getModifiers(); if((mods & (Modifiers.Public | Modifiers.Protected)) != 0) { if(constructors[i].isSynthetic()) { mods |= Modifiers.Synthetic; } if(constructors[i].isVarArgs()) { mods |= Modifiers.VarArgs; } Class[] args = constructors[i].getParameterTypes(); FieldOrMethod m = f.AddMethod(mods, "<init>", MakeSig(args, java.lang.Void.TYPE)); CodeAttribute code = new CodeAttribute(f); code.SetMaxLocals(args.length * 2 + 1); code.SetMaxStack(3); short index1 = f.AddClass("java/lang/UnsatisfiedLinkError"); short index2 = f.AddString("ikvmstub generated stubs can only be used on IKVM.NET"); short index3 = f.AddMethodRef("java/lang/UnsatisfiedLinkError", "<init>", "(Ljava/lang/String;)V"); code.SetByteCode(new byte[] { (byte)187, (byte)(index1 >> 8), (byte)index1, // new java/lang/UnsatisfiedLinkError (byte)89, // dup (byte)19, (byte)(index2 >> 8), (byte)index2, // ldc_w "..." (byte)183, (byte)(index3 >> 8), (byte)index3, // invokespecial java/lang/UnsatisfiedLinkError/init()V (byte)191 // athrow }); m.AddAttribute(code); AddExceptions(f, m, constructors[i].getExceptionTypes()); if(isMethodDeprecated(constructors[i])) { m.AddAttribute(new DeprecatedAttribute(f)); } String signature = BuildGenericSignature(constructors[i].getTypeParameters(), constructors[i].getGenericParameterTypes(), Void.TYPE, constructors[i].getGenericExceptionTypes()); if (signature != null) { m.AddAttribute(f.MakeStringAttribute("Signature", signature)); } Annotation[] annotations = constructors[i].getDeclaredAnnotations(); if(annotations.length > 0) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } Annotation[][] parameterAnnotations = constructors[i].getParameterAnnotations(); if(hasParameterAnnotations(parameterAnnotations)) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, parameterAnnotations)); } } } java.lang.reflect.Method[] methods = c.getDeclaredMethods(); for(int i = 0; i < methods.length; i++) { - // FXBUG (?) .NET reflection on java.lang.Object returns toString() twice! - // I didn't want to add the work around to CompiledTypeWrapper, so it's here. - if((c.getName().equals("java.lang.Object") || c.getName().equals("java.lang.Throwable")) - && methods[i].getName().equals("toString")) - { - boolean found = false; - for(int j = 0; j < i; j++) - { - if(methods[j].getName().equals("toString")) - { - found = true; - break; - } - } - if(found) - { - continue; - } - } int mods = methods[i].getModifiers(); if((mods & (Modifiers.Public | Modifiers.Protected)) != 0) { if((mods & Modifiers.Abstract) == 0) { mods |= Modifiers.Native; } if(methods[i].isBridge()) { mods |= Modifiers.Bridge; } if(methods[i].isSynthetic()) { mods |= Modifiers.Synthetic; } if(methods[i].isVarArgs()) { mods |= Modifiers.VarArgs; } Class[] args = methods[i].getParameterTypes(); Class retType = methods[i].getReturnType(); FieldOrMethod m = f.AddMethod(mods, methods[i].getName(), MakeSig(args, retType)); AddExceptions(f, m, methods[i].getExceptionTypes()); if(isMethodDeprecated(methods[i])) { m.AddAttribute(new DeprecatedAttribute(f)); } String signature = BuildGenericSignature(methods[i].getTypeParameters(), methods[i].getGenericParameterTypes(), methods[i].getGenericReturnType(), methods[i].getGenericExceptionTypes()); if (signature != null) { m.AddAttribute(f.MakeStringAttribute("Signature", signature)); } Object defaultValue = methods[i].getDefaultValue(); if(defaultValue != null) { m.AddAttribute(new AnnotationDefaultClassFileAttribute(f, defaultValue)); } Annotation[] annotations = methods[i].getDeclaredAnnotations(); if(annotations.length > 0) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } Annotation[][] parameterAnnotations = methods[i].getParameterAnnotations(); if(hasParameterAnnotations(parameterAnnotations)) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, parameterAnnotations)); } } } boolean hasSerialVersionUID = false; java.lang.reflect.Field[] fields = c.getDeclaredFields(); for(int i = 0; i < fields.length; i++) { int mods = fields[i].getModifiers(); boolean serialVersionUID = includeSerialVersionUIDs && fields[i].getName().equals("serialVersionUID"); hasSerialVersionUID |= serialVersionUID; if((mods & (Modifiers.Public | Modifiers.Protected)) != 0 || // Include serialVersionUID field, to make Japitools comparison more acurate ((mods & (Modifiers.Static | Modifiers.Final)) == (Modifiers.Static | Modifiers.Final) && serialVersionUID && fields[i].getType() == java.lang.Long.TYPE)) { // NOTE we can't use Field.get() because that will run the static initializer and // also won't allow us to see the difference between constants and blank final fields, // so we use a "native" method. Object constantValue = getFieldConstantValue(fields[i]); Class fieldType = fields[i].getType(); if(fields[i].isEnumConstant()) { mods |= Modifiers.Enum; } if(fields[i].isSynthetic()) { mods |= Modifiers.Synthetic; } FieldOrMethod fld = f.AddField(mods, fields[i].getName(), ClassToSig(fieldType), constantValue); if(isFieldDeprecated(fields[i])) { fld.AddAttribute(new DeprecatedAttribute(f)); } if(fields[i].getGenericType() != fieldType) { fld.AddAttribute(f.MakeStringAttribute("Signature", ToSigForm(fields[i].getGenericType()))); } Annotation[] annotations = fields[i].getDeclaredAnnotations(); if(annotations.length > 0) { fld.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } } } if(!hasSerialVersionUID && includeSerialVersionUIDs) { ObjectStreamClass osc = ObjectStreamClass.lookup(c); if(osc != null) { // class is serializable but doesn't have an explicit serialVersionUID, so we add the field to record // the serialVersionUID as we see it (mainly to make the Japi reports more realistic) f.AddField(Modifiers.Private | Modifiers.Static | Modifiers.Final, "serialVersionUID", "J", osc.getSerialVersionUID()); } } if(innerClassesAttribute != null) { f.AddAttribute(innerClassesAttribute); } Annotation[] annotations = c.getDeclaredAnnotations(); if(annotations.length > 0) { f.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); f.Write(baos); return baos.toByteArray(); } catch (IOException x) { throw new Error(x); } } public interface IConstantPoolWriter { short AddUtf8(String str); short AddInt(int i); short AddLong(long l); short AddFloat(float f); short AddDouble(double d); } public static byte[] writeAnnotations(IConstantPoolWriter cp, Annotation[] annotations) throws IOException, InvocationTargetException, IllegalAccessException { ByteArrayOutputStream mem = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(mem); dos.writeShort((short)annotations.length); for(Annotation ann : annotations) { RuntimeVisibleAnnotationsAttribute.WriteAnnotation(cp, dos, ann); } return mem.toByteArray(); } public static byte[] writeParameterAnnotations(IConstantPoolWriter cp, Annotation[][] parameterAnnotations) throws IOException, InvocationTargetException, IllegalAccessException { ByteArrayOutputStream mem = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(mem); dos.writeByte(parameterAnnotations.length); for(Annotation[] annotations : parameterAnnotations) { dos.writeShort((short)annotations.length); for(Annotation ann : annotations) { RuntimeVisibleAnnotationsAttribute.WriteAnnotation(cp, dos, ann); } } return mem.toByteArray(); } public static byte[] writeAnnotationDefault(IConstantPoolWriter cp, Object value) throws IOException, InvocationTargetException, IllegalAccessException { ByteArrayOutputStream mem = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(mem); RuntimeVisibleAnnotationsAttribute.WriteValue(cp, dos, value); return mem.toByteArray(); } private static boolean hasParameterAnnotations(Annotation[][] parameterAnnotations) { for(int i = 0; i < parameterAnnotations.length; i++) { if(parameterAnnotations[i].length > 0) { return true; } } return false; } private static int getModifiers(Class c) { int mods = c.getModifiers(); if(c.isAnnotation()) { mods |= Modifiers.Annotation; } if(c.isEnum()) { mods |= Modifiers.Enum; } if(c.isSynthetic()) { mods |= Modifiers.Synthetic; } return mods; } private static native String getAssemblyName(Class c); private static native boolean isClassDeprecated(Class c); private static native boolean isFieldDeprecated(Object field); private static native boolean isMethodDeprecated(Object method); private static native Object getFieldConstantValue(Object field); private static void AddExceptions(ClassFileWriter f, FieldOrMethod m, Class[] exceptions) { if (exceptions.length > 0) { ExceptionsAttribute attrib = new ExceptionsAttribute(f); for (int i = 0; i < exceptions.length; i++) { attrib.Add(exceptions[i].getName().replace('.', '/')); } m.AddAttribute(attrib); } } private static String MakeSig(Class[] args, Class ret) { StringBuilder sb = new StringBuilder(); sb.append('('); for(int i = 0; i < args.length; i++) { sb.append(ClassToSig(args[i])); } sb.append(')'); sb.append(ClassToSig(ret)); return sb.toString(); } private static String ClassToSig(Class c) { if(c.isPrimitive()) { if(c == Void.TYPE) { return "V"; } else if(c == Byte.TYPE) { return "B"; } else if(c == Boolean.TYPE) { return "Z"; } else if(c == Short.TYPE) { return "S"; } else if(c == Character.TYPE) { return "C"; } else if(c == Integer.TYPE) { return "I"; } else if(c == Long.TYPE) { return "J"; } else if(c == Float.TYPE) { return "F"; } else if(c == Double.TYPE) { return "D"; } else { throw new Error(); } } else if(c.isArray()) { return "[" + ClassToSig(c.getComponentType()); } else { return "L" + c.getName().replace('.', '/') + ";"; } } private static String BuildGenericSignature(Class c) { boolean isgeneric = false; StringBuilder sb = new StringBuilder(); java.lang.reflect.TypeVariable[] vars = c.getTypeParameters(); if(vars.length > 0) { isgeneric = true; sb.append('<'); for (int i = 0; i < vars.length; i++) { java.lang.reflect.TypeVariable t = vars[i]; sb.append(t.getName()); boolean first = true; java.lang.reflect.Type[] bounds = t.getBounds(); for (int j = 0; j < bounds.length; j++) { java.lang.reflect.Type bound = bounds[j]; if(first) { first = false; if(bound instanceof Class) { // HACK I don't really understand what the proper criterion is to decide this if(((Class)bound).isInterface()) { sb.append(':'); } } } sb.append(':').append(ToSigForm(bound)); } } sb.append('>'); } java.lang.reflect.Type superclass = c.getGenericSuperclass(); if(superclass == null) { sb.append("Ljava/lang/Object;"); } else { isgeneric |= !(superclass instanceof Class); sb.append(ToSigForm(superclass)); } java.lang.reflect.Type[] interfaces = c.getGenericInterfaces(); for (int i = 0; i < interfaces.length; i++) { java.lang.reflect.Type t = interfaces[i]; isgeneric |= !(t instanceof Class); sb.append(ToSigForm(t)); } if(isgeneric) { return sb.toString(); } return null; } private static String BuildGenericSignature(java.lang.reflect.TypeVariable[] typeParameters, java.lang.reflect.Type[] parameterTypes, java.lang.reflect.Type returnType, java.lang.reflect.Type[] exceptionTypes) { boolean isgeneric = false; StringBuilder sb = new StringBuilder(); if(typeParameters.length > 0) { isgeneric = true; sb.append('<'); for (int i = 0; i < typeParameters.length; i++) { java.lang.reflect.TypeVariable t = typeParameters[i]; sb.append(t.getName()); java.lang.reflect.Type[] bounds = t.getBounds(); for (int j = 0; j < bounds.length; j++) { sb.append(':').append(ToSigForm(bounds[j])); } } sb.append('>'); } sb.append('('); for (int i = 0; i < parameterTypes.length; i++) { java.lang.reflect.Type t = parameterTypes[i]; isgeneric |= !(t instanceof Class); sb.append(ToSigForm(t)); } sb.append(')'); sb.append(ToSigForm(returnType)); isgeneric |= !(returnType instanceof Class); for (int i = 0; i < exceptionTypes.length; i++) { java.lang.reflect.Type t = exceptionTypes[i]; isgeneric |= !(t instanceof Class); sb.append('^').append(ToSigForm(t)); } if(isgeneric) { return sb.toString(); } return null; } private static String ToSigForm(java.lang.reflect.Type t) { if(t instanceof java.lang.reflect.ParameterizedType) { java.lang.reflect.ParameterizedType p = (java.lang.reflect.ParameterizedType)t; StringBuilder sb = new StringBuilder(); sb.append('L').append(((Class)p.getRawType()).getName().replace('.', '/')); sb.append('<'); java.lang.reflect.Type[] args = p.getActualTypeArguments(); for (int i = 0; i < args.length; i++) { sb.append(ToSigForm(args[i])); } sb.append(">;"); return sb.toString(); } else if(t instanceof java.lang.reflect.TypeVariable) { return "T" + ((java.lang.reflect.TypeVariable)t).getName() + ";"; } else if(t instanceof java.lang.reflect.WildcardType) { java.lang.reflect.WildcardType w = (java.lang.reflect.WildcardType)t; java.lang.reflect.Type[] lower = w.getLowerBounds(); java.lang.reflect.Type[] upper = w.getUpperBounds(); if (lower.length == 0 && upper.length == 0) { return "*"; } if (lower.length == 1) { return "-" + ToSigForm(lower[0]); } if (upper.length == 1) { return "+" + ToSigForm(upper[0]); } // TODO throw new Error("Not Implemented"); } else if(t instanceof java.lang.reflect.GenericArrayType) { java.lang.reflect.GenericArrayType a = (java.lang.reflect.GenericArrayType)t; return "[" + ToSigForm(a.getGenericComponentType()); } else if(t instanceof Class) { return ClassToSig((Class)t); } else { throw new Error("Not Implemented: " + t); } } } class Modifiers { static final short Public = 0x0001; static final short Private = 0x0002; static final short Protected = 0x0004; static final short Static = 0x0008; static final short Final = 0x0010; static final short Super = 0x0020; static final short Synchronized = 0x0020; static final short Volatile = 0x0040; static final short Bridge = 0x0040; static final short Transient = 0x0080; static final short VarArgs = 0x0080; static final short Native = 0x0100; static final short Interface = 0x0200; static final short Abstract = 0x0400; static final short Strictfp = 0x0800; static final short Synthetic = 0x1000; static final short Annotation = 0x2000; static final short Enum = 0x4000; } class Constant { static final int Utf8 = 1; static final int Integer = 3; static final int Float = 4; static final int Long = 5; static final int Double = 6; static final int Class = 7; static final int String = 8; static final int Fieldref = 9; static final int Methodref = 10; static final int InterfaceMethodref = 11; static final int NameAndType = 12; } abstract class ConstantPoolItem { abstract void Write(DataOutputStream dos) throws IOException; } final class ConstantPoolItemClass extends ConstantPoolItem { private short name_index; public ConstantPoolItemClass(short name_index) { this.name_index = name_index; } public int hashCode() { return name_index; } public boolean equals(Object o) { if(o instanceof ConstantPoolItemClass) { return ((ConstantPoolItemClass)o).name_index == name_index; } return false; } void Write(DataOutputStream dos) throws IOException { dos.writeByte(Constant.Class); dos.writeShort(name_index); } } final class ConstantPoolItemMethodref extends ConstantPoolItem { private short class_index; private short name_and_type_index; public ConstantPoolItemMethodref(short class_index, short name_and_type_index) { this.class_index = class_index; this.name_and_type_index = name_and_type_index; } public int hashCode() { return (class_index & 0xFFFF) | (name_and_type_index << 16); } public boolean equals(Object o) { if(o instanceof ConstantPoolItemMethodref) { ConstantPoolItemMethodref m = (ConstantPoolItemMethodref)o; return m.class_index == class_index && m.name_and_type_index == name_and_type_index; } return false; } void Write(DataOutputStream dos) throws IOException { dos.writeByte(Constant.Methodref); dos.writeShort(class_index); dos.writeShort(name_and_type_index); } } final class ConstantPoolItemNameAndType extends ConstantPoolItem { private short name_index; private short descriptor_index; public ConstantPoolItemNameAndType(short name_index, short descriptor_index) { this.name_index = name_index; this.descriptor_index = descriptor_index; } public int hashCode() { return (name_index & 0xFFFF) | (descriptor_index << 16); } public boolean equals(Object o) { if(o instanceof ConstantPoolItemNameAndType) { ConstantPoolItemNameAndType n = (ConstantPoolItemNameAndType)o; return n.name_index == name_index && n.descriptor_index == descriptor_index; } return false; } void Write(DataOutputStream dos) throws IOException { dos.writeByte(Constant.NameAndType); dos.writeShort(name_index); dos.writeShort(descriptor_index); } } final class ConstantPoolItemUtf8 extends ConstantPoolItem { private String str; public ConstantPoolItemUtf8(String str) { this.str = str; } public int hashCode() { return str.hashCode(); } public boolean equals(Object o) { if(o instanceof ConstantPoolItemUtf8) { return ((ConstantPoolItemUtf8)o).str.equals(str); } return false; } void Write(DataOutputStream dos) throws IOException { dos.writeByte(Constant.Utf8); dos.writeUTF(str); } } final class ConstantPoolItemInt extends ConstantPoolItem { private int v; public ConstantPoolItemInt(int v) { this.v = v; } public int hashCode() { return v; } public boolean equals(Object o) { if(o instanceof ConstantPoolItemInt) { return ((ConstantPoolItemInt)o).v == v; } return false; } void Write(DataOutputStream dos) throws IOException { dos.writeByte(Constant.Integer); dos.writeInt(v); } } final class ConstantPoolItemLong extends ConstantPoolItem { private long v; public ConstantPoolItemLong(long v) { this.v = v; } public int hashCode() { return (int)v; } public boolean equals(Object o) { if(o instanceof ConstantPoolItemLong) { return ((ConstantPoolItemLong)o).v == v; } return false; } void Write(DataOutputStream dos) throws IOException { dos.writeByte(Constant.Long); dos.writeLong(v); } } final class ConstantPoolItemFloat extends ConstantPoolItem { private float v; public ConstantPoolItemFloat(float v) { this.v = v; } public int hashCode() { return Float.floatToIntBits(v); } public boolean equals(Object o) { if(o instanceof ConstantPoolItemFloat) { return ((ConstantPoolItemFloat)o).v == v; } return false; } void Write(DataOutputStream dos) throws IOException { dos.writeByte(Constant.Float); dos.writeFloat(v); } } final class ConstantPoolItemDouble extends ConstantPoolItem { private double v; public ConstantPoolItemDouble(double v) { this.v = v; } public int hashCode() { long l = Double.doubleToLongBits(v); return ((int)l) ^ ((int)(l >> 32)); } public boolean equals(Object o) { if(o instanceof ConstantPoolItemDouble) { return ((ConstantPoolItemDouble)o).v == v; } return false; } void Write(DataOutputStream dos) throws IOException { dos.writeByte(Constant.Double); dos.writeDouble(v); } } final class ConstantPoolItemString extends ConstantPoolItem { private short string_index; public ConstantPoolItemString(short string_index) { this.string_index = string_index; } public int hashCode() { return string_index; } public boolean equals(Object o) { if(o instanceof ConstantPoolItemString) { return ((ConstantPoolItemString)o).string_index == string_index; } return false; } void Write(DataOutputStream dos) throws IOException { dos.writeByte(Constant.String); dos.writeShort(string_index); } } class ClassFileAttribute { private short name_index; public ClassFileAttribute(short name_index) { this.name_index = name_index; } void Write(DataOutputStream dos) throws IOException { dos.writeShort(name_index); } } class DeprecatedAttribute extends ClassFileAttribute { DeprecatedAttribute(ClassFileWriter classFile) { super(classFile.AddUtf8("Deprecated")); } void Write(DataOutputStream dos) throws IOException { super.Write(dos); dos.writeInt(0); } } class ConstantValueAttribute extends ClassFileAttribute { private short constant_index; public ConstantValueAttribute(short name_index, short constant_index) { super(name_index); this.constant_index = constant_index; } void Write(DataOutputStream dos) throws IOException { super.Write(dos); dos.writeInt(2); dos.writeShort(constant_index); } } class StringAttribute extends ClassFileAttribute { private short string_index; public StringAttribute(short name_index, short string_index) { super(name_index); this.string_index = string_index; } void Write(DataOutputStream dos) throws IOException { super.Write(dos); dos.writeInt(2); dos.writeShort(string_index); } } class InnerClassesAttribute extends ClassFileAttribute { private ClassFileWriter classFile; private ArrayList classes = new ArrayList(); public InnerClassesAttribute(ClassFileWriter classFile) { super(classFile.AddUtf8("InnerClasses")); this.classFile = classFile; } void Write(DataOutputStream dos) throws IOException { super.Write(dos); dos.writeInt(2 + 8 * classes.size()); dos.writeShort(classes.size()); for (int i = 0; i < classes.size(); i++) { Item it = (Item)classes.get(i); dos.writeShort(it.inner_class_info_index); dos.writeShort(it.outer_class_info_index); dos.writeShort(it.inner_name_index); dos.writeShort(it.inner_class_access_flags); } } private class Item { short inner_class_info_index; short outer_class_info_index; short inner_name_index; short inner_class_access_flags; } public void Add(String inner, String outer, String name, int access) { Item i = new Item(); i.inner_class_info_index = classFile.AddClass(inner); i.outer_class_info_index = classFile.AddClass(outer); if(name != null) { i.inner_name_index = classFile.AddUtf8(name); } i.inner_class_access_flags = (short)access; classes.add(i); } } class ExceptionsAttribute extends ClassFileAttribute { private ClassFileWriter classFile; private ArrayList classes = new ArrayList(); ExceptionsAttribute(ClassFileWriter classFile) { super(classFile.AddUtf8("Exceptions")); this.classFile = classFile; } void Add(String exceptionClass) { classes.add(classFile.AddClass(exceptionClass)); } void Write(DataOutputStream dos) throws IOException { super.Write(dos); dos.writeInt(2 + 2 * classes.size()); dos.writeShort(classes.size()); for (int i = 0; i < classes.size(); i++) { short idx = (Short)classes.get(i); dos.writeShort(idx); } } } class RuntimeVisibleAnnotationsAttribute extends ClassFileAttribute { private ClassFileWriter classFile; private byte[] buf; RuntimeVisibleAnnotationsAttribute(ClassFileWriter classFile, Annotation[] annotations) { super(classFile.AddUtf8("RuntimeVisibleAnnotations")); this.classFile = classFile; try { ByteArrayOutputStream mem = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(mem); dos.writeShort((short)annotations.length); for(Annotation ann : annotations) { WriteAnnotation(classFile, dos, ann); } buf = mem.toByteArray(); } catch(Exception x) { throw new Error(x); } } RuntimeVisibleAnnotationsAttribute(ClassFileWriter classFile, Annotation[][] parameterAnnotations) { super(classFile.AddUtf8("RuntimeVisibleParameterAnnotations")); this.classFile = classFile; try { ByteArrayOutputStream mem = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(mem); dos.writeByte(parameterAnnotations.length); for(Annotation[] annotations : parameterAnnotations) { dos.writeShort((short)annotations.length); for(Annotation ann : annotations) { WriteAnnotation(classFile, dos, ann); } } buf = mem.toByteArray(); } catch(Exception x) { throw new Error(x); } } private static boolean deepEquals(Object o1, Object o2) { if (o1 == o2) return true; if (o1 == null || o2 == null) return false; if (o1 instanceof boolean[] && o2 instanceof boolean[]) return Arrays.equals((boolean[]) o1, (boolean[]) o2); if (o1 instanceof byte[] && o2 instanceof byte[]) return Arrays.equals((byte[]) o1, (byte[]) o2); if (o1 instanceof char[] && o2 instanceof char[]) return Arrays.equals((char[]) o1, (char[]) o2); if (o1 instanceof short[] && o2 instanceof short[]) return Arrays.equals((short[]) o1, (short[]) o2); if (o1 instanceof int[] && o2 instanceof int[]) return Arrays.equals((int[]) o1, (int[]) o2); if (o1 instanceof float[] && o2 instanceof float[]) return Arrays.equals((float[]) o1, (float[]) o2); if (o1 instanceof long[] && o2 instanceof long[]) return Arrays.equals((long[]) o1, (long[]) o2); if (o1 instanceof double[] && o2 instanceof double[]) return Arrays.equals((double[]) o1, (double[]) o2); if (o1 instanceof Object[] && o2 instanceof Object[]) return Arrays.equals((Object[]) o1, (Object[]) o2); return o1.equals(o2); } static void WriteValue(StubGenerator.IConstantPoolWriter classFile, DataOutputStream dos, Object val) throws IOException, IllegalAccessException, InvocationTargetException { if(val instanceof Boolean) { dos.writeByte('Z'); dos.writeShort(classFile.AddInt(((Boolean)val).booleanValue() ? 1 : 0)); } else if(val instanceof Byte) { dos.writeByte('B'); dos.writeShort(classFile.AddInt(((Byte)val).byteValue())); } else if(val instanceof Character) { dos.writeByte('C'); dos.writeShort(classFile.AddInt(((Character)val).charValue())); } else if(val instanceof Short) { dos.writeByte('S'); dos.writeShort(classFile.AddInt(((Short)val).shortValue())); } else if(val instanceof Integer) { dos.writeByte('I'); dos.writeShort(classFile.AddInt(((Integer)val).intValue())); } else if(val instanceof Float) { dos.writeByte('F'); dos.writeShort(classFile.AddFloat(((Float)val).floatValue())); } else if(val instanceof Long) { dos.writeByte('J'); dos.writeShort(classFile.AddLong(((Long)val).longValue())); } else if(val instanceof Double) { dos.writeByte('D'); dos.writeShort(classFile.AddDouble(((Double)val).doubleValue())); } else if(val instanceof String) { dos.writeByte('s'); dos.writeShort(classFile.AddUtf8((String)val)); } else if(val instanceof Enum) { Enum enumVal = (Enum)val; Class enumType = enumVal.getDeclaringClass(); dos.writeByte('e'); dos.writeShort(classFile.AddUtf8("L" + enumType.getName().replace('.', '/') + ";")); dos.writeShort(classFile.AddUtf8(enumVal.name())); } else if(val instanceof Class) { dos.writeByte('c'); Class c = (Class)val; String sig; if(c.isArray()) { sig = c.getName(); } else if(c == Boolean.TYPE) { sig = "Z"; } else if(c == Byte.TYPE) { sig = "B"; } else if(c == Character.TYPE) { sig = "C"; } else if(c == Short.TYPE) { sig = "S"; } else if(c == Integer.TYPE) { sig = "I"; } else if(c == Float.TYPE) { sig = "F"; } else if(c == Long.TYPE) { sig = "J"; } else if(c == Double.TYPE) { sig = "D"; } else if(c == Void.TYPE) { sig = "V"; } else { sig = "L" + c.getName() + ";"; } dos.writeShort(classFile.AddUtf8(sig.replace('.', '/'))); } else if(val instanceof Annotation) { dos.writeByte('@'); WriteAnnotation(classFile, dos, (Annotation)val); } else if(val.getClass().isArray()) { dos.writeByte('['); int len = Array.getLength(val); dos.writeShort((short)len); for(int i = 0; i < len; i++) { WriteValue(classFile, dos, Array.get(val, i)); } } else { throw new Error("Not Implemented: " + val.getClass()); } } static void WriteAnnotation(StubGenerator.IConstantPoolWriter classFile, DataOutputStream dos, Annotation ann) throws IOException, IllegalAccessException, InvocationTargetException { Class annotationType = ann.annotationType(); dos.writeShort(classFile.AddUtf8("L" + annotationType.getName().replace('.', '/') + ";")); short numvalues = 0; Method[] methods = annotationType.getDeclaredMethods(); for(int i = 0; i < methods.length; i++) { final Method m = methods[i]; AccessController.doPrivileged(new PrivilegedAction() { public Object run() { m.setAccessible(true); return null; } }); // HACK since there's no way to query if the annotation value is the default value // (and I don't want to add a private API for that), we simply compare the value // with the default and if they match we won't list the value. if(deepEquals(m.invoke(ann), m.getDefaultValue())) { methods[i] = null; } else { numvalues++; } } dos.writeShort(numvalues); for(Method m : methods) { if(m != null) { dos.writeShort(classFile.AddUtf8(m.getName())); WriteValue(classFile, dos, m.invoke(ann)); } } } void Write(DataOutputStream dos) throws IOException { super.Write(dos); dos.writeInt(buf.length); dos.write(buf); } } class AnnotationDefaultClassFileAttribute extends ClassFileAttribute { private ClassFileWriter classFile; private byte[] buf; AnnotationDefaultClassFileAttribute(ClassFileWriter classFile, Object val) { super(classFile.AddUtf8("AnnotationDefault")); this.classFile = classFile; try { ByteArrayOutputStream mem = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(mem); RuntimeVisibleAnnotationsAttribute.WriteValue(classFile, dos, val); buf = mem.toByteArray(); } catch (Exception x) { throw new Error(x); } } void Write(DataOutputStream dos) throws IOException { super.Write(dos); dos.writeInt(buf.length); dos.write(buf); } } class FieldOrMethod { private short access_flags; private short name_index; private short descriptor_index; private ArrayList attribs = new ArrayList(); public FieldOrMethod(int access_flags, short name_index, short descriptor_index) { this.access_flags = (short)access_flags; this.name_index = name_index; this.descriptor_index = descriptor_index; } public void AddAttribute(ClassFileAttribute attrib) { attribs.add(attrib); } public void Write(DataOutputStream dos) throws IOException { dos.writeShort(access_flags); dos.writeShort(name_index); dos.writeShort(descriptor_index); dos.writeShort(attribs.size()); for(int i = 0; i < attribs.size(); i++) { ((ClassFileAttribute)attribs.get(i)).Write(dos); } } } class CodeAttribute extends ClassFileAttribute { private ClassFileWriter classFile; private short max_stack; private short max_locals; private byte[] code; public CodeAttribute(ClassFileWriter classFile) { super(classFile.AddUtf8("Code")); this.classFile = classFile; } public void SetMaxStack(int v) { max_stack = (short)v; } public void SetMaxLocals(int v) { max_locals = (short)v; } public void SetByteCode(byte[] v) { code = v; } void Write(DataOutputStream dos) throws IOException { super.Write(dos); dos.writeInt(2 + 2 + 4 + code.length + 2 + 2); dos.writeShort(max_stack); dos.writeShort(max_locals); dos.writeInt(code.length); dos.write(code); dos.writeShort(0); // no exceptions dos.writeShort(0); // no attributes } } class ClassFileWriter implements StubGenerator.IConstantPoolWriter { private ArrayList cplist = new ArrayList(); private Hashtable cphashtable = new Hashtable(); private ArrayList fields = new ArrayList(); private ArrayList methods = new ArrayList(); private ArrayList attribs = new ArrayList(); private ArrayList interfaces = new ArrayList(); private int access_flags; private short this_class; private short super_class; private short minorVersion; private short majorVersion; public ClassFileWriter(int mods, String name, String superClass, int minorVersion, int majorVersion) { cplist.add(null); access_flags = mods; this_class = AddClass(name); if(superClass != null) { super_class = AddClass(superClass); } this.minorVersion = (short)minorVersion; this.majorVersion = (short)majorVersion; } private short Add(ConstantPoolItem cpi) { Object index = cphashtable.get(cpi); if(index == null) { index = (short)cplist.size(); cplist.add(cpi); if(cpi instanceof ConstantPoolItemDouble || cpi instanceof ConstantPoolItemLong) { cplist.add(null); } cphashtable.put(cpi, index); } return (Short)index; } public short AddUtf8(String str) { return Add(new ConstantPoolItemUtf8(str)); } public short AddClass(String classname) { return Add(new ConstantPoolItemClass(AddUtf8(classname))); } public short AddMethodRef(String classname, String methodname, String signature) { return Add(new ConstantPoolItemMethodref(AddClass(classname), AddNameAndType(methodname, signature))); } public short AddNameAndType(String name, String type) { return Add(new ConstantPoolItemNameAndType(AddUtf8(name), AddUtf8(type))); } public short AddInt(int i) { return Add(new ConstantPoolItemInt(i)); } public short AddLong(long l) { return Add(new ConstantPoolItemLong(l)); } public short AddFloat(float f) { return Add(new ConstantPoolItemFloat(f)); } public short AddDouble(double d) { return Add(new ConstantPoolItemDouble(d)); } public short AddString(String s) { return Add(new ConstantPoolItemString(AddUtf8(s))); } public void AddInterface(String name) { interfaces.add(AddClass(name)); } public FieldOrMethod AddMethod(int access, String name, String signature) { FieldOrMethod method = new FieldOrMethod(access, AddUtf8(name), AddUtf8(signature)); methods.add(method); return method; } public FieldOrMethod AddField(int access, String name, String signature, Object constantValue) { FieldOrMethod field = new FieldOrMethod(access, AddUtf8(name), AddUtf8(signature)); if(constantValue != null) { short constantValueIndex; if(constantValue instanceof Boolean) { constantValueIndex = AddInt(((Boolean)constantValue).booleanValue() ? 1 : 0); } else if(constantValue instanceof Byte) { constantValueIndex = AddInt(((Byte)constantValue).byteValue()); } else if(constantValue instanceof Short) { constantValueIndex = AddInt(((Short)constantValue).shortValue()); } else if(constantValue instanceof Character) { constantValueIndex = AddInt(((Character)constantValue).charValue()); } else if(constantValue instanceof Integer) { constantValueIndex = AddInt(((Integer)constantValue).intValue()); } else if(constantValue instanceof Long) { constantValueIndex = AddLong(((Long)constantValue).longValue()); } else if(constantValue instanceof Float) { constantValueIndex = AddFloat(((Float)constantValue).floatValue()); } else if(constantValue instanceof Double) { constantValueIndex = AddDouble(((Double)constantValue).doubleValue()); } else if(constantValue instanceof String) { constantValueIndex = AddString((String)constantValue); } else { throw new Error(); } field.AddAttribute(new ConstantValueAttribute(AddUtf8("ConstantValue"), constantValueIndex)); } fields.add(field); return field; } public ClassFileAttribute MakeStringAttribute(String name, String value) { return new StringAttribute(AddUtf8(name), AddUtf8(value)); } public void AddStringAttribute(String name, String value) { attribs.add(MakeStringAttribute(name, value)); } public void AddAttribute(ClassFileAttribute attrib) { attribs.add(attrib); } public void Write(OutputStream stream) throws IOException { DataOutputStream dos = new DataOutputStream(stream); dos.writeInt(0xCAFEBABE); dos.writeShort(minorVersion); dos.writeShort(majorVersion); dos.writeShort(cplist.size()); for(int i = 1; i < cplist.size(); i++) { ConstantPoolItem cpi = (ConstantPoolItem)cplist.get(i); if(cpi != null) { cpi.Write(dos); } } dos.writeShort(access_flags); dos.writeShort(this_class); dos.writeShort(super_class); // interfaces count dos.writeShort(interfaces.size()); for(int i = 0; i < interfaces.size(); i++) { dos.writeShort((Short)interfaces.get(i)); } // fields count dos.writeShort(fields.size()); for(int i = 0; i < fields.size(); i++) { ((FieldOrMethod)fields.get(i)).Write(dos); } // methods count dos.writeShort(methods.size()); for(int i = 0; i < methods.size(); i++) { ((FieldOrMethod)methods.get(i)).Write(dos); } // attributes count dos.writeShort(attribs.size()); for(int i = 0; i < attribs.size(); i++) { ((ClassFileAttribute)attribs.get(i)).Write(dos); } } }
true
true
public byte[] run() { boolean includeSerialVersionUIDs = "true".equalsIgnoreCase(System.getProperty("ikvm.stubgen.serialver")); Class outer = c.getDeclaringClass(); String name = c.getName().replace('.', '/'); String superClass = null; if(c.getSuperclass() != null) { superClass = c.getSuperclass().getName().replace('.', '/'); } if(c.isInterface()) { superClass = "java/lang/Object"; } int classmods = getModifiers(c); if(outer != null) { // protected inner classes are actually public and private inner classes are actually package if((classmods & Modifiers.Protected) != 0) { classmods |= Modifiers.Public; } classmods &= ~(Modifiers.Static | Modifiers.Private | Modifiers.Protected); } ClassFileWriter f = new ClassFileWriter(classmods, name, superClass, 0, 49); String genericSignature = BuildGenericSignature(c); if(genericSignature != null) { f.AddStringAttribute("Signature", genericSignature); } f.AddStringAttribute("IKVM.NET.Assembly", getAssemblyName(c)); if(isClassDeprecated(c)) { f.AddAttribute(new DeprecatedAttribute(f)); } InnerClassesAttribute innerClassesAttribute = null; if(outer != null) { innerClassesAttribute = new InnerClassesAttribute(f); String innername = name; // TODO instead of mangling the name, maybe we chould use the new Class APIs (e.g. getSimpleName()) int idx = name.lastIndexOf('$'); if(idx >= 0) { innername = innername.substring(idx + 1); } innerClassesAttribute.Add(name, outer.getName().replace('.', '/'), innername, getModifiers(c)); } Class[] interfaces = c.getInterfaces(); for(int i = 0; i < interfaces.length; i++) { f.AddInterface(interfaces[i].getName().replace('.', '/')); } Class[] innerClasses = c.getDeclaredClasses(); for(int i = 0; i < innerClasses.length; i++) { // TODO add private export support (for bcel) int mods = getModifiers(innerClasses[i]); if((mods & (Modifiers.Public | Modifiers.Protected)) != 0) { if(innerClassesAttribute == null) { innerClassesAttribute = new InnerClassesAttribute(f); } String namePart = innerClasses[i].getName(); // TODO name mangling namePart = namePart.substring(namePart.lastIndexOf('$') + 1); innerClassesAttribute.Add(innerClasses[i].getName().replace('.', '/'), name, namePart, mods); } } java.lang.reflect.Constructor[] constructors = c.getDeclaredConstructors(); for(int i = 0; i < constructors.length; i++) { int mods = constructors[i].getModifiers(); if((mods & (Modifiers.Public | Modifiers.Protected)) != 0) { if(constructors[i].isSynthetic()) { mods |= Modifiers.Synthetic; } if(constructors[i].isVarArgs()) { mods |= Modifiers.VarArgs; } Class[] args = constructors[i].getParameterTypes(); FieldOrMethod m = f.AddMethod(mods, "<init>", MakeSig(args, java.lang.Void.TYPE)); CodeAttribute code = new CodeAttribute(f); code.SetMaxLocals(args.length * 2 + 1); code.SetMaxStack(3); short index1 = f.AddClass("java/lang/UnsatisfiedLinkError"); short index2 = f.AddString("ikvmstub generated stubs can only be used on IKVM.NET"); short index3 = f.AddMethodRef("java/lang/UnsatisfiedLinkError", "<init>", "(Ljava/lang/String;)V"); code.SetByteCode(new byte[] { (byte)187, (byte)(index1 >> 8), (byte)index1, // new java/lang/UnsatisfiedLinkError (byte)89, // dup (byte)19, (byte)(index2 >> 8), (byte)index2, // ldc_w "..." (byte)183, (byte)(index3 >> 8), (byte)index3, // invokespecial java/lang/UnsatisfiedLinkError/init()V (byte)191 // athrow }); m.AddAttribute(code); AddExceptions(f, m, constructors[i].getExceptionTypes()); if(isMethodDeprecated(constructors[i])) { m.AddAttribute(new DeprecatedAttribute(f)); } String signature = BuildGenericSignature(constructors[i].getTypeParameters(), constructors[i].getGenericParameterTypes(), Void.TYPE, constructors[i].getGenericExceptionTypes()); if (signature != null) { m.AddAttribute(f.MakeStringAttribute("Signature", signature)); } Annotation[] annotations = constructors[i].getDeclaredAnnotations(); if(annotations.length > 0) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } Annotation[][] parameterAnnotations = constructors[i].getParameterAnnotations(); if(hasParameterAnnotations(parameterAnnotations)) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, parameterAnnotations)); } } } java.lang.reflect.Method[] methods = c.getDeclaredMethods(); for(int i = 0; i < methods.length; i++) { // FXBUG (?) .NET reflection on java.lang.Object returns toString() twice! // I didn't want to add the work around to CompiledTypeWrapper, so it's here. if((c.getName().equals("java.lang.Object") || c.getName().equals("java.lang.Throwable")) && methods[i].getName().equals("toString")) { boolean found = false; for(int j = 0; j < i; j++) { if(methods[j].getName().equals("toString")) { found = true; break; } } if(found) { continue; } } int mods = methods[i].getModifiers(); if((mods & (Modifiers.Public | Modifiers.Protected)) != 0) { if((mods & Modifiers.Abstract) == 0) { mods |= Modifiers.Native; } if(methods[i].isBridge()) { mods |= Modifiers.Bridge; } if(methods[i].isSynthetic()) { mods |= Modifiers.Synthetic; } if(methods[i].isVarArgs()) { mods |= Modifiers.VarArgs; } Class[] args = methods[i].getParameterTypes(); Class retType = methods[i].getReturnType(); FieldOrMethod m = f.AddMethod(mods, methods[i].getName(), MakeSig(args, retType)); AddExceptions(f, m, methods[i].getExceptionTypes()); if(isMethodDeprecated(methods[i])) { m.AddAttribute(new DeprecatedAttribute(f)); } String signature = BuildGenericSignature(methods[i].getTypeParameters(), methods[i].getGenericParameterTypes(), methods[i].getGenericReturnType(), methods[i].getGenericExceptionTypes()); if (signature != null) { m.AddAttribute(f.MakeStringAttribute("Signature", signature)); } Object defaultValue = methods[i].getDefaultValue(); if(defaultValue != null) { m.AddAttribute(new AnnotationDefaultClassFileAttribute(f, defaultValue)); } Annotation[] annotations = methods[i].getDeclaredAnnotations(); if(annotations.length > 0) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } Annotation[][] parameterAnnotations = methods[i].getParameterAnnotations(); if(hasParameterAnnotations(parameterAnnotations)) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, parameterAnnotations)); } } } boolean hasSerialVersionUID = false; java.lang.reflect.Field[] fields = c.getDeclaredFields(); for(int i = 0; i < fields.length; i++) { int mods = fields[i].getModifiers(); boolean serialVersionUID = includeSerialVersionUIDs && fields[i].getName().equals("serialVersionUID"); hasSerialVersionUID |= serialVersionUID; if((mods & (Modifiers.Public | Modifiers.Protected)) != 0 || // Include serialVersionUID field, to make Japitools comparison more acurate ((mods & (Modifiers.Static | Modifiers.Final)) == (Modifiers.Static | Modifiers.Final) && serialVersionUID && fields[i].getType() == java.lang.Long.TYPE)) { // NOTE we can't use Field.get() because that will run the static initializer and // also won't allow us to see the difference between constants and blank final fields, // so we use a "native" method. Object constantValue = getFieldConstantValue(fields[i]); Class fieldType = fields[i].getType(); if(fields[i].isEnumConstant()) { mods |= Modifiers.Enum; } if(fields[i].isSynthetic()) { mods |= Modifiers.Synthetic; } FieldOrMethod fld = f.AddField(mods, fields[i].getName(), ClassToSig(fieldType), constantValue); if(isFieldDeprecated(fields[i])) { fld.AddAttribute(new DeprecatedAttribute(f)); } if(fields[i].getGenericType() != fieldType) { fld.AddAttribute(f.MakeStringAttribute("Signature", ToSigForm(fields[i].getGenericType()))); } Annotation[] annotations = fields[i].getDeclaredAnnotations(); if(annotations.length > 0) { fld.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } } } if(!hasSerialVersionUID && includeSerialVersionUIDs) { ObjectStreamClass osc = ObjectStreamClass.lookup(c); if(osc != null) { // class is serializable but doesn't have an explicit serialVersionUID, so we add the field to record // the serialVersionUID as we see it (mainly to make the Japi reports more realistic) f.AddField(Modifiers.Private | Modifiers.Static | Modifiers.Final, "serialVersionUID", "J", osc.getSerialVersionUID()); } } if(innerClassesAttribute != null) { f.AddAttribute(innerClassesAttribute); } Annotation[] annotations = c.getDeclaredAnnotations(); if(annotations.length > 0) { f.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); f.Write(baos); return baos.toByteArray(); } catch (IOException x) { throw new Error(x); } }
public byte[] run() { boolean includeSerialVersionUIDs = "true".equalsIgnoreCase(System.getProperty("ikvm.stubgen.serialver")); Class outer = c.getDeclaringClass(); String name = c.getName().replace('.', '/'); String superClass = null; if(c.getSuperclass() != null) { superClass = c.getSuperclass().getName().replace('.', '/'); } if(c.isInterface()) { superClass = "java/lang/Object"; } int classmods = getModifiers(c); if(outer != null) { // protected inner classes are actually public and private inner classes are actually package if((classmods & Modifiers.Protected) != 0) { classmods |= Modifiers.Public; } classmods &= ~(Modifiers.Static | Modifiers.Private | Modifiers.Protected); } ClassFileWriter f = new ClassFileWriter(classmods, name, superClass, 0, 49); String genericSignature = BuildGenericSignature(c); if(genericSignature != null) { f.AddStringAttribute("Signature", genericSignature); } f.AddStringAttribute("IKVM.NET.Assembly", getAssemblyName(c)); if(isClassDeprecated(c)) { f.AddAttribute(new DeprecatedAttribute(f)); } InnerClassesAttribute innerClassesAttribute = null; if(outer != null) { innerClassesAttribute = new InnerClassesAttribute(f); String innername = name; // TODO instead of mangling the name, maybe we chould use the new Class APIs (e.g. getSimpleName()) int idx = name.lastIndexOf('$'); if(idx >= 0) { innername = innername.substring(idx + 1); } innerClassesAttribute.Add(name, outer.getName().replace('.', '/'), innername, getModifiers(c)); } Class[] interfaces = c.getInterfaces(); for(int i = 0; i < interfaces.length; i++) { f.AddInterface(interfaces[i].getName().replace('.', '/')); } Class[] innerClasses = c.getDeclaredClasses(); for(int i = 0; i < innerClasses.length; i++) { // TODO add private export support (for bcel) int mods = getModifiers(innerClasses[i]); if((mods & (Modifiers.Public | Modifiers.Protected)) != 0) { if(innerClassesAttribute == null) { innerClassesAttribute = new InnerClassesAttribute(f); } String namePart = innerClasses[i].getName(); // TODO name mangling namePart = namePart.substring(namePart.lastIndexOf('$') + 1); innerClassesAttribute.Add(innerClasses[i].getName().replace('.', '/'), name, namePart, mods); } } java.lang.reflect.Constructor[] constructors = c.getDeclaredConstructors(); for(int i = 0; i < constructors.length; i++) { int mods = constructors[i].getModifiers(); if((mods & (Modifiers.Public | Modifiers.Protected)) != 0) { if(constructors[i].isSynthetic()) { mods |= Modifiers.Synthetic; } if(constructors[i].isVarArgs()) { mods |= Modifiers.VarArgs; } Class[] args = constructors[i].getParameterTypes(); FieldOrMethod m = f.AddMethod(mods, "<init>", MakeSig(args, java.lang.Void.TYPE)); CodeAttribute code = new CodeAttribute(f); code.SetMaxLocals(args.length * 2 + 1); code.SetMaxStack(3); short index1 = f.AddClass("java/lang/UnsatisfiedLinkError"); short index2 = f.AddString("ikvmstub generated stubs can only be used on IKVM.NET"); short index3 = f.AddMethodRef("java/lang/UnsatisfiedLinkError", "<init>", "(Ljava/lang/String;)V"); code.SetByteCode(new byte[] { (byte)187, (byte)(index1 >> 8), (byte)index1, // new java/lang/UnsatisfiedLinkError (byte)89, // dup (byte)19, (byte)(index2 >> 8), (byte)index2, // ldc_w "..." (byte)183, (byte)(index3 >> 8), (byte)index3, // invokespecial java/lang/UnsatisfiedLinkError/init()V (byte)191 // athrow }); m.AddAttribute(code); AddExceptions(f, m, constructors[i].getExceptionTypes()); if(isMethodDeprecated(constructors[i])) { m.AddAttribute(new DeprecatedAttribute(f)); } String signature = BuildGenericSignature(constructors[i].getTypeParameters(), constructors[i].getGenericParameterTypes(), Void.TYPE, constructors[i].getGenericExceptionTypes()); if (signature != null) { m.AddAttribute(f.MakeStringAttribute("Signature", signature)); } Annotation[] annotations = constructors[i].getDeclaredAnnotations(); if(annotations.length > 0) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } Annotation[][] parameterAnnotations = constructors[i].getParameterAnnotations(); if(hasParameterAnnotations(parameterAnnotations)) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, parameterAnnotations)); } } } java.lang.reflect.Method[] methods = c.getDeclaredMethods(); for(int i = 0; i < methods.length; i++) { int mods = methods[i].getModifiers(); if((mods & (Modifiers.Public | Modifiers.Protected)) != 0) { if((mods & Modifiers.Abstract) == 0) { mods |= Modifiers.Native; } if(methods[i].isBridge()) { mods |= Modifiers.Bridge; } if(methods[i].isSynthetic()) { mods |= Modifiers.Synthetic; } if(methods[i].isVarArgs()) { mods |= Modifiers.VarArgs; } Class[] args = methods[i].getParameterTypes(); Class retType = methods[i].getReturnType(); FieldOrMethod m = f.AddMethod(mods, methods[i].getName(), MakeSig(args, retType)); AddExceptions(f, m, methods[i].getExceptionTypes()); if(isMethodDeprecated(methods[i])) { m.AddAttribute(new DeprecatedAttribute(f)); } String signature = BuildGenericSignature(methods[i].getTypeParameters(), methods[i].getGenericParameterTypes(), methods[i].getGenericReturnType(), methods[i].getGenericExceptionTypes()); if (signature != null) { m.AddAttribute(f.MakeStringAttribute("Signature", signature)); } Object defaultValue = methods[i].getDefaultValue(); if(defaultValue != null) { m.AddAttribute(new AnnotationDefaultClassFileAttribute(f, defaultValue)); } Annotation[] annotations = methods[i].getDeclaredAnnotations(); if(annotations.length > 0) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } Annotation[][] parameterAnnotations = methods[i].getParameterAnnotations(); if(hasParameterAnnotations(parameterAnnotations)) { m.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, parameterAnnotations)); } } } boolean hasSerialVersionUID = false; java.lang.reflect.Field[] fields = c.getDeclaredFields(); for(int i = 0; i < fields.length; i++) { int mods = fields[i].getModifiers(); boolean serialVersionUID = includeSerialVersionUIDs && fields[i].getName().equals("serialVersionUID"); hasSerialVersionUID |= serialVersionUID; if((mods & (Modifiers.Public | Modifiers.Protected)) != 0 || // Include serialVersionUID field, to make Japitools comparison more acurate ((mods & (Modifiers.Static | Modifiers.Final)) == (Modifiers.Static | Modifiers.Final) && serialVersionUID && fields[i].getType() == java.lang.Long.TYPE)) { // NOTE we can't use Field.get() because that will run the static initializer and // also won't allow us to see the difference between constants and blank final fields, // so we use a "native" method. Object constantValue = getFieldConstantValue(fields[i]); Class fieldType = fields[i].getType(); if(fields[i].isEnumConstant()) { mods |= Modifiers.Enum; } if(fields[i].isSynthetic()) { mods |= Modifiers.Synthetic; } FieldOrMethod fld = f.AddField(mods, fields[i].getName(), ClassToSig(fieldType), constantValue); if(isFieldDeprecated(fields[i])) { fld.AddAttribute(new DeprecatedAttribute(f)); } if(fields[i].getGenericType() != fieldType) { fld.AddAttribute(f.MakeStringAttribute("Signature", ToSigForm(fields[i].getGenericType()))); } Annotation[] annotations = fields[i].getDeclaredAnnotations(); if(annotations.length > 0) { fld.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } } } if(!hasSerialVersionUID && includeSerialVersionUIDs) { ObjectStreamClass osc = ObjectStreamClass.lookup(c); if(osc != null) { // class is serializable but doesn't have an explicit serialVersionUID, so we add the field to record // the serialVersionUID as we see it (mainly to make the Japi reports more realistic) f.AddField(Modifiers.Private | Modifiers.Static | Modifiers.Final, "serialVersionUID", "J", osc.getSerialVersionUID()); } } if(innerClassesAttribute != null) { f.AddAttribute(innerClassesAttribute); } Annotation[] annotations = c.getDeclaredAnnotations(); if(annotations.length > 0) { f.AddAttribute(new RuntimeVisibleAnnotationsAttribute(f, annotations)); } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); f.Write(baos); return baos.toByteArray(); } catch (IOException x) { throw new Error(x); } }
diff --git a/src/com/redhat/qe/sm/cli/tests/TranslationTests.java b/src/com/redhat/qe/sm/cli/tests/TranslationTests.java index 7df0d524..2106afe0 100644 --- a/src/com/redhat/qe/sm/cli/tests/TranslationTests.java +++ b/src/com/redhat/qe/sm/cli/tests/TranslationTests.java @@ -1,680 +1,680 @@ package com.redhat.qe.sm.cli.tests; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.redhat.qe.Assert; import com.redhat.qe.auto.bugzilla.BlockedByBzBug; import com.redhat.qe.auto.tcms.ImplementsNitrateTest; import com.redhat.qe.auto.testng.TestNGUtils; import com.redhat.qe.sm.base.CandlepinType; import com.redhat.qe.sm.base.SubscriptionManagerCLITestScript; import com.redhat.qe.sm.data.Translation; import com.redhat.qe.tools.RemoteFileTasks; import com.redhat.qe.tools.SSHCommandResult; /** * @author jsefler * References: * Engineering Localization Services: https://home.corp.redhat.com/node/53593 * http://git.fedorahosted.org/git/?p=subscription-manager.git;a=blob;f=po/pt.po;h=0854212f4fab348a25f0542625df343653a4a097;hb=RHEL6.3 * Here is the raw rhsm.po file for LANG=pt * http://git.fedorahosted.org/git/?p=subscription-manager.git;a=blob;f=po/pt.po;hb=RHEL6.3 * * https://translate.zanata.org/zanata/project/view/subscription-manager/iter/0.99.X/stats * * https://fedora.transifex.net/projects/p/fedora/ * * http://translate.sourceforge.net/wiki/ * http://translate.sourceforge.net/wiki/toolkit/index * http://translate.sourceforge.net/wiki/toolkit/pofilter * http://translate.sourceforge.net/wiki/toolkit/pofilter_tests * http://translate.sourceforge.net/wiki/toolkit/installation * * https://github.com/translate/translate * * RHEL5 * Table 2.1. Red Hat Enterprise Linux 5 International Languages * http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/5/html/International_Language_Support_Guide/Red_Hat_Enterprise_Linux_International_Language_Support_Guide-Installing_and_supporting_languages.html * notice Sri Lanka Sinhala si_LK.UTF-8) * * RHEL6 * https://engineering.redhat.com/trac/LocalizationServices * https://engineering.redhat.com/trac/LocalizationServices/wiki/L10nRHEL6LanguageSupportCriteria * **/ @Test(groups={"TranslationTests"}) public class TranslationTests extends SubscriptionManagerCLITestScript { // Test Methods *********************************************************************** @Test( description="subscription-manager-cli: assert help commands return translated text", groups={/*"blockedByBug-756156"*/}, dataProvider="getTranslatedCommandLineHelpData") //@ImplementsNitrateTest(caseId=) public void TranslatedCommandLineHelp_Test(Object meta, String lang, String command, List<String> stdoutRegexs) { SSHCommandResult result = RemoteFileTasks.runCommandAndAssert(client,"LANG="+lang+".UTF-8 "+command,0,stdoutRegexs,null); } @Test( description="subscription-manager-cli: attempt to register to a Candlepin server using bogus credentials and check for localized strings results", groups={"AcceptanceTests"}, dataProvider="getInvalidRegistrationWithLocalizedStringsData") @ImplementsNitrateTest(caseId=41691) public void AttemptLocalizedRegistrationWithInvalidCredentials_Test(Object bugzilla, String lang, String username, String password, Integer exitCode, String stdoutRegex, String stderrRegex) { // ensure we are unregistered clienttasks.unregister(null, null, null); log.info("Attempting to register to a candlepin server using invalid credentials and expecting output in language "+(lang==null?"DEFAULT":lang)); String command = String.format("%s %s register --username=%s --password=%s", lang==null?"":"LANG="+lang, clienttasks.command, username, password); RemoteFileTasks.runCommandAndAssert(client, command, exitCode, stdoutRegex, stderrRegex); // assert that the consumer cert and key have NOT been dropped Assert.assertTrue(!RemoteFileTasks.testExists(client,clienttasks.consumerKeyFile()), "Consumer key file '"+clienttasks.consumerKeyFile()+"' does NOT exist after an attempt to register with invalid credentials."); Assert.assertTrue(!RemoteFileTasks.testExists(client,clienttasks.consumerCertFile()), "Consumer cert file '"+clienttasks.consumerCertFile()+" does NOT exist after an attempt to register with invalid credentials."); } @Test( description="attempt LANG=C subscription-manager register", groups={"blockedByBug-729988"}, enabled=true) //@ImplementsNitrateTest(caseId=) public void RegisterWithFallbackCLocale_Test() { // [root@rhsm-compat-rhel61 ~]# LANG=C subscription-manager register --username stage_test_12 --password redhat 1>/tmp/stdout 2>/tmp/stderr // [root@rhsm-compat-rhel61 ~]# echo $? // 255 // [root@rhsm-compat-rhel61 ~]# cat /tmp/stdout // [root@rhsm-compat-rhel61 ~]# cat /tmp/stderr // 'NoneType' object has no attribute 'lower' // [root@rhsm-compat-rhel61 ~]# for(String lang: new String[]{"C","us"}) { clienttasks.unregister(null, null, null); String command = String.format("%s register --username %s --password %s", clienttasks.command,sm_clientUsername,sm_clientPassword); if (sm_clientOrg!=null) command += String.format(" --org %s", sm_clientOrg); SSHCommandResult sshCommandResult = clienttasks.runCommandWithLang(lang,clienttasks.command+" register --username "+sm_clientUsername+" --password "+sm_clientPassword+" "+(sm_clientOrg!=null?"--org "+sm_clientOrg:"")); Assert.assertEquals(sshCommandResult.getExitCode(), Integer.valueOf(0),"ExitCode after register with LANG="+lang+" fallback locale."); //Assert.assertContainsMatch(sshCommandResult.getStdout().trim(), expectedStdoutRegex,"Stdout after register with LANG="+lang+" fallback locale."); //Assert.assertContainsMatch(sshCommandResult.getStderr().trim(), expectedStderrRegex,"Stderr after register with LANG="+lang+" fallback locale."); } } @Test( description="subscription-manager: attempt redeem without --email option using LANG", groups={"blockedByBug-766577","AcceptanceTests"}, enabled=false) // TODO PASSES ON THE COMMAND LINE BUT FAILS WHEN RUN THROUGH AUTOMATION - NOTE STDOUT DISPLAYS DOUBLE BYTE BUT NOT STDERR //@ImplementsNitrateTest(caseId=) public void AttemptRedeemWithoutEmailUsingLang_Test() { clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String)null, null, null, true, false, null, null, null); //SSHCommandResult redeemResult = clienttasks.redeem_(null,null,null,null,null) String lang = "de_DE"; log.info("Attempting to redeem without specifying email expecting output in language "+(lang==null?"DEFAULT":lang)); String command = String.format("%s %s redeem", lang==null?"":"LANG="+lang+".UTF-8", clienttasks.command); client.runCommandAndWait(command+" --help"); SSHCommandResult redeemResult = client.runCommandAndWait(command); // bug766577 // 201112191709:14.807 - FINE: ssh [email protected] LANG=de_DE subscription-manager redeem // 201112191709:17.276 - FINE: Stdout: // 201112191709:17.277 - FINE: Stderr: 'ascii' codec can't encode character u'\xf6' in position 20: ordinal not in range(128) // 201112191709:17.277 - FINE: ExitCode: 255 // [root@jsefler-onprem-5server ~]# LANG=de_DE.UTF-8 subscription-manager redeem // E-Mail-Adresse ist nötig zur Benachrichtigung // assert redemption results //Assert.assertEquals(redeemResult.getStdout().trim(), "email and email_locale are required for notification","Redeem should require that the email option be specified."); Assert.assertEquals(redeemResult.getStderr().trim(), ""); Assert.assertEquals(redeemResult.getStdout().trim(), "E-Mail-Adresse ist nötig zur Benachrichtigung","Redeem should require that the email option be specified."); Assert.assertEquals(redeemResult.getExitCode(), Integer.valueOf(255),"Exit code from redeem when executed without an email option."); } @Test( description="verify that rhsm.mo is installed for each of the supported locales", groups={"AcceptanceTests"}, dataProvider="getSupportedLocalesData", enabled=false) // replaced by VerifyOnlyExpectedTranslationFilesAreInstalled_Test @Deprecated //@ImplementsNitrateTest(caseId=) public void VerifyTranslationFileIsInstalled_Test_DEPRECATED(Object bugzilla, String locale) { File localeFile = localeFile(locale); Assert.assertTrue(RemoteFileTasks.testExists(client, localeFile.getPath()),"Supported locale file '"+localeFile+"' is installed."); if (!translationFileMapForSubscriptionManager.keySet().contains(localeFile)) Assert.fail("Something went wrong in TranslationTests.buildTranslationFileMap(). File '"+localeFile+"' was not found in the translationFileMap.keySet()."); } @Test( description="verify that only the expected rhsm.mo tranlation files are installed for each of the supported locales", groups={"AcceptanceTests", "blockedByBug-824100"}, enabled=true) //@ImplementsNitrateTest(caseId=) public void VerifyOnlyExpectedTranslationFilesAreInstalled_Test() { List<File> supportedTranslationFiles = new ArrayList<File>(); for (String supportedLocale : supportedLocales) supportedTranslationFiles.add(localeFile(supportedLocale)); log.info("Expected locales include: "+supportedLocales); // assert no unexpected translation files are installed boolean unexpectedTranslationFilesFound = false; for (File translationFile : translationFileMapForSubscriptionManager.keySet()) { if (!supportedTranslationFiles.contains(translationFile)) { unexpectedTranslationFilesFound = true; log.warning("Unexpected translation file '"+translationFile+"' is installed."); } } // assert that all expected translation files are installed boolean allExpectedTranslationFilesFound = true; for (File translationFile : supportedTranslationFiles) { if (!translationFileMapForSubscriptionManager.keySet().contains(translationFile)) { log.warning("Expected translation file '"+translationFile+"' is NOT installed."); allExpectedTranslationFilesFound = false; } else { log.info("Expected translation file '"+translationFile+"' is installed."); } } Assert.assertTrue(!unexpectedTranslationFilesFound, "No unexpected translation files were found installed."); Assert.assertTrue(allExpectedTranslationFilesFound, "All expected translation files were found installed."); } @Test( description="verify that only the expected rhsm.mo tranlation files are installed for each of the supported locales", groups={"AcceptanceTests"}, dataProvider="getTranslationFileData", enabled=true) //@ImplementsNitrateTest(caseId=) public void VerifyTranslationFileContainsAllMsgids_Test(Object bugzilla, File translationFile) { List<Translation> translationList = translationFileMapForSubscriptionManager.get(translationFile); boolean translationFilePassed=true; for (String msgid : translationMsgidSet) { int numMsgidOccurances=0; for (Translation translation : translationList) { if (translation.msgid.equals(msgid)) numMsgidOccurances++; } if (numMsgidOccurances!=1) { log.warning("Expected 1 occurance (actual='"+numMsgidOccurances+"') of the following msgid in translation file '"+translationFile+"': msgid \""+msgid+"\""); translationFilePassed=false; } } Assert.assertTrue(translationFilePassed,"Exactly 1 occurance of all the expected translation msgids ("+translationMsgidSet.size()+") were found in translation file '"+translationFile+"'."); } @Test( description="run pofilter translate tests on the translation file", groups={}, dataProvider="getTranslationFilePofilterTestData", enabled=false) // 07/12/2012 this was the initial test created for the benefit of fsharath who further developed the test in PofilterTranslationTests.java; disabling this test in favor of his @Deprecated //@ImplementsNitrateTest(caseId=) public void pofilter_Test(Object bugzilla, String pofilterTest, File translationFile) { log.info("For an explanation of pofilter test '"+pofilterTest+"', see: http://translate.sourceforge.net/wiki/toolkit/pofilter_tests"); File translationPoFile = new File(translationFile.getPath().replaceFirst(".mo$", ".po")); // execute the pofilter test String pofilterCommand = "pofilter --gnome -t "+pofilterTest; SSHCommandResult pofilterResult = client.runCommandAndWait(pofilterCommand+" "+translationPoFile); Assert.assertEquals(pofilterResult.getExitCode(), new Integer(0), "Successfully executed the pofilter tests."); // convert the pofilter test results into a list of failed Translation objects for simplified handling of special cases List<Translation> pofilterFailedTranslations = Translation.parse(pofilterResult.getStdout()); // remove the first translation which contains only meta data if (!pofilterFailedTranslations.isEmpty() && pofilterFailedTranslations.get(0).msgid.equals("")) pofilterFailedTranslations.remove(0); // ignore the following special cases of acceptable results.......... List<String> ignorableMsgIds = Arrays.asList(); if (pofilterTest.equals("accelerators")) { if (translationFile.getPath().contains("/hi/")) ignorableMsgIds = Arrays.asList("proxy url in the form of proxy_hostname:proxy_port"); if (translationFile.getPath().contains("/ru/")) ignorableMsgIds = Arrays.asList("proxy url in the form of proxy_hostname:proxy_port"); } if (pofilterTest.equals("newlines")) { ignorableMsgIds = Arrays.asList( "Optional language to use for email notification when subscription redemption is complete. Examples: en-us, de-de", "\n"+"Unable to register.\n"+"For further assistance, please contact Red Hat Global Support Services.", "Tip: Forgot your login or password? Look it up at http://red.ht/lost_password", "Unable to perform refresh due to the following exception: %s", ""+"This migration script requires the system to be registered to RHN Classic.\n"+"However this system appears to be registered to '%s'.\n"+"Exiting.", "The tool you are using is attempting to re-register using RHN Certificate-Based technology. Red Hat recommends (except in a few cases) that customers only register with RHN once.", // bug 825397 ""+"Redeeming the subscription may take a few minutes.\n"+"Please provide an email address to receive notification\n"+"when the redemption is complete.", // the Subscription Redemption dialog actually expands to accommodate the message, therefore we could ignore it // bug 825397 should fix this // bug 825388 ""+"We have detected that you have multiple service level\n"+"agreements on various products. Please select how you\n"+"want them assigned.", // bug 825388 or 825397 should fix this "\n"+"This machine appears to be already registered to Certificate-based RHN. Exiting.", "\n"+"This machine appears to be already registered to Red Hat Subscription Management. Exiting."); } if (pofilterTest.equals("unchanged")) { ignorableMsgIds = Arrays.asList("close_button","facts_view","register_button","register_dialog_main_vbox","registration_dialog_action_area\n","prod 1, prod2, prod 3, prod 4, prod 5, prod 6, prod 7, prod 8"); } // pluck out the ignorable pofilter test results for (String msgid : ignorableMsgIds) { Translation ignoreTranslation = Translation.findFirstInstanceWithMatchingFieldFromList("msgid", msgid, pofilterFailedTranslations); if (ignoreTranslation!=null) { log.info("Ignoring result of pofiliter test '"+pofilterTest+"' for msgid: "+ignoreTranslation.msgid); pofilterFailedTranslations.remove(ignoreTranslation); } } // assert that there are no failed pofilter translation test results Assert.assertEquals(pofilterFailedTranslations.size(),0, "Discounting the ignored test results, the number of failed pofilter '"+pofilterTest+"' tests for translation file '"+translationFile+"'."); } // Candidates for an automated Test: // TODO Bug 752321 - [ALL LANG] [RHSM CLI] Word [OPTIONS] is unlocalized and some message translation is still not complete // TODO NESTED LANG LOOP... for L in en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR pt_BR ru_RU zh_CN zh_TW as_IN bn_IN hi_IN mr_IN gu_IN kn_IN ml_IN or_IN pa_IN ta_IN te_IN; do for C in list refresh register subscribe unregister unsubscribe clean config environments facts identity import orgs redeem repos; do echo ""; echo "# LANG=$L.UTF8 subscription-manager $C --help | grep OPTIONS"; LANG=$L.UTF8 subscription-manager $C --help | grep OPTIONS; done; done; // TODO Create an equivalent test for candlepin VerifyOnlyExpectedTranslationFilesAreInstalled_Test // TODO Create an equivalent test for candlepin VerifyTranslationFileContainsAllMsgids_Test // Configuration Methods *********************************************************************** @BeforeClass (groups="setup") public void buildTranslationFileMapForSubscriptionManagerBeforeClass() { translationFileMapForSubscriptionManager = buildTranslationFileMapForSubscriptionManager(); } Map<File,List<Translation>> translationFileMapForSubscriptionManager = null; // @BeforeClass (groups="setup") // public void buildTranslationFileMapForCandlepinBeforeClass() { // translationFileMapForCandlepin = buildTranslationFileMapForCandlepin(); // } // Map<File,List<Translation>> translationFileMapForCandlepin; @BeforeClass (groups="setup",dependsOnMethods={"buildTranslationFileMapForSubscriptionManagerBeforeClass"}) public void buildTranslationMsgidSet() { if (clienttasks==null) return; // assemble a unique set of msgids (by taking the union of all the msgids from all of the translation files.) // TODO: My assumption that the union of all the msgids from the translation files completely matches // the currently extracted message ids from the source code is probably incorrect. // There could be extra msgids in the translation files that were left over from the last round // of translations and are no longer applicable (should be excluded from this union algorithm). for (File translationFile : translationFileMapForSubscriptionManager.keySet()) { List<Translation> translationList = translationFileMapForSubscriptionManager.get(translationFile); for (Translation translation : translationList) { translationMsgidSet.add(translation.msgid); } } } Set<String> translationMsgidSet = new HashSet<String>(500); // 500 is an estimated size // Protected Methods *********************************************************************** List<String> supportedLocales = Arrays.asList( "as", "bn_IN","de_DE","es_ES","fr", "gu", "hi", "it", "ja", "kn", "ko", "ml", "mr", "or", "pa", "pt_BR","ru", "ta_IN","te", "zh_CN","zh_TW"); List<String> supportedLangs = Arrays.asList( "as_IN","bn_IN","de_DE","es_ES","fr_FR","gu_IN","hi_IN","it_IT","ja_JP","kn_IN","ko_KR","ml_IN","mr_IN","or_IN","pa_IN","pt_BR","ru_RU","ta_IN","te_IN","zh_CN","zh_TW"); protected List<String> newList(String item) { List <String> newList = new ArrayList<String>(); newList.add(item); return newList; } protected File localeFile(String locale) { return new File("/usr/share/locale/"+locale+"/LC_MESSAGES/rhsm.mo"); } // Data Providers *********************************************************************** @DataProvider(name="getSupportedLocalesData") public Object[][] getSupportedLocalesDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getSupportedLocalesDataAsListOfLists()); } protected List<List<Object>> getSupportedLocalesDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); for (String locale : supportedLocales) { // bugzillas Object bugzilla = null; if (locale.equals("kn")) bugzilla = new BlockedByBzBug("811294"); // Object bugzilla, String locale ll.add(Arrays.asList(new Object[] {bugzilla, locale})); } return ll; } @DataProvider(name="getTranslationFileData") public Object[][] getTranslationFileDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getTranslationFileDataAsListOfLists()); } protected List<List<Object>> getTranslationFileDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (translationFileMapForSubscriptionManager==null) return ll; for (File translationFile : translationFileMapForSubscriptionManager.keySet()) { BlockedByBzBug bugzilla = null; // Bug 824100 - pt_BR translations are outdated for subscription-manager if (translationFile.getPath().contains("/pt_BR/")) bugzilla = new BlockedByBzBug("824100"); // Bug 824184 - [ta_IN] translations for subscription-manager are missing (95% complete) if (translationFile.getPath().contains("/ta/") || translationFile.getPath().contains("/ta_IN/")) bugzilla = new BlockedByBzBug("824184"); // Bug 844369 - msgids translations are missing for several languages if (translationFile.getPath().contains("/es_ES/") || translationFile.getPath().contains("/ja/") || translationFile.getPath().contains("/as/") || translationFile.getPath().contains("/it/") || translationFile.getPath().contains("/ru/") || translationFile.getPath().contains("/zh_TW/") || translationFile.getPath().contains("/de_DE/") || translationFile.getPath().contains("/mr/") || translationFile.getPath().contains("/ko/") || translationFile.getPath().contains("/fr/") || translationFile.getPath().contains("/or/") || translationFile.getPath().contains("/te/") || translationFile.getPath().contains("/zh_CN/") || translationFile.getPath().contains("/hi/") || translationFile.getPath().contains("/gu/") || translationFile.getPath().contains("/pt_BR/") || translationFile.getPath().contains("/pa/") || translationFile.getPath().contains("/ml/") || translationFile.getPath().contains("/bn_IN/") || translationFile.getPath().contains("/kn/")) bugzilla = new BlockedByBzBug("844369"); ll.add(Arrays.asList(new Object[] {bugzilla, translationFile})); } return ll; } @Deprecated // 07/12/2012 this was the initial test created for the benefit of fsharath who further developed the test in PofilterTranslationTests.java @DataProvider(name="getTranslationFilePofilterTestData") public Object[][] getTranslationFilePofilterTestDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getTranslationFilePofilterTestDataAsListOfLists()); } @Deprecated // 07/12/2012 this was the initial test created for the benefit of fsharath who further developed the test in PofilterTranslationTests.java protected List<List<Object>> getTranslationFilePofilterTestDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (translationFileMapForSubscriptionManager==null) return ll; // see http://translate.sourceforge.net/wiki/toolkit/pofilter_tests // Critical -- can break a program // accelerators, escapes, newlines, nplurals, printf, tabs, variables, xmltags, dialogsizes // Functional -- may confuse the user // acronyms, blank, emails, filepaths, functions, gconf, kdecomments, long, musttranslatewords, notranslatewords, numbers, options, purepunc, sentencecount, short, spellcheck, urls, unchanged // Cosmetic -- make it look better // brackets, doublequoting, doublespacing, doublewords, endpunc, endwhitespace, puncspacing, simplecaps, simpleplurals, startcaps, singlequoting, startpunc, startwhitespace, validchars // Extraction -- useful mainly for extracting certain types of string // compendiumconflicts, credits, hassuggestion, isfuzzy, isreview, untranslated List<String> pofilterTests = Arrays.asList( // Critical -- can break a program "accelerators","escapes","newlines","nplurals","printf","tabs","variables","xmltags", // Functional -- may confuse the user "blank","emails","filepaths","gconf","long","notranslatewords","numbers","options","short","urls","unchanged", // Cosmetic -- make it look better "doublewords", // Extraction -- useful mainly for extracting certain types of string "untranslated"); // debugTesting pofilterTests = Arrays.asList("newlines"); for (File translationFile : translationFileMapForSubscriptionManager.keySet()) { for (String pofilterTest : pofilterTests) { BlockedByBzBug bugzilla = null; // Bug 825362 [es_ES] failed pofilter accelerator tests for subscription-manager translations if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/es_ES/")) bugzilla = new BlockedByBzBug("825362"); // Bug 825367 [zh_CN] failed pofilter accelerator tests for subscription-manager translations if (pofilterTest.equals("accelerators") && translationFile.getPath().contains("/zh_CN/")) bugzilla = new BlockedByBzBug("825367"); // Bug 825397 Many translated languages fail the pofilter newlines test if (pofilterTest.equals("newlines") && !(translationFile.getPath().contains("/zh_CN/")||translationFile.getPath().contains("/ru/")||translationFile.getPath().contains("/ja/"))) bugzilla = new BlockedByBzBug("825397"); // Bug 825393 [ml_IN][es_ES] translations should not use character ¶ for a new line. if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/ml/")) bugzilla = new BlockedByBzBug("825393"); if (pofilterTest.equals("newlines") && translationFile.getPath().contains("/es_ES/")) bugzilla = new BlockedByBzBug("825393"); ll.add(Arrays.asList(new Object[] {bugzilla, pofilterTest, translationFile})); } } return ll; } @DataProvider(name="getTranslatedCommandLineHelpData") public Object[][] getTranslatedCommandLineHelpDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getTranslatedCommandLineHelpDataAsListOfLists()); } protected List<List<Object>> getTranslatedCommandLineHelpDataAsListOfLists() { List<List<Object>> ll = new ArrayList<List<Object>>(); if (clienttasks==null) return ll; String usage,lang,module; // MODULES for (String smHelpCommand : new String[]{clienttasks.command+" -h",clienttasks.command+" --help"}) { // TODO new BlockedByBzBug("707080") // [root@jsefler-r63-server ~]# for L in en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR pt_BR ru_RU zh_CN zh_TW as_IN bn_IN hi_IN mr_IN gu_IN kn_IN ml_IN or_IN pa_IN ta_IN te_IN; do echo ""; echo "# LANG=$L.UTF-8 subscription-manager --help | grep -- --help"; LANG=$L.UTF-8 subscription-manager --help | grep -- --help; done; lang = "en_US"; usage = "(U|u)sage: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "de_DE"; usage = "(V|v)erwendung: subscription-manager MODUL-NAME [MODUL-OPTIONEN] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "es_ES"; usage = "(U|u)so: subscription-manager MÓDULO-NOMBRE [MÓDULO-OPCIONES] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); // lang = "fr_FR"; usage = "(U|u)tilisation\\s?: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null/*new BlockedByBzBug(new String[]{"707080","743734","743732"})*/, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "fr_FR"; usage = "(U|u)tilisation.*: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null/*new BlockedByBzBug(new String[]{"707080","743734","743732"})*/, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "it_IT"; usage = "(U|u)tilizzo: subscription-manager NOME-MODULO [OPZIONI-MODULO] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ja_JP"; usage = "使い方: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ko_KR"; usage = "사용법: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "pt_BR"; usage = "(U|u)so: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ru_RU"; usage = "(Ф|ф)ормат: subscription-manager ДЕЙСТВИЕ [ПАРАМЕТРЫ] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "zh_CN"; usage = "用法: subscription-manager 模块名称 [模块选项] [--help]"; ll.add(Arrays.asList(new Object[] {null/*new BlockedByBzBug(new String[]{"707080","743732"})*/, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "zh_TW"; usage = "使用方法:subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "as_IN"; usage = "ব্যৱহাৰ: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null/*new BlockedByBzBug(new String[]{"743732","750807"})*/, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "bn_IN"; usage = "ব্যবহারপ্রণালী: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "hi_IN"; usage = "प्रयोग: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "mr_IN"; usage = "(वापर|वपार): subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "gu_IN"; usage = "વપરાશ: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "kn_IN"; usage = "ಬಳಕೆ: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("811294"), lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ml_IN"; usage = "ഉപയോഗിയ്ക്കേണ്ട വിധം: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "or_IN"; usage = "ବ୍ୟବହାର ବିଧି: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "pa_IN"; usage = "ਵਰਤੋਂ: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ta_IN"; usage = "பயன்பாடு: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug("811301"), lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "te_IN"; usage = "వాడుక: subscription-manager MODULE-NAME [MODULE-OPTIONS] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); // TODO MODULE: clean // TODO MODULE: activate // TODO MODULE: facts // TODO MODULE: identity // TODO MODULE: list // TODO MODULE: refresh // MODULE: register // [root@jsefler-r63-server ~]# for L in en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR pt_BR ru_RU zh_CN zh_TW as_IN bn_IN hi_IN mr_IN gu_IN kn_IN ml_IN or_IN pa_IN ta_IN te_IN; do echo ""; echo "# LANG=$L.UTF-8 subscription-manager register --help | grep -- 'subscription-manager register'"; LANG=$L.UTF-8 subscription-manager register --help | grep -- 'subscription-manager register'; done; module = "register"; lang = "en_US"; usage = "Usage: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "de_DE"; usage = "Verwendung: subscription-manager register [OPTIONEN]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"693527","839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "es_ES"; usage = "Uso: subscription-manager register [OPCIONES]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); // lang = "fr_FR"; usage = "(U|u)tilisation\\s?: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "fr_FR"; usage = "Utilisation.*subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "it_IT"; usage = "Utilizzo: subscription-manager register [OPZIONI]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ja_JP"; usage = "使用法: subscription-manager register [オプション]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ko_KR"; usage = "사용법: subscription-manager register [옵션]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "pt_BR"; usage = "Uso: subscription-manager register [OPÇÕES]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ru_RU"; usage = "Формат: subscription-manager register [ПАРАМЕТРЫ]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "zh_CN"; usage = "用法:subscription-manager register [选项]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "zh_TW"; usage = "使用方法:subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "as_IN"; usage = "ব্যৱহাৰ: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"})/*new BlockedByBzBug(new String[]{"743732"})*/, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "bn_IN"; usage = "ব্যবহারপ্রণালী: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "hi_IN"; usage = "प्रयोग: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); //lang = "mr_IN"; usage = "(वापर|वपार): subscription-manager मॉड्युल-नाव [मॉड्युल-पर्याय] [--help]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "mr_IN"; usage = "वपार: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "gu_IN"; usage = "વપરાશ: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "kn_IN"; usage = "ಬಳಕೆ: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"811294","839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ml_IN"; usage = "ഉപയോഗിയ്ക്കേണ്ട വിധം: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); //lang = "or_IN"; usage = "ବ୍ଯବହାର ବିଧି: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {null, lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); //rhel57 rhel61 lang = "or_IN"; usage = "ଉପଯୋଗ: subscription-manager register [ବିକଳ୍ପଗୁଡ଼ିକ]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "pa_IN"; usage = "ਵਰਤੋਂ: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "ta_IN"; usage = "பயன்பாடு: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); lang = "te_IN"; usage = "వా‍డుక: subscription-manager register [OPTIONS]"; ll.add(Arrays.asList(new Object[] {new BlockedByBzBug(new String[]{"839807","845304"}), lang, smHelpCommand+" "+module, newList(usage.replaceAll("\\[", "\\\\[").replaceAll("\\]", "\\\\]")+"$")})); // TODO MODULE: subscribe // TODO MODULE: unregister // TODO MODULE: unsubscribe } return ll; } @DataProvider(name="getInvalidRegistrationWithLocalizedStringsData") public Object[][] getInvalidRegistrationWithLocalizedStringsDataAs2dArray() { return TestNGUtils.convertListOfListsTo2dArray(getInvalidRegistrationWithLocalizedStringsAsListOfLists()); } protected List<List<Object>> getInvalidRegistrationWithLocalizedStringsAsListOfLists(){ List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (servertasks==null) return ll; if (clienttasks==null) return ll; String uErrMsg = servertasks.invalidCredentialsRegexMsg(); // String lang, String username, String password, Integer exitCode, String stdoutRegex, String stderrRegex // registration test for a user who is invalid ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, uErrMsg})); // registration test for a user who with "invalid credentials" (translated) //if (!isServerOnPremises) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}), "de_DE.UTF-8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); //else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF-8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); if (sm_serverType.equals(CandlepinType.standalone)) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid Credentials"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültige Berechtigungnachweise"})); ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciales inválidas"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Informations d’identification invalides"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenziali invalide"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無効な識別情報"})); ll.add(Arrays.asList(new Object[]{null, "ko_KR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "잘못된 인증 정보"})); ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciais inválidas"})); - ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("839805"), "ru_RU.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Недопустимые учетные данные"})); // "Недопустимые реквизиты" translates to Illegal details + ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("839805"), "ru_RU.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Недопустимые реквизиты"})); // "Недопустимые реквизиты" google translates to "Illegal details"; "Недопустимые учетные данные" google translates to "Invalid Credentials" ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效证书"})); ll.add(Arrays.asList(new Object[]{null, "zh_TW.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的認證"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "as_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পৰিচয়"})); ll.add(Arrays.asList(new Object[]{null, "bn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পরিচয়"})); ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "mr_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "gu_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય શ્રેય"})); ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಪರಿಚಯಪತ್ರ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "ml_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ആധികാരികതകള്‍"})); ll.add(Arrays.asList(new Object[]{null, "or_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ପ୍ରାଧିକରଣ"})); ll.add(Arrays.asList(new Object[]{null, "pa_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਕਰੀਡੈਂਸ਼ਲ"})); ll.add(Arrays.asList(new Object[]{null, "ta_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான சான்றுகள்"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "te_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని ప్రమాణాలు"})); } else { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid username or password. To create a login, please visit https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "de_DE.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültiger Benutzername oder Passwort. Um ein Login anzulegen, besuchen Sie bitte https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "El nombre de usuario o contraseña es inválido. Para crear un nombre de usuario, por favor visite https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nom d'utilisateur ou mot de passe non valide. Pour créer une connexion, veuillez visiter https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome utente o password non valide. Per creare un login visitare https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ユーザー名かパスワードが無効です。ログインを作成するには、https://www.redhat.com/wapps/ugc/register.html に進んでください"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ko_KR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "사용자 이름 또는 암호가 잘못되었습니다. 로그인을 만들려면, https://www.redhat.com/wapps/ugc/register.html으로 이동해 주십시오."})); ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome do usuário e senha incorretos. Por favor visite https://www.redhat.com/wapps/ugc/register.html para a criação do logon."})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ru_RU.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Неверное имя пользователя или пароль. Для создания учётной записи перейдите к https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效用户名或者密码。要创建登录,请访问 https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "zh_TW.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的使用者名稱或密碼。若要建立登錄帳號,請至 https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "as_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ ব্যৱহাৰকাৰী নাম অথবা পাছৱাৰ্ড। এটা লগিন সৃষ্টি কৰিবলে, অনুগ্ৰহ কৰি চাওক https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "bn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ব্যবহারকারীর নাম অথবা পাসওয়ার্ড বৈধ নয়। লগ-ইন প্রস্তুত করার জন্য অনুগ্রহ করে https://www.redhat.com/wapps/ugc/register.html পরিদর্শন করুন"})); ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध उपयोक्तानाम या कूटशब्द. लॉगिन करने के लिए, कृपया https://www.redhat.com/wapps/ugc/register.html भ्रमण करें"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "mr_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध वापरकर्तानाव किंवा पासवर्ड. प्रवेश निर्माण करण्यासाठी, कृपया https://www.redhat.com/wapps/ugc/register.html येथे भेट द्या"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "gu_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય વપરાશકર્તાનામ અથવા પાસવર્ડ. લૉગિનને બનાવવા માટે, મહેરબાની કરીને https://www.redhat.com/wapps/ugc/register.html મુલાકાત લો"})); ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಬಳಕೆದಾರ ಹೆಸರು ಅಥವ ಗುಪ್ತಪದ. ಒಂದು ಲಾಗಿನ್ ಅನ್ನು ರಚಿಸಲು, ದಯವಿಟ್ಟು https://www.redhat.com/wapps/ugc/register.html ಗೆ ತೆರಳಿ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ml_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ഉപയോക്തൃനാമം അല്ലെങ്കില്<200d> രഹസ്യവാക്ക്. പ്രവേശനത്തിനായി, ദയവായി https://www.redhat.com/wapps/ugc/register.html സന്ദര്<200d>ശിയ്ക്കുക"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "or_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ଚାଳକନାମ କିମ୍ବା ପ୍ରବେଶ ସଂକେତ। ଗୋଟିଏ ଲଗଇନ ନିର୍ମାଣ କରିବା ପାଇଁ, ଦୟାକରି https://www.redhat.com/wapps/ugc/register.html କୁ ପରିଦର୍ଶନ କରନ୍ତୁ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "pa_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਯੂਜ਼ਰ-ਨਾਂ ਜਾਂ ਪਾਸਵਰਡ। ਲਾਗਇਨ ਬਣਾਉਣ ਲਈ, ਕਿਰਪਾ ਕਰਕੇ ਇਹ ਵੇਖੋ https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ta_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான பயனர்பெயர் அல்லது கடவுச்சொல். ஒரு உட்புகுவை உருவாக்குவதற்கு, https://www.redhat.com/wapps/ugc/register.html பார்வையிடவும்"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "te_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని వాడుకరిపేరు లేదా సంకేతపదము. లాగిన్ సృష్టించుటకు, దయచేసి https://www.redhat.com/wapps/ugc/register.html దర్శించండి"})); } // registration test for a user who has not accepted Red Hat's Terms and conditions (translated) Man, why did you do something? if (!sm_usernameWithUnacceptedTC.equals("")) { if (sm_serverType.equals(CandlepinType.hosted)) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}),"de_DE.UTF-8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF-8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); } // registration test for a user who has been disabled (translated) if (!sm_disabledUsername.equals("")) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_disabledUsername, sm_disabledPassword, 255, null,"The user has been disabled, if this is a mistake, please contact customer service."})); } // [root@jsefler-onprem-server ~]# for l in en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR pt_BR ru_RU zh_CN zh_TW as_IN bn_IN hi_IN mr_IN gu_IN kn_IN ml_IN or_IN pa_IN ta_IN te_IN; do echo ""; echo ""; echo "# LANG=$l.UTF-8 subscription-manager clean --help"; LANG=$l.UTF-8 subscription-manager clean --help; done; /* TODO reference for locales [root@jsefler-onprem03 ~]# rpm -lq subscription-manager | grep locale /usr/share/locale/as_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/bn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/de_DE/LC_MESSAGES/rhsm.mo /usr/share/locale/en_US/LC_MESSAGES/rhsm.mo /usr/share/locale/es_ES/LC_MESSAGES/rhsm.mo /usr/share/locale/fr_FR/LC_MESSAGES/rhsm.mo /usr/share/locale/gu_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/hi_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/it_IT/LC_MESSAGES/rhsm.mo /usr/share/locale/ja_JP/LC_MESSAGES/rhsm.mo /usr/share/locale/kn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/ko_KR/LC_MESSAGES/rhsm.mo /usr/share/locale/ml_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/mr_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/or_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pa_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pt_BR/LC_MESSAGES/rhsm.mo /usr/share/locale/ru_RU/LC_MESSAGES/rhsm.mo /usr/share/locale/ta_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/te_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_CN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_TW/LC_MESSAGES/rhsm.mo */ // TODO HERE IS A COMMAND FOR GETTING THE EXPECTED TRANSLATION MESSAGE STRINGS /* msgunfmt /usr/share/locale/de/LC_MESSAGES/rhsm.mo msgid "%prog [options]" msgstr "%prog [Optionen]" msgid "%s (first date of invalid entitlements)" msgstr "%s (erster Tag mit ungültigen Berechtigungen)" */ /* python script that alikins wrote to pad a language strings with _ #!/usr/bin/python import polib import sys path = sys.argv[1] pofile = polib.pofile(path) for entry in pofile: orig = entry.msgstr new = orig + "_"*40 entry.msgstr = new pofile.save(path) */ /* TODO Here is a script from alikins that will report untranslated strings #!/usr/bin/python # NEEDS polib from http://pypi.python.org/pypi/polib # or easy_install polib import glob import polib #FIXME PO_PATH = "po/" po_files = glob.glob("%s/*.po" % PO_PATH) for po_file in po_files: print print po_file p = polib.pofile(po_file) for entry in p.untranslated_entries(): for line in entry.occurrences: print "%s:%s" % (line[0], line[1]) print "\t%s" % entry.msgid for entry in p.fuzzy_entries(): for line in entry.occurrences: print "%s:%s" % (line[0], line[1]) print "\t%s" % entry.msgid */ return ll; } }
true
true
protected List<List<Object>> getInvalidRegistrationWithLocalizedStringsAsListOfLists(){ List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (servertasks==null) return ll; if (clienttasks==null) return ll; String uErrMsg = servertasks.invalidCredentialsRegexMsg(); // String lang, String username, String password, Integer exitCode, String stdoutRegex, String stderrRegex // registration test for a user who is invalid ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, uErrMsg})); // registration test for a user who with "invalid credentials" (translated) //if (!isServerOnPremises) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}), "de_DE.UTF-8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); //else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF-8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); if (sm_serverType.equals(CandlepinType.standalone)) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid Credentials"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültige Berechtigungnachweise"})); ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciales inválidas"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Informations d’identification invalides"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenziali invalide"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無効な識別情報"})); ll.add(Arrays.asList(new Object[]{null, "ko_KR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "잘못된 인증 정보"})); ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciais inválidas"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("839805"), "ru_RU.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Недопустимые учетные данные"})); // "Недопустимые реквизиты" translates to Illegal details ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效证书"})); ll.add(Arrays.asList(new Object[]{null, "zh_TW.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的認證"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "as_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পৰিচয়"})); ll.add(Arrays.asList(new Object[]{null, "bn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পরিচয়"})); ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "mr_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "gu_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય શ્રેય"})); ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಪರಿಚಯಪತ್ರ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "ml_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ആധികാരികതകള്‍"})); ll.add(Arrays.asList(new Object[]{null, "or_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ପ୍ରାଧିକରଣ"})); ll.add(Arrays.asList(new Object[]{null, "pa_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਕਰੀਡੈਂਸ਼ਲ"})); ll.add(Arrays.asList(new Object[]{null, "ta_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான சான்றுகள்"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "te_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని ప్రమాణాలు"})); } else { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid username or password. To create a login, please visit https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "de_DE.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültiger Benutzername oder Passwort. Um ein Login anzulegen, besuchen Sie bitte https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "El nombre de usuario o contraseña es inválido. Para crear un nombre de usuario, por favor visite https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nom d'utilisateur ou mot de passe non valide. Pour créer une connexion, veuillez visiter https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome utente o password non valide. Per creare un login visitare https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ユーザー名かパスワードが無効です。ログインを作成するには、https://www.redhat.com/wapps/ugc/register.html に進んでください"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ko_KR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "사용자 이름 또는 암호가 잘못되었습니다. 로그인을 만들려면, https://www.redhat.com/wapps/ugc/register.html으로 이동해 주십시오."})); ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome do usuário e senha incorretos. Por favor visite https://www.redhat.com/wapps/ugc/register.html para a criação do logon."})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ru_RU.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Неверное имя пользователя или пароль. Для создания учётной записи перейдите к https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效用户名或者密码。要创建登录,请访问 https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "zh_TW.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的使用者名稱或密碼。若要建立登錄帳號,請至 https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "as_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ ব্যৱহাৰকাৰী নাম অথবা পাছৱাৰ্ড। এটা লগিন সৃষ্টি কৰিবলে, অনুগ্ৰহ কৰি চাওক https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "bn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ব্যবহারকারীর নাম অথবা পাসওয়ার্ড বৈধ নয়। লগ-ইন প্রস্তুত করার জন্য অনুগ্রহ করে https://www.redhat.com/wapps/ugc/register.html পরিদর্শন করুন"})); ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध उपयोक्तानाम या कूटशब्द. लॉगिन करने के लिए, कृपया https://www.redhat.com/wapps/ugc/register.html भ्रमण करें"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "mr_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध वापरकर्तानाव किंवा पासवर्ड. प्रवेश निर्माण करण्यासाठी, कृपया https://www.redhat.com/wapps/ugc/register.html येथे भेट द्या"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "gu_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય વપરાશકર્તાનામ અથવા પાસવર્ડ. લૉગિનને બનાવવા માટે, મહેરબાની કરીને https://www.redhat.com/wapps/ugc/register.html મુલાકાત લો"})); ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಬಳಕೆದಾರ ಹೆಸರು ಅಥವ ಗುಪ್ತಪದ. ಒಂದು ಲಾಗಿನ್ ಅನ್ನು ರಚಿಸಲು, ದಯವಿಟ್ಟು https://www.redhat.com/wapps/ugc/register.html ಗೆ ತೆರಳಿ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ml_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ഉപയോക്തൃനാമം അല്ലെങ്കില്<200d> രഹസ്യവാക്ക്. പ്രവേശനത്തിനായി, ദയവായി https://www.redhat.com/wapps/ugc/register.html സന്ദര്<200d>ശിയ്ക്കുക"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "or_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ଚାଳକନାମ କିମ୍ବା ପ୍ରବେଶ ସଂକେତ। ଗୋଟିଏ ଲଗଇନ ନିର୍ମାଣ କରିବା ପାଇଁ, ଦୟାକରି https://www.redhat.com/wapps/ugc/register.html କୁ ପରିଦର୍ଶନ କରନ୍ତୁ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "pa_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਯੂਜ਼ਰ-ਨਾਂ ਜਾਂ ਪਾਸਵਰਡ। ਲਾਗਇਨ ਬਣਾਉਣ ਲਈ, ਕਿਰਪਾ ਕਰਕੇ ਇਹ ਵੇਖੋ https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ta_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான பயனர்பெயர் அல்லது கடவுச்சொல். ஒரு உட்புகுவை உருவாக்குவதற்கு, https://www.redhat.com/wapps/ugc/register.html பார்வையிடவும்"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "te_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని వాడుకరిపేరు లేదా సంకేతపదము. లాగిన్ సృష్టించుటకు, దయచేసి https://www.redhat.com/wapps/ugc/register.html దర్శించండి"})); } // registration test for a user who has not accepted Red Hat's Terms and conditions (translated) Man, why did you do something? if (!sm_usernameWithUnacceptedTC.equals("")) { if (sm_serverType.equals(CandlepinType.hosted)) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}),"de_DE.UTF-8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF-8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); } // registration test for a user who has been disabled (translated) if (!sm_disabledUsername.equals("")) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_disabledUsername, sm_disabledPassword, 255, null,"The user has been disabled, if this is a mistake, please contact customer service."})); } // [root@jsefler-onprem-server ~]# for l in en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR pt_BR ru_RU zh_CN zh_TW as_IN bn_IN hi_IN mr_IN gu_IN kn_IN ml_IN or_IN pa_IN ta_IN te_IN; do echo ""; echo ""; echo "# LANG=$l.UTF-8 subscription-manager clean --help"; LANG=$l.UTF-8 subscription-manager clean --help; done; /* TODO reference for locales [root@jsefler-onprem03 ~]# rpm -lq subscription-manager | grep locale /usr/share/locale/as_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/bn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/de_DE/LC_MESSAGES/rhsm.mo /usr/share/locale/en_US/LC_MESSAGES/rhsm.mo /usr/share/locale/es_ES/LC_MESSAGES/rhsm.mo /usr/share/locale/fr_FR/LC_MESSAGES/rhsm.mo /usr/share/locale/gu_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/hi_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/it_IT/LC_MESSAGES/rhsm.mo /usr/share/locale/ja_JP/LC_MESSAGES/rhsm.mo /usr/share/locale/kn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/ko_KR/LC_MESSAGES/rhsm.mo /usr/share/locale/ml_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/mr_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/or_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pa_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pt_BR/LC_MESSAGES/rhsm.mo /usr/share/locale/ru_RU/LC_MESSAGES/rhsm.mo /usr/share/locale/ta_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/te_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_CN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_TW/LC_MESSAGES/rhsm.mo */ // TODO HERE IS A COMMAND FOR GETTING THE EXPECTED TRANSLATION MESSAGE STRINGS /* msgunfmt /usr/share/locale/de/LC_MESSAGES/rhsm.mo msgid "%prog [options]" msgstr "%prog [Optionen]" msgid "%s (first date of invalid entitlements)" msgstr "%s (erster Tag mit ungültigen Berechtigungen)" */ /* python script that alikins wrote to pad a language strings with _ #!/usr/bin/python import polib import sys path = sys.argv[1] pofile = polib.pofile(path) for entry in pofile: orig = entry.msgstr new = orig + "_"*40 entry.msgstr = new pofile.save(path) */ /* TODO Here is a script from alikins that will report untranslated strings #!/usr/bin/python # NEEDS polib from http://pypi.python.org/pypi/polib # or easy_install polib import glob import polib #FIXME PO_PATH = "po/" po_files = glob.glob("%s/*.po" % PO_PATH) for po_file in po_files: print print po_file p = polib.pofile(po_file) for entry in p.untranslated_entries(): for line in entry.occurrences: print "%s:%s" % (line[0], line[1]) print "\t%s" % entry.msgid for entry in p.fuzzy_entries(): for line in entry.occurrences: print "%s:%s" % (line[0], line[1]) print "\t%s" % entry.msgid */ return ll; } }
protected List<List<Object>> getInvalidRegistrationWithLocalizedStringsAsListOfLists(){ List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll; if (servertasks==null) return ll; if (clienttasks==null) return ll; String uErrMsg = servertasks.invalidCredentialsRegexMsg(); // String lang, String username, String password, Integer exitCode, String stdoutRegex, String stderrRegex // registration test for a user who is invalid ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, uErrMsg})); // registration test for a user who with "invalid credentials" (translated) //if (!isServerOnPremises) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}), "de_DE.UTF-8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); //else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF-8", clientusername+getRandInt(), clientpassword+getRandInt(), 255, null, isServerOnPremises? "Ungültige Berechtigungnachweise"/*"Ungültige Mandate"*//*"Ungültiger Benutzername oder Kennwort"*/:"Ungültiger Benutzername oder Kennwort. So erstellen Sie ein Login, besuchen Sie bitte https://www.redhat.com/wapps/ugc"})); if (sm_serverType.equals(CandlepinType.standalone)) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid Credentials"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültige Berechtigungnachweise"})); ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciales inválidas"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Informations d’identification invalides"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenziali invalide"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無効な識別情報"})); ll.add(Arrays.asList(new Object[]{null, "ko_KR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "잘못된 인증 정보"})); ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Credenciais inválidas"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("839805"), "ru_RU.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Недопустимые реквизиты"})); // "Недопустимые реквизиты" google translates to "Illegal details"; "Недопустимые учетные данные" google translates to "Invalid Credentials" ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效证书"})); ll.add(Arrays.asList(new Object[]{null, "zh_TW.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的認證"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "as_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পৰিচয়"})); ll.add(Arrays.asList(new Object[]{null, "bn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ পরিচয়"})); ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "mr_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध श्रेय"})); ll.add(Arrays.asList(new Object[]{null, "gu_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય શ્રેય"})); ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಪರಿಚಯಪತ್ರ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "ml_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ആധികാരികതകള്‍"})); ll.add(Arrays.asList(new Object[]{null, "or_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ପ୍ରାଧିକରଣ"})); ll.add(Arrays.asList(new Object[]{null, "pa_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਕਰੀਡੈਂਸ਼ਲ"})); ll.add(Arrays.asList(new Object[]{null, "ta_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான சான்றுகள்"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("683914"), "te_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని ప్రమాణాలు"})); } else { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Invalid username or password. To create a login, please visit https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "de_DE.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Ungültiger Benutzername oder Passwort. Um ein Login anzulegen, besuchen Sie bitte https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "es_ES.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "El nombre de usuario o contraseña es inválido. Para crear un nombre de usuario, por favor visite https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "fr_FR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nom d'utilisateur ou mot de passe non valide. Pour créer une connexion, veuillez visiter https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "it_IT.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome utente o password non valide. Per creare un login visitare https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "ja_JP.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ユーザー名かパスワードが無効です。ログインを作成するには、https://www.redhat.com/wapps/ugc/register.html に進んでください"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ko_KR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "사용자 이름 또는 암호가 잘못되었습니다. 로그인을 만들려면, https://www.redhat.com/wapps/ugc/register.html으로 이동해 주십시오."})); ll.add(Arrays.asList(new Object[]{null, "pt_BR.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Nome do usuário e senha incorretos. Por favor visite https://www.redhat.com/wapps/ugc/register.html para a criação do logon."})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ru_RU.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "Неверное имя пользователя или пароль. Для создания учётной записи перейдите к https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{null, "zh_CN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "无效用户名或者密码。要创建登录,请访问 https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "zh_TW.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "無效的使用者名稱或密碼。若要建立登錄帳號,請至 https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "as_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "অবৈধ ব্যৱহাৰকাৰী নাম অথবা পাছৱাৰ্ড। এটা লগিন সৃষ্টি কৰিবলে, অনুগ্ৰহ কৰি চাওক https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "bn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ব্যবহারকারীর নাম অথবা পাসওয়ার্ড বৈধ নয়। লগ-ইন প্রস্তুত করার জন্য অনুগ্রহ করে https://www.redhat.com/wapps/ugc/register.html পরিদর্শন করুন"})); ll.add(Arrays.asList(new Object[]{null, "hi_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध उपयोक्तानाम या कूटशब्द. लॉगिन करने के लिए, कृपया https://www.redhat.com/wapps/ugc/register.html भ्रमण करें"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "mr_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "अवैध वापरकर्तानाव किंवा पासवर्ड. प्रवेश निर्माण करण्यासाठी, कृपया https://www.redhat.com/wapps/ugc/register.html येथे भेट द्या"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "gu_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "અયોગ્ય વપરાશકર્તાનામ અથવા પાસવર્ડ. લૉગિનને બનાવવા માટે, મહેરબાની કરીને https://www.redhat.com/wapps/ugc/register.html મુલાકાત લો"})); ll.add(Arrays.asList(new Object[]{null, "kn_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ಅಮಾನ್ಯವಾದ ಬಳಕೆದಾರ ಹೆಸರು ಅಥವ ಗುಪ್ತಪದ. ಒಂದು ಲಾಗಿನ್ ಅನ್ನು ರಚಿಸಲು, ದಯವಿಟ್ಟು https://www.redhat.com/wapps/ugc/register.html ಗೆ ತೆರಳಿ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ml_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "തെറ്റായ ഉപയോക്തൃനാമം അല്ലെങ്കില്<200d> രഹസ്യവാക്ക്. പ്രവേശനത്തിനായി, ദയവായി https://www.redhat.com/wapps/ugc/register.html സന്ദര്<200d>ശിയ്ക്കുക"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "or_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ଅବୈଧ ଚାଳକନାମ କିମ୍ବା ପ୍ରବେଶ ସଂକେତ। ଗୋଟିଏ ଲଗଇନ ନିର୍ମାଣ କରିବା ପାଇଁ, ଦୟାକରି https://www.redhat.com/wapps/ugc/register.html କୁ ପରିଦର୍ଶନ କରନ୍ତୁ"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "pa_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "ਗਲਤ ਯੂਜ਼ਰ-ਨਾਂ ਜਾਂ ਪਾਸਵਰਡ। ਲਾਗਇਨ ਬਣਾਉਣ ਲਈ, ਕਿਰਪਾ ਕਰਕੇ ਇਹ ਵੇਖੋ https://www.redhat.com/wapps/ugc/register.html"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "ta_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "தவறான பயனர்பெயர் அல்லது கடவுச்சொல். ஒரு உட்புகுவை உருவாக்குவதற்கு, https://www.redhat.com/wapps/ugc/register.html பார்வையிடவும்"})); ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("706197"), "te_IN.UTF-8", sm_clientUsername+getRandInt(), sm_clientPassword+getRandInt(), 255, null, "చెల్లని వాడుకరిపేరు లేదా సంకేతపదము. లాగిన్ సృష్టించుటకు, దయచేసి https://www.redhat.com/wapps/ugc/register.html దర్శించండి"})); } // registration test for a user who has not accepted Red Hat's Terms and conditions (translated) Man, why did you do something? if (!sm_usernameWithUnacceptedTC.equals("")) { if (sm_serverType.equals(CandlepinType.hosted)) ll.add(Arrays.asList(new Object[]{new BlockedByBzBug(new String[]{"615362","642805"}),"de_DE.UTF-8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); else ll.add(Arrays.asList(new Object[]{new BlockedByBzBug("615362"), "de_DE.UTF-8", sm_usernameWithUnacceptedTC, sm_passwordWithUnacceptedTC, 255, null, "Mensch, warum hast du auch etwas zu tun?? Bitte besuchen https://www.redhat.com/wapps/ugc!!!!!!!!!!!!!!!!!!"})); } // registration test for a user who has been disabled (translated) if (!sm_disabledUsername.equals("")) { ll.add(Arrays.asList(new Object[]{null, "en_US.UTF-8", sm_disabledUsername, sm_disabledPassword, 255, null,"The user has been disabled, if this is a mistake, please contact customer service."})); } // [root@jsefler-onprem-server ~]# for l in en_US de_DE es_ES fr_FR it_IT ja_JP ko_KR pt_BR ru_RU zh_CN zh_TW as_IN bn_IN hi_IN mr_IN gu_IN kn_IN ml_IN or_IN pa_IN ta_IN te_IN; do echo ""; echo ""; echo "# LANG=$l.UTF-8 subscription-manager clean --help"; LANG=$l.UTF-8 subscription-manager clean --help; done; /* TODO reference for locales [root@jsefler-onprem03 ~]# rpm -lq subscription-manager | grep locale /usr/share/locale/as_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/bn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/de_DE/LC_MESSAGES/rhsm.mo /usr/share/locale/en_US/LC_MESSAGES/rhsm.mo /usr/share/locale/es_ES/LC_MESSAGES/rhsm.mo /usr/share/locale/fr_FR/LC_MESSAGES/rhsm.mo /usr/share/locale/gu_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/hi_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/it_IT/LC_MESSAGES/rhsm.mo /usr/share/locale/ja_JP/LC_MESSAGES/rhsm.mo /usr/share/locale/kn_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/ko_KR/LC_MESSAGES/rhsm.mo /usr/share/locale/ml_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/mr_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/or_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pa_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/pt_BR/LC_MESSAGES/rhsm.mo /usr/share/locale/ru_RU/LC_MESSAGES/rhsm.mo /usr/share/locale/ta_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/te_IN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_CN/LC_MESSAGES/rhsm.mo /usr/share/locale/zh_TW/LC_MESSAGES/rhsm.mo */ // TODO HERE IS A COMMAND FOR GETTING THE EXPECTED TRANSLATION MESSAGE STRINGS /* msgunfmt /usr/share/locale/de/LC_MESSAGES/rhsm.mo msgid "%prog [options]" msgstr "%prog [Optionen]" msgid "%s (first date of invalid entitlements)" msgstr "%s (erster Tag mit ungültigen Berechtigungen)" */ /* python script that alikins wrote to pad a language strings with _ #!/usr/bin/python import polib import sys path = sys.argv[1] pofile = polib.pofile(path) for entry in pofile: orig = entry.msgstr new = orig + "_"*40 entry.msgstr = new pofile.save(path) */ /* TODO Here is a script from alikins that will report untranslated strings #!/usr/bin/python # NEEDS polib from http://pypi.python.org/pypi/polib # or easy_install polib import glob import polib #FIXME PO_PATH = "po/" po_files = glob.glob("%s/*.po" % PO_PATH) for po_file in po_files: print print po_file p = polib.pofile(po_file) for entry in p.untranslated_entries(): for line in entry.occurrences: print "%s:%s" % (line[0], line[1]) print "\t%s" % entry.msgid for entry in p.fuzzy_entries(): for line in entry.occurrences: print "%s:%s" % (line[0], line[1]) print "\t%s" % entry.msgid */ return ll; } }
diff --git a/photoviewer/src/com/android/ex/photo/PhotoViewActivity.java b/photoviewer/src/com/android/ex/photo/PhotoViewActivity.java index aa8029e..1ba81a8 100644 --- a/photoviewer/src/com/android/ex/photo/PhotoViewActivity.java +++ b/photoviewer/src/com/android/ex/photo/PhotoViewActivity.java @@ -1,543 +1,541 @@ /* * Copyright (C) 2011 Google Inc. * Licensed to The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ex.photo; import android.app.ActionBar; import android.app.ActionBar.OnMenuVisibilityListener; import android.app.Activity; import android.app.ActivityManager; import android.app.Fragment; import android.app.LoaderManager.LoaderCallbacks; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import com.android.ex.photo.PhotoViewPager.InterceptType; import com.android.ex.photo.PhotoViewPager.OnInterceptTouchListener; import com.android.ex.photo.adapters.BaseFragmentPagerAdapter.OnFragmentPagerListener; import com.android.ex.photo.adapters.PhotoPagerAdapter; import com.android.ex.photo.fragments.PhotoViewFragment; import com.android.ex.photo.loaders.PhotoPagerLoader; import com.android.ex.photo.provider.PhotoContract; import java.util.HashSet; import java.util.Set; /** * Activity to view the contents of an album. */ public class PhotoViewActivity extends Activity implements LoaderCallbacks<Cursor>, OnPageChangeListener, OnInterceptTouchListener, OnFragmentPagerListener, OnMenuVisibilityListener { /** * Listener to be invoked for screen events. */ public static interface OnScreenListener { /** * The full screen state has changed. */ public void onFullScreenChanged(boolean fullScreen); /** * A new view has been activated and the previous view de-activated. */ public void onViewActivated(); /** * Called when a right-to-left touch move intercept is about to occur. * * @param origX the raw x coordinate of the initial touch * @param origY the raw y coordinate of the initial touch * @return {@code true} if the touch should be intercepted. */ public boolean onInterceptMoveLeft(float origX, float origY); /** * Called when a left-to-right touch move intercept is about to occur. * * @param origX the raw x coordinate of the initial touch * @param origY the raw y coordinate of the initial touch * @return {@code true} if the touch should be intercepted. */ public boolean onInterceptMoveRight(float origX, float origY); } public static interface CursorChangedListener { /** * Called when the cursor that contains the photo list data * is updated. Note that there is no guarantee that the cursor * will be at the proper position. * @param cursor the cursor containing the photo list data */ public void onCursorChanged(Cursor cursor); } private final static String STATE_ITEM_KEY = "com.google.android.apps.plus.PhotoViewFragment.ITEM"; private final static String STATE_FULLSCREEN_KEY = "com.google.android.apps.plus.PhotoViewFragment.FULLSCREEN"; private static final int LOADER_PHOTO_LIST = 1; /** Count used when the real photo count is unknown [but, may be determined] */ public static final int ALBUM_COUNT_UNKNOWN = -1; /** Argument key for the dialog message */ public static final String KEY_MESSAGE = "dialog_message"; public static int sMemoryClass; /** The URI of the photos we're viewing; may be {@code null} */ private String mPhotosUri; /** The index of the currently viewed photo */ private int mPhotoIndex; /** The query projection to use; may be {@code null} */ private String[] mProjection; /** The name of the particular photo being viewed. */ private String mPhotoName; /** The total number of photos; only valid if {@link #mIsEmpty} is {@code false}. */ private int mAlbumCount = ALBUM_COUNT_UNKNOWN; /** {@code true} if the view is empty. Otherwise, {@code false}. */ private boolean mIsEmpty; /** The main pager; provides left/right swipe between photos */ private PhotoViewPager mViewPager; /** Adapter to create pager views */ private PhotoPagerAdapter mAdapter; /** Whether or not we're in "full screen" mode */ private boolean mFullScreen; /** The set of listeners wanting full screen state */ private Set<OnScreenListener> mScreenListeners = new HashSet<OnScreenListener>(); /** The set of listeners wanting full screen state */ private Set<CursorChangedListener> mCursorListeners = new HashSet<CursorChangedListener>(); /** When {@code true}, restart the loader when the activity becomes active */ private boolean mRestartLoader; /** Whether or not this activity is paused */ private boolean mIsPaused = true; private Handler mActionBarHideHandler; // TODO Find a better way to do this. We basically want the activity to display the // "loading..." progress until the fragment takes over and shows it's own "loading..." // progress [located in photo_header_view.xml]. We could potentially have all status displayed // by the activity, but, that gets tricky when it comes to screen rotation. For now, we // track the loading by this variable which is fragile and may cause phantom "loading..." // text. private long mActionBarHideDelayTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActivityManager mgr = (ActivityManager) getApplicationContext(). getSystemService(Activity.ACTIVITY_SERVICE); sMemoryClass = mgr.getMemoryClass(); Intent mIntent = getIntent(); int currentItem = -1; if (savedInstanceState != null) { currentItem = savedInstanceState.getInt(STATE_ITEM_KEY, -1); mFullScreen = savedInstanceState.getBoolean(STATE_FULLSCREEN_KEY, false); } // album name; if not set, use a default name if (mIntent.hasExtra(Intents.EXTRA_PHOTO_NAME)) { mPhotoName = mIntent.getStringExtra(Intents.EXTRA_PHOTO_NAME); - } else { - mPhotoName = getResources().getString(R.string.photo_view_default_title); } // uri of the photos to view; optional if (mIntent.hasExtra(Intents.EXTRA_PHOTOS_URI)) { mPhotosUri = mIntent.getStringExtra(Intents.EXTRA_PHOTOS_URI); } // projection for the query; optional // I.f not set, the default projection is used. // This projection must include the columns from the default projection. if (mIntent.hasExtra(Intents.EXTRA_PROJECTION)) { mProjection = mIntent.getStringArrayExtra(Intents.EXTRA_PROJECTION); } else { mProjection = null; } // Set the current item from the intent if wasn't in the saved instance if (mIntent.hasExtra(Intents.EXTRA_PHOTO_INDEX) && currentItem < 0) { currentItem = mIntent.getIntExtra(Intents.EXTRA_PHOTO_INDEX, -1); } mPhotoIndex = currentItem; setContentView(R.layout.photo_activity_view); // Create the adapter and add the view pager mAdapter = new PhotoPagerAdapter(this, getFragmentManager(), null); mAdapter.setFragmentPagerListener(this); mViewPager = (PhotoViewPager) findViewById(R.id.photo_view_pager); mViewPager.setAdapter(mAdapter); mViewPager.setOnPageChangeListener(this); mViewPager.setOnInterceptTouchListener(this); // Kick off the loader getLoaderManager().initLoader(LOADER_PHOTO_LIST, null, this); final ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); mActionBarHideDelayTime = getResources().getInteger( R.integer.action_bar_delay_time_in_millis); actionBar.addOnMenuVisibilityListener(this); mActionBarHideHandler = new Handler(); } @Override protected void onResume() { super.onResume(); setFullScreen(mFullScreen, false); mIsPaused = false; if (mRestartLoader) { mRestartLoader = false; getLoaderManager().restartLoader(LOADER_PHOTO_LIST, null, this); } } @Override protected void onPause() { mIsPaused = true; super.onPause(); } @Override public void onBackPressed() { // If in full screen mode, toggle mode & eat the 'back' if (mFullScreen) { toggleFullScreen(); } else { super.onBackPressed(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_ITEM_KEY, mViewPager.getCurrentItem()); outState.putBoolean(STATE_FULLSCREEN_KEY, mFullScreen); } public void addScreenListener(OnScreenListener listener) { mScreenListeners.add(listener); } public void removeScreenListener(OnScreenListener listener) { mScreenListeners.remove(listener); } public synchronized void addCursorListener(CursorChangedListener listener) { mCursorListeners.add(listener); } public synchronized void removeCursorListener(CursorChangedListener listener) { mCursorListeners.remove(listener); } public boolean isFragmentFullScreen(Fragment fragment) { if (mViewPager == null || mAdapter == null || mAdapter.getCount() == 0) { return mFullScreen; } return mFullScreen || (mViewPager.getCurrentItem() != mAdapter.getItemPosition(fragment)); } public void toggleFullScreen() { setFullScreen(!mFullScreen, true); } public void onPhotoRemoved(long photoId) { final Cursor data = mAdapter.getCursor(); if (data == null) { // Huh?! How would this happen? return; } final int dataCount = data.getCount(); if (dataCount <= 1) { finish(); return; } getLoaderManager().restartLoader(LOADER_PHOTO_LIST, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (id == LOADER_PHOTO_LIST) { return new PhotoPagerLoader(this, Uri.parse(mPhotosUri), mProjection); } return null; } @Override public void onLoadFinished(final Loader<Cursor> loader, final Cursor data) { final int id = loader.getId(); if (id == LOADER_PHOTO_LIST) { if (data == null || data.getCount() == 0) { mIsEmpty = true; } else { mAlbumCount = data.getCount(); // Cannot do this directly; need to be out of the loader new Handler().post(new Runnable() { @Override public void run() { // We're paused; don't do anything now, we'll get re-invoked // when the activity becomes active again if (mIsPaused) { mRestartLoader = true; return; } mIsEmpty = false; // set the selected photo int itemIndex = mPhotoIndex; // Use an index of 0 if the index wasn't specified or couldn't be found if (itemIndex < 0) { itemIndex = 0; } mAdapter.swapCursor(data); notifyCursorListeners(data); mViewPager.setCurrentItem(itemIndex, false); setViewActivated(); } }); } } } private synchronized void notifyCursorListeners(Cursor data) { // tell all of the objects listening for cursor changes // that the cursor has changed for (CursorChangedListener listener : mCursorListeners) { listener.onCursorChanged(data); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mPhotoIndex = position; setViewActivated(); } @Override public void onPageScrollStateChanged(int state) { } @Override public void onPageActivated(Fragment fragment) { setViewActivated(); } public boolean isFragmentActive(Fragment fragment) { if (mViewPager == null || mAdapter == null) { return false; } return mViewPager.getCurrentItem() == mAdapter.getItemPosition(fragment); } public void onFragmentVisible(PhotoViewFragment fragment) { updateActionBar(fragment); } @Override public InterceptType onTouchIntercept(float origX, float origY) { boolean interceptLeft = false; boolean interceptRight = false; for (OnScreenListener listener : mScreenListeners) { if (!interceptLeft) { interceptLeft = listener.onInterceptMoveLeft(origX, origY); } if (!interceptRight) { interceptRight = listener.onInterceptMoveRight(origX, origY); } listener.onViewActivated(); } if (interceptLeft) { if (interceptRight) { return InterceptType.BOTH; } return InterceptType.LEFT; } else if (interceptRight) { return InterceptType.RIGHT; } return InterceptType.NONE; } /** * Updates the title bar according to the value of {@link #mFullScreen}. */ private void setFullScreen(boolean fullScreen, boolean setDelayedRunnable) { final boolean fullScreenChanged = (fullScreen != mFullScreen); mFullScreen = fullScreen; if (mFullScreen) { setLightsOutMode(true); cancelActionBarHideRunnable(); } else { setLightsOutMode(false); if (setDelayedRunnable) { postActionBarHideRunnableWithDelay(); } } if (fullScreenChanged) { for (OnScreenListener listener : mScreenListeners) { listener.onFullScreenChanged(mFullScreen); } } } private void postActionBarHideRunnableWithDelay() { mActionBarHideHandler.postDelayed(mActionBarHideRunnable, mActionBarHideDelayTime); } private void cancelActionBarHideRunnable() { mActionBarHideHandler.removeCallbacks(mActionBarHideRunnable); } private void setLightsOutMode(boolean enabled) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { int flags = enabled ? View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE : View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; // using mViewPager since we have it and we need a view mViewPager.setSystemUiVisibility(flags); } else { final ActionBar actionBar = getActionBar(); if (enabled) { actionBar.hide(); } else { actionBar.show(); } int flags = enabled ? View.SYSTEM_UI_FLAG_LOW_PROFILE : View.SYSTEM_UI_FLAG_VISIBLE; mViewPager.setSystemUiVisibility(flags); } } private Runnable mActionBarHideRunnable = new Runnable() { @Override public void run() { PhotoViewActivity.this.setLightsOutMode(true); } }; public void setViewActivated() { for (OnScreenListener listener : mScreenListeners) { listener.onViewActivated(); } } /** * Adjusts the activity title and subtitle to reflect the photo name and count. */ protected void updateActionBar(PhotoViewFragment fragment) { final int position = mViewPager.getCurrentItem() + 1; final String subtitle; final boolean hasAlbumCount = mAlbumCount >= 0; final Cursor cursor = getCursorAtProperPosition(); if (cursor != null) { final int photoNameIndex = cursor.getColumnIndex(PhotoContract.PhotoViewColumns.NAME); mPhotoName = cursor.getString(photoNameIndex); } if (mIsEmpty || !hasAlbumCount || position <= 0) { subtitle = null; } else { subtitle = getResources().getString(R.string.photo_view_count, position, mAlbumCount); } final ActionBar actionBar = getActionBar(); actionBar.setTitle(mPhotoName); actionBar.setSubtitle(subtitle); } /** * Utility method that will return the cursor that contains the data * at the current position so that it refers to the current image on screen. * @return the cursor at the current position or * null if no cursor exists or if the {@link PhotoViewPager} is null. */ public Cursor getCursorAtProperPosition() { if (mViewPager == null) { return null; } final int position = mViewPager.getCurrentItem(); final Cursor cursor = mAdapter.getCursor(); if (cursor == null) { return null; } cursor.moveToPosition(position); return cursor; } public Cursor getCursor() { return (mAdapter == null) ? null : mAdapter.getCursor(); } @Override public void onMenuVisibilityChanged(boolean isVisible) { if (isVisible) { cancelActionBarHideRunnable(); } else { postActionBarHideRunnableWithDelay(); } } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActivityManager mgr = (ActivityManager) getApplicationContext(). getSystemService(Activity.ACTIVITY_SERVICE); sMemoryClass = mgr.getMemoryClass(); Intent mIntent = getIntent(); int currentItem = -1; if (savedInstanceState != null) { currentItem = savedInstanceState.getInt(STATE_ITEM_KEY, -1); mFullScreen = savedInstanceState.getBoolean(STATE_FULLSCREEN_KEY, false); } // album name; if not set, use a default name if (mIntent.hasExtra(Intents.EXTRA_PHOTO_NAME)) { mPhotoName = mIntent.getStringExtra(Intents.EXTRA_PHOTO_NAME); } else { mPhotoName = getResources().getString(R.string.photo_view_default_title); } // uri of the photos to view; optional if (mIntent.hasExtra(Intents.EXTRA_PHOTOS_URI)) { mPhotosUri = mIntent.getStringExtra(Intents.EXTRA_PHOTOS_URI); } // projection for the query; optional // I.f not set, the default projection is used. // This projection must include the columns from the default projection. if (mIntent.hasExtra(Intents.EXTRA_PROJECTION)) { mProjection = mIntent.getStringArrayExtra(Intents.EXTRA_PROJECTION); } else { mProjection = null; } // Set the current item from the intent if wasn't in the saved instance if (mIntent.hasExtra(Intents.EXTRA_PHOTO_INDEX) && currentItem < 0) { currentItem = mIntent.getIntExtra(Intents.EXTRA_PHOTO_INDEX, -1); } mPhotoIndex = currentItem; setContentView(R.layout.photo_activity_view); // Create the adapter and add the view pager mAdapter = new PhotoPagerAdapter(this, getFragmentManager(), null); mAdapter.setFragmentPagerListener(this); mViewPager = (PhotoViewPager) findViewById(R.id.photo_view_pager); mViewPager.setAdapter(mAdapter); mViewPager.setOnPageChangeListener(this); mViewPager.setOnInterceptTouchListener(this); // Kick off the loader getLoaderManager().initLoader(LOADER_PHOTO_LIST, null, this); final ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); mActionBarHideDelayTime = getResources().getInteger( R.integer.action_bar_delay_time_in_millis); actionBar.addOnMenuVisibilityListener(this); mActionBarHideHandler = new Handler(); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActivityManager mgr = (ActivityManager) getApplicationContext(). getSystemService(Activity.ACTIVITY_SERVICE); sMemoryClass = mgr.getMemoryClass(); Intent mIntent = getIntent(); int currentItem = -1; if (savedInstanceState != null) { currentItem = savedInstanceState.getInt(STATE_ITEM_KEY, -1); mFullScreen = savedInstanceState.getBoolean(STATE_FULLSCREEN_KEY, false); } // album name; if not set, use a default name if (mIntent.hasExtra(Intents.EXTRA_PHOTO_NAME)) { mPhotoName = mIntent.getStringExtra(Intents.EXTRA_PHOTO_NAME); } // uri of the photos to view; optional if (mIntent.hasExtra(Intents.EXTRA_PHOTOS_URI)) { mPhotosUri = mIntent.getStringExtra(Intents.EXTRA_PHOTOS_URI); } // projection for the query; optional // I.f not set, the default projection is used. // This projection must include the columns from the default projection. if (mIntent.hasExtra(Intents.EXTRA_PROJECTION)) { mProjection = mIntent.getStringArrayExtra(Intents.EXTRA_PROJECTION); } else { mProjection = null; } // Set the current item from the intent if wasn't in the saved instance if (mIntent.hasExtra(Intents.EXTRA_PHOTO_INDEX) && currentItem < 0) { currentItem = mIntent.getIntExtra(Intents.EXTRA_PHOTO_INDEX, -1); } mPhotoIndex = currentItem; setContentView(R.layout.photo_activity_view); // Create the adapter and add the view pager mAdapter = new PhotoPagerAdapter(this, getFragmentManager(), null); mAdapter.setFragmentPagerListener(this); mViewPager = (PhotoViewPager) findViewById(R.id.photo_view_pager); mViewPager.setAdapter(mAdapter); mViewPager.setOnPageChangeListener(this); mViewPager.setOnInterceptTouchListener(this); // Kick off the loader getLoaderManager().initLoader(LOADER_PHOTO_LIST, null, this); final ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); mActionBarHideDelayTime = getResources().getInteger( R.integer.action_bar_delay_time_in_millis); actionBar.addOnMenuVisibilityListener(this); mActionBarHideHandler = new Handler(); }
diff --git a/src/org/mozilla/javascript/Context.java b/src/org/mozilla/javascript/Context.java index 456e115a..e397ad5a 100644 --- a/src/org/mozilla/javascript/Context.java +++ b/src/org/mozilla/javascript/Context.java @@ -1,2638 +1,2638 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Bob Jervis * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ // API class package org.mozilla.javascript; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.CharArrayWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Hashtable; import java.util.Locale; import org.mozilla.javascript.debug.DebuggableScript; import org.mozilla.javascript.debug.Debugger; import org.mozilla.javascript.xml.XMLLib; /** * This class represents the runtime context of an executing script. * * Before executing a script, an instance of Context must be created * and associated with the thread that will be executing the script. * The Context will be used to store information about the executing * of the script such as the call stack. Contexts are associated with * the current thread using the {@link #call(ContextAction)} * or {@link #enter()} methods.<p> * * Different forms of script execution are supported. Scripts may be * evaluated from the source directly, or first compiled and then later * executed. Interactive execution is also supported.<p> * * Some aspects of script execution, such as type conversions and * object creation, may be accessed directly through methods of * Context. * * @see Scriptable * @author Norris Boyd * @author Brendan Eich */ public class Context { /** * Language versions. * * All integral values are reserved for future version numbers. */ /** * The unknown version. */ public static final int VERSION_UNKNOWN = -1; /** * The default version. */ public static final int VERSION_DEFAULT = 0; /** * JavaScript 1.0 */ public static final int VERSION_1_0 = 100; /** * JavaScript 1.1 */ public static final int VERSION_1_1 = 110; /** * JavaScript 1.2 */ public static final int VERSION_1_2 = 120; /** * JavaScript 1.3 */ public static final int VERSION_1_3 = 130; /** * JavaScript 1.4 */ public static final int VERSION_1_4 = 140; /** * JavaScript 1.5 */ public static final int VERSION_1_5 = 150; /** * JavaScript 1.6 */ public static final int VERSION_1_6 = 160; /** * JavaScript 1.7 */ public static final int VERSION_1_7 = 170; /** * Controls behaviour of <tt>Date.prototype.getYear()</tt>. * If <tt>hasFeature(FEATURE_NON_ECMA_GET_YEAR)</tt> returns true, * Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000. * The default behavior of {@link #hasFeature(int)} is always to subtruct * 1900 as rquired by ECMAScript B.2.4. */ public static final int FEATURE_NON_ECMA_GET_YEAR = 1; /** * Control if member expression as function name extension is available. * If <tt>hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME)</tt> returns * true, allow <tt>function memberExpression(args) { body }</tt> to be * syntax sugar for <tt>memberExpression = function(args) { body }</tt>, * when memberExpression is not a simple identifier. * See ECMAScript-262, section 11.2 for definition of memberExpression. * By default {@link #hasFeature(int)} returns false. */ public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME = 2; /** * Control if reserved keywords are treated as identifiers. * If <tt>hasFeature(RESERVED_KEYWORD_AS_IDENTIFIER)</tt> returns true, * treat future reserved keyword (see Ecma-262, section 7.5.3) as ordinary * identifiers but warn about this usage. * * By default {@link #hasFeature(int)} returns false. */ public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER = 3; /** * Control if <tt>toString()</tt> should returns the same result * as <tt>toSource()</tt> when applied to objects and arrays. * If <tt>hasFeature(FEATURE_TO_STRING_AS_SOURCE)</tt> returns true, * calling <tt>toString()</tt> on JS objects gives the same result as * calling <tt>toSource()</tt>. That is it returns JS source with code * to create an object with all enumeratable fields of the original object * instead of printing <tt>[object <i>result of * {@link Scriptable#getClassName()}</i>]</tt>. * <p> * By default {@link #hasFeature(int)} returns true only if * the current JS version is set to {@link #VERSION_1_2}. */ public static final int FEATURE_TO_STRING_AS_SOURCE = 4; /** * Control if properties <tt>__proto__</tt> and <tt>__parent__</tt> * are treated specially. * If <tt>hasFeature(FEATURE_PARENT_PROTO_PROPERTIES)</tt> returns true, * treat <tt>__parent__</tt> and <tt>__proto__</tt> as special properties. * <p> * The properties allow to query and set scope and prototype chains for the * objects. The special meaning of the properties is available * only when they are used as the right hand side of the dot operator. * For example, while <tt>x.__proto__ = y</tt> changes the prototype * chain of the object <tt>x</tt> to point to <tt>y</tt>, * <tt>x["__proto__"] = y</tt> simply assigns a new value to the property * <tt>__proto__</tt> in <tt>x</tt> even when the feature is on. * * By default {@link #hasFeature(int)} returns true. */ public static final int FEATURE_PARENT_PROTO_PROPERTIES = 5; /** * @deprecated In previous releases, this name was given to * FEATURE_PARENT_PROTO_PROPERTIES. */ public static final int FEATURE_PARENT_PROTO_PROPRTIES = 5; /** * Control if support for E4X(ECMAScript for XML) extension is available. * If hasFeature(FEATURE_E4X) returns true, the XML syntax is available. * <p> * By default {@link #hasFeature(int)} returns true if * the current JS version is set to {@link #VERSION_DEFAULT} * or is at least {@link #VERSION_1_6}. * @since 1.6 Release 1 */ public static final int FEATURE_E4X = 6; /** * Control if dynamic scope should be used for name access. * If hasFeature(FEATURE_DYNAMIC_SCOPE) returns true, then the name lookup * during name resolution will use the top scope of the script or function * which is at the top of JS execution stack instead of the top scope of the * script or function from the current stack frame if the top scope of * the top stack frame contains the top scope of the current stack frame * on its prototype chain. * <p> * This is useful to define shared scope containing functions that can * be called from scripts and functions using private scopes. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.6 Release 1 */ public static final int FEATURE_DYNAMIC_SCOPE = 7; /** * Control if strict variable mode is enabled. * When the feature is on Rhino reports runtime errors if assignment * to a global variable that does not exist is executed. When the feature * is off such assignments creates new variable in the global scope as * required by ECMA 262. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.6 Release 1 */ public static final int FEATURE_STRICT_VARS = 8; /** * Control if strict eval mode is enabled. * When the feature is on Rhino reports runtime errors if non-string * argument is passed to the eval function. When the feature is off * eval simply return non-string argument as is without performing any * evaluation as required by ECMA 262. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.6 Release 1 */ public static final int FEATURE_STRICT_EVAL = 9; /** * When the feature is on Rhino will add a "fileName" and "lineNumber" * properties to Error objects automatically. When the feature is off, you * have to explicitly pass them as the second and third argument to the * Error constructor. Note that neither behaviour is fully ECMA 262 * compliant (as 262 doesn't specify a three-arg constructor), but keeping * the feature off results in Error objects that don't have * additional non-ECMA properties when constructed using the ECMA-defined * single-arg constructor and is thus desirable if a stricter ECMA * compliance is desired, specifically adherence to the point 15.11.5. of * the standard. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.6 Release 6 */ public static final int FEATURE_LOCATION_INFORMATION_IN_ERROR = 10; /** * Controls whether JS 1.5 'strict mode' is enabled. * When the feature is on, Rhino reports more than a dozen different * warnings. When the feature is off, these warnings are not generated. * FEATURE_STRICT_MODE implies FEATURE_STRICT_VARS and FEATURE_STRICT_EVAL. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.6 Release 6 */ public static final int FEATURE_STRICT_MODE = 11; /** * Controls whether a warning should be treated as an error. * @since 1.6 Release 6 */ public static final int FEATURE_WARNING_AS_ERROR = 12; /** * Enables enhanced access to Java. * Specifically, controls whether private and protected members can be * accessed, and whether scripts can catch all Java exceptions. * <p> * Note that this feature should only be enabled for trusted scripts. * <p> * By default {@link #hasFeature(int)} returns false. * @since 1.7 Release 1 */ public static final int FEATURE_ENHANCED_JAVA_ACCESS = 13; public static final String languageVersionProperty = "language version"; public static final String errorReporterProperty = "error reporter"; /** * Convenient value to use as zero-length array of objects. */ public static final Object[] emptyArgs = ScriptRuntime.emptyArgs; /** * Create a new Context. * * Note that the Context must be associated with a thread before * it can be used to execute a script. * * @see #enter() * @see #call(ContextAction) */ public Context() { setLanguageVersion(VERSION_DEFAULT); optimizationLevel = codegenClass != null ? 0 : -1; maximumInterpreterStackDepth = Integer.MAX_VALUE; } /** * Get the current Context. * * The current Context is per-thread; this method looks up * the Context associated with the current thread. <p> * * @return the Context associated with the current thread, or * null if no context is associated with the current * thread. * @see org.mozilla.javascript.Context#enter() * @see org.mozilla.javascript.Context#exit() */ public static Context getCurrentContext() { Object helper = VMBridge.instance.getThreadContextHelper(); return VMBridge.instance.getContext(helper); } /** * Get a context associated with the current thread, creating * one if need be. * * The Context stores the execution state of the JavaScript * engine, so it is required that the context be entered * before execution may begin. Once a thread has entered * a Context, then getCurrentContext() may be called to find * the context that is associated with the current thread. * <p> * Calling <code>enter()</code> will * return either the Context currently associated with the * thread, or will create a new context and associate it * with the current thread. Each call to <code>enter()</code> * must have a matching call to <code>exit()</code>. For example, * <pre> * Context cx = Context.enter(); * try { * ... * cx.evaluateString(...); * } finally { * Context.exit(); * } * </pre> * Instead of using <tt>enter()</tt>, <tt>exit()</tt> pair consider using * {@link #call(ContextAction)} which guarantees proper * association of Context instances with the current thread and is faster. * With this method the above example becomes: * <pre> * Context.call(new ContextAction() { * public Object run(Context cx) { * ... * cx.evaluateString(...); * return null; * } * }); * </pre> * * @return a Context associated with the current thread * @see #getCurrentContext() * @see #exit() * @see #call(ContextAction) */ public static Context enter() { return enter(null); } /** * Get a Context associated with the current thread, using * the given Context if need be. * <p> * The same as <code>enter()</code> except that <code>cx</code> * is associated with the current thread and returned if * the current thread has no associated context and <code>cx</code> * is not associated with any other thread. * @param cx a Context to associate with the thread if possible * @return a Context associated with the current thread * * @see #enter() * @see #call(ContextAction) * @see ContextFactory#call(ContextAction) */ public static Context enter(Context cx) { return enter(cx, ContextFactory.getGlobal()); } static final Context enter(Context cx, ContextFactory factory) { Object helper = VMBridge.instance.getThreadContextHelper(); Context old = VMBridge.instance.getContext(helper); if (old != null) { if (cx != null && cx != old && cx.enterCount != 0) { // The suplied context must be the context for // the current thread if it is already entered throw new IllegalArgumentException( "Cannot enter Context active on another thread"); } if (old.factory != null) { // Context with associated factory will be released // automatically and does not need to change enterCount return old; } if (old.sealed) onSealedMutation(); cx = old; } else { if (cx == null) { cx = factory.makeContext(); } else { if (cx.sealed) onSealedMutation(); } if (cx.enterCount != 0 || cx.factory != null) { throw new IllegalStateException(); } if (!cx.creationEventWasSent) { cx.creationEventWasSent = true; factory.onContextCreated(cx); } } if (old == null) { VMBridge.instance.setContext(helper, cx); } ++cx.enterCount; return cx; } /** * Exit a block of code requiring a Context. * * Calling <code>exit()</code> will remove the association between * the current thread and a Context if the prior call to * <code>enter()</code> on this thread newly associated a Context * with this thread. * Once the current thread no longer has an associated Context, * it cannot be used to execute JavaScript until it is again associated * with a Context. * * @see org.mozilla.javascript.Context#enter() * @see #call(ContextAction) * @see ContextFactory#call(ContextAction) */ public static void exit() { exit(ContextFactory.getGlobal()); } static void exit(ContextFactory factory) { Object helper = VMBridge.instance.getThreadContextHelper(); Context cx = VMBridge.instance.getContext(helper); if (cx == null) { throw new IllegalStateException( "Calling Context.exit without previous Context.enter"); } if (cx.factory != null) { // Context with associated factory will be released // automatically and does not need to change enterCount return; } if (cx.enterCount < 1) Kit.codeBug(); if (cx.sealed) onSealedMutation(); --cx.enterCount; if (cx.enterCount == 0) { VMBridge.instance.setContext(helper, null); factory.onContextReleased(cx); } } /** * Call {@link ContextAction#run(Context cx)} * using the Context instance associated with the current thread. * If no Context is associated with the thread, then * <tt>ContextFactory.getGlobal().makeContext()</tt> will be called to * construct new Context instance. The instance will be temporary * associated with the thread during call to * {@link ContextAction#run(Context)}. * * @return The result of {@link ContextAction#run(Context)}. */ public static Object call(ContextAction action) { return call(ContextFactory.getGlobal(), action); } /** * Call {@link * Callable#call(Context cx, Scriptable scope, Scriptable thisObj, * Object[] args)} * using the Context instance associated with the current thread. * If no Context is associated with the thread, then * {@link ContextFactory#makeContext()} will be called to construct * new Context instance. The instance will be temporary associated * with the thread during call to {@link ContextAction#run(Context)}. * <p> * It is allowed to use null for <tt>factory</tt> argument * in which case the factory associated with the scope will be * used to create new context instances. * * @see ContextFactory#call(ContextAction) */ public static Object call(ContextFactory factory, Callable callable, Scriptable scope, Scriptable thisObj, Object[] args) { if (factory == null) { factory = ContextFactory.getGlobal(); } Object helper = VMBridge.instance.getThreadContextHelper(); Context cx = VMBridge.instance.getContext(helper); if (cx != null) { Object result; if (cx.factory != null) { result = callable.call(cx, scope, thisObj, args); } else { // Context was associated with the thread via Context.enter, // set factory to make Context.enter/exit to be no-op // during call cx.factory = factory; try { result = callable.call(cx, scope, thisObj, args); } finally { cx.factory = null; } } return result; } cx = prepareNewContext(factory, helper); try { return callable.call(cx, scope, thisObj, args); } finally { releaseContext(helper, cx); } } /** * The method implements {@links ContextFactory#call(ContextAction)} logic. */ static Object call(ContextFactory factory, ContextAction action) { Object helper = VMBridge.instance.getThreadContextHelper(); Context cx = VMBridge.instance.getContext(helper); if (cx != null) { if (cx.factory != null) { return action.run(cx); } else { cx.factory = factory; try { return action.run(cx); } finally { cx.factory = null; } } } cx = prepareNewContext(factory, helper); try { return action.run(cx); } finally { releaseContext(helper, cx); } } private static Context prepareNewContext(ContextFactory factory, Object contextHelper) { Context cx = factory.makeContext(); if (cx.factory != null || cx.enterCount != 0) { throw new IllegalStateException("factory.makeContext() returned Context instance already associated with some thread"); } cx.factory = factory; factory.onContextCreated(cx); if (factory.isSealed() && !cx.isSealed()) { cx.seal(null); } VMBridge.instance.setContext(contextHelper, cx); return cx; } private static void releaseContext(Object contextHelper, Context cx) { VMBridge.instance.setContext(contextHelper, null); try { cx.factory.onContextReleased(cx); } finally { cx.factory = null; } } /** * @deprecated * @see ContextFactory#addListener(ContextFactory.Listener) * @see ContextFactory#getGlobal() */ public static void addContextListener(ContextListener listener) { // Special workaround for the debugger String DBG = "org.mozilla.javascript.tools.debugger.Main"; if (DBG.equals(listener.getClass().getName())) { Class cl = listener.getClass(); Class factoryClass = Kit.classOrNull( "org.mozilla.javascript.ContextFactory"); Class[] sig = { factoryClass }; Object[] args = { ContextFactory.getGlobal() }; try { Method m = cl.getMethod("attachTo", sig); m.invoke(listener, args); } catch (Exception ex) { RuntimeException rex = new RuntimeException(); Kit.initCause(rex, ex); throw rex; } return; } ContextFactory.getGlobal().addListener(listener); } /** * @deprecated * @see ContextFactory#removeListener(ContextFactory.Listener) * @see ContextFactory#getGlobal() */ public static void removeContextListener(ContextListener listener) { ContextFactory.getGlobal().addListener(listener); } /** * Return {@link ContextFactory} instance used to create this Context * or the result of {@link ContextFactory#getGlobal()} if no factory * was used for Context creation. */ public final ContextFactory getFactory() { ContextFactory result = factory; if (result == null) { result = ContextFactory.getGlobal(); } return result; } /** * Checks if this is a sealed Context. A sealed Context instance does not * allow to modify any of its properties and will throw an exception * on any such attempt. * @see #seal(Object sealKey) */ public final boolean isSealed() { return sealed; } /** * Seal this Context object so any attempt to modify any of its properties * including calling {@link #enter()} and {@link #exit()} methods will * throw an exception. * <p> * If <tt>sealKey</tt> is not null, calling * {@link #unseal(Object sealKey)} with the same key unseals * the object. If <tt>sealKey</tt> is null, unsealing is no longer possible. * * @see #isSealed() * @see #unseal(Object) */ public final void seal(Object sealKey) { if (sealed) onSealedMutation(); sealed = true; this.sealKey = sealKey; } /** * Unseal previously sealed Context object. * The <tt>sealKey</tt> argument should not be null and should match * <tt>sealKey</tt> suplied with the last call to * {@link #seal(Object)} or an exception will be thrown. * * @see #isSealed() * @see #seal(Object sealKey) */ public final void unseal(Object sealKey) { if (sealKey == null) throw new IllegalArgumentException(); if (this.sealKey != sealKey) throw new IllegalArgumentException(); if (!sealed) throw new IllegalStateException(); sealed = false; this.sealKey = null; } static void onSealedMutation() { throw new IllegalStateException(); } /** * Get the current language version. * <p> * The language version number affects JavaScript semantics as detailed * in the overview documentation. * * @return an integer that is one of VERSION_1_0, VERSION_1_1, etc. */ public final int getLanguageVersion() { return version; } /** * Set the language version. * * <p> * Setting the language version will affect functions and scripts compiled * subsequently. See the overview documentation for version-specific * behavior. * * @param version the version as specified by VERSION_1_0, VERSION_1_1, etc. */ public void setLanguageVersion(int version) { if (sealed) onSealedMutation(); checkLanguageVersion(version); Object listeners = propertyListeners; if (listeners != null && version != this.version) { firePropertyChangeImpl(listeners, languageVersionProperty, new Integer(this.version), new Integer(version)); } this.version = version; } public static boolean isValidLanguageVersion(int version) { switch (version) { case VERSION_DEFAULT: case VERSION_1_0: case VERSION_1_1: case VERSION_1_2: case VERSION_1_3: case VERSION_1_4: case VERSION_1_5: case VERSION_1_6: case VERSION_1_7: return true; } return false; } public static void checkLanguageVersion(int version) { if (isValidLanguageVersion(version)) { return; } throw new IllegalArgumentException("Bad language version: "+version); } /** * Get the implementation version. * * <p> * The implementation version is of the form * <pre> * "<i>name langVer</i> <code>release</code> <i>relNum date</i>" * </pre> * where <i>name</i> is the name of the product, <i>langVer</i> is * the language version, <i>relNum</i> is the release number, and * <i>date</i> is the release date for that specific * release in the form "yyyy mm dd". * * @return a string that encodes the product, language version, release * number, and date. */ public final String getImplementationVersion() { // XXX Probably it would be better to embed this directly into source // with special build preprocessing but that would require some ant // tweaking and then replacing token in resource files was simpler if (implementationVersion == null) { implementationVersion = ScriptRuntime.getMessage0("implementation.version"); } return implementationVersion; } /** * Get the current error reporter. * * @see org.mozilla.javascript.ErrorReporter */ public final ErrorReporter getErrorReporter() { if (errorReporter == null) { return DefaultErrorReporter.instance; } return errorReporter; } /** * Change the current error reporter. * * @return the previous error reporter * @see org.mozilla.javascript.ErrorReporter */ public final ErrorReporter setErrorReporter(ErrorReporter reporter) { if (sealed) onSealedMutation(); if (reporter == null) throw new IllegalArgumentException(); ErrorReporter old = getErrorReporter(); if (reporter == old) { return old; } Object listeners = propertyListeners; if (listeners != null) { firePropertyChangeImpl(listeners, errorReporterProperty, old, reporter); } this.errorReporter = reporter; return old; } /** * Get the current locale. Returns the default locale if none has * been set. * * @see java.util.Locale */ public final Locale getLocale() { if (locale == null) locale = Locale.getDefault(); return locale; } /** * Set the current locale. * * @see java.util.Locale */ public final Locale setLocale(Locale loc) { if (sealed) onSealedMutation(); Locale result = locale; locale = loc; return result; } /** * Register an object to receive notifications when a bound property * has changed * @see java.beans.PropertyChangeEvent * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) * @param l the listener */ public final void addPropertyChangeListener(PropertyChangeListener l) { if (sealed) onSealedMutation(); propertyListeners = Kit.addListener(propertyListeners, l); } /** * Remove an object from the list of objects registered to receive * notification of changes to a bounded property * @see java.beans.PropertyChangeEvent * @see #addPropertyChangeListener(java.beans.PropertyChangeListener) * @param l the listener */ public final void removePropertyChangeListener(PropertyChangeListener l) { if (sealed) onSealedMutation(); propertyListeners = Kit.removeListener(propertyListeners, l); } /** * Notify any registered listeners that a bounded property has changed * @see #addPropertyChangeListener(java.beans.PropertyChangeListener) * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) * @see java.beans.PropertyChangeListener * @see java.beans.PropertyChangeEvent * @param property the bound property * @param oldValue the old value * @param newValue the new value */ final void firePropertyChange(String property, Object oldValue, Object newValue) { Object listeners = propertyListeners; if (listeners != null) { firePropertyChangeImpl(listeners, property, oldValue, newValue); } } private void firePropertyChangeImpl(Object listeners, String property, Object oldValue, Object newValue) { for (int i = 0; ; ++i) { Object l = Kit.getListener(listeners, i); if (l == null) break; if (l instanceof PropertyChangeListener) { PropertyChangeListener pcl = (PropertyChangeListener)l; pcl.propertyChange(new PropertyChangeEvent( this, property, oldValue, newValue)); } } } /** * Report a warning using the error reporter for the current thread. * * @param message the warning message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @see org.mozilla.javascript.ErrorReporter */ public static void reportWarning(String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = Context.getContext(); if (cx.hasFeature(FEATURE_WARNING_AS_ERROR)) reportError(message, sourceName, lineno, lineSource, lineOffset); else cx.getErrorReporter().warning(message, sourceName, lineno, lineSource, lineOffset); } /** * Report a warning using the error reporter for the current thread. * * @param message the warning message to report * @see org.mozilla.javascript.ErrorReporter */ public static void reportWarning(String message) { int[] linep = { 0 }; String filename = getSourcePositionFromStack(linep); Context.reportWarning(message, filename, linep[0], null, 0); } public static void reportWarning(String message, Throwable t) { int[] linep = { 0 }; String filename = getSourcePositionFromStack(linep); Writer sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(message); t.printStackTrace(pw); pw.flush(); Context.reportWarning(sw.toString(), filename, linep[0], null, 0); } /** * Report an error using the error reporter for the current thread. * * @param message the error message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @see org.mozilla.javascript.ErrorReporter */ public static void reportError(String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = getCurrentContext(); if (cx != null) { cx.getErrorReporter().error(message, sourceName, lineno, lineSource, lineOffset); } else { throw new EvaluatorException(message, sourceName, lineno, lineSource, lineOffset); } } /** * Report an error using the error reporter for the current thread. * * @param message the error message to report * @see org.mozilla.javascript.ErrorReporter */ public static void reportError(String message) { int[] linep = { 0 }; String filename = getSourcePositionFromStack(linep); Context.reportError(message, filename, linep[0], null, 0); } /** * Report a runtime error using the error reporter for the current thread. * * @param message the error message to report * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param lineSource the text of the line (may be null) * @param lineOffset the offset into lineSource where problem was detected * @return a runtime exception that will be thrown to terminate the * execution of the script * @see org.mozilla.javascript.ErrorReporter */ public static EvaluatorException reportRuntimeError(String message, String sourceName, int lineno, String lineSource, int lineOffset) { Context cx = getCurrentContext(); if (cx != null) { return cx.getErrorReporter(). runtimeError(message, sourceName, lineno, lineSource, lineOffset); } else { throw new EvaluatorException(message, sourceName, lineno, lineSource, lineOffset); } } static EvaluatorException reportRuntimeError0(String messageId) { String msg = ScriptRuntime.getMessage0(messageId); return reportRuntimeError(msg); } static EvaluatorException reportRuntimeError1(String messageId, Object arg1) { String msg = ScriptRuntime.getMessage1(messageId, arg1); return reportRuntimeError(msg); } static EvaluatorException reportRuntimeError2(String messageId, Object arg1, Object arg2) { String msg = ScriptRuntime.getMessage2(messageId, arg1, arg2); return reportRuntimeError(msg); } static EvaluatorException reportRuntimeError3(String messageId, Object arg1, Object arg2, Object arg3) { String msg = ScriptRuntime.getMessage3(messageId, arg1, arg2, arg3); return reportRuntimeError(msg); } static EvaluatorException reportRuntimeError4(String messageId, Object arg1, Object arg2, Object arg3, Object arg4) { String msg = ScriptRuntime.getMessage4(messageId, arg1, arg2, arg3, arg4); return reportRuntimeError(msg); } /** * Report a runtime error using the error reporter for the current thread. * * @param message the error message to report * @see org.mozilla.javascript.ErrorReporter */ public static EvaluatorException reportRuntimeError(String message) { int[] linep = { 0 }; String filename = getSourcePositionFromStack(linep); return Context.reportRuntimeError(message, filename, linep[0], null, 0); } /** * Initialize the standard objects. * * Creates instances of the standard objects and their constructors * (Object, String, Number, Date, etc.), setting up 'scope' to act * as a global object as in ECMA 15.1.<p> * * This method must be called to initialize a scope before scripts * can be evaluated in that scope.<p> * * This method does not affect the Context it is called upon. * * @return the initialized scope */ public final ScriptableObject initStandardObjects() { return initStandardObjects(null, false); } /** * Initialize the standard objects. * * Creates instances of the standard objects and their constructors * (Object, String, Number, Date, etc.), setting up 'scope' to act * as a global object as in ECMA 15.1.<p> * * This method must be called to initialize a scope before scripts * can be evaluated in that scope.<p> * * This method does not affect the Context it is called upon. * * @param scope the scope to initialize, or null, in which case a new * object will be created to serve as the scope * @return the initialized scope. The method returns the value of the scope * argument if it is not null or newly allocated scope object which * is an instance {@link ScriptableObject}. */ public final Scriptable initStandardObjects(ScriptableObject scope) { return initStandardObjects(scope, false); } /** * Initialize the standard objects. * * Creates instances of the standard objects and their constructors * (Object, String, Number, Date, etc.), setting up 'scope' to act * as a global object as in ECMA 15.1.<p> * * This method must be called to initialize a scope before scripts * can be evaluated in that scope.<p> * * This method does not affect the Context it is called upon.<p> * * This form of the method also allows for creating "sealed" standard * objects. An object that is sealed cannot have properties added, changed, * or removed. This is useful to create a "superglobal" that can be shared * among several top-level objects. Note that sealing is not allowed in * the current ECMA/ISO language specification, but is likely for * the next version. * * @param scope the scope to initialize, or null, in which case a new * object will be created to serve as the scope * @param sealed whether or not to create sealed standard objects that * cannot be modified. * @return the initialized scope. The method returns the value of the scope * argument if it is not null or newly allocated scope object. * @since 1.4R3 */ public ScriptableObject initStandardObjects(ScriptableObject scope, boolean sealed) { return ScriptRuntime.initStandardObjects(this, scope, sealed); } /** * Get the singleton object that represents the JavaScript Undefined value. */ public static Object getUndefinedValue() { return Undefined.instance; } /** * Evaluate a JavaScript source string. * * The provided source name and line number are used for error messages * and for producing debug information. * * @param scope the scope to execute in * @param source the JavaScript source * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security * information about the origin or owner of the script. For * implementations that don't care about security, this value * may be null. * @return the result of evaluating the string * @see org.mozilla.javascript.SecurityController */ public final Object evaluateString(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain) { Script script = compileString(source, sourceName, lineno, securityDomain); if (script != null) { return script.exec(this, scope); } else { return null; } } /** * Evaluate a reader as JavaScript source. * * All characters of the reader are consumed. * * @param scope the scope to execute in * @param in the Reader to get JavaScript source from * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security * information about the origin or owner of the script. For * implementations that don't care about security, this value * may be null. * @return the result of evaluating the source * * @exception IOException if an IOException was generated by the Reader */ public final Object evaluateReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { Script script = compileReader(scope, in, sourceName, lineno, securityDomain); if (script != null) { return script.exec(this, scope); } else { return null; } } /** * Check whether a string is ready to be compiled. * <p> * stringIsCompilableUnit is intended to support interactive compilation of * javascript. If compiling the string would result in an error * that might be fixed by appending more source, this method * returns false. In every other case, it returns true. * <p> * Interactive shells may accumulate source lines, using this * method after each new line is appended to check whether the * statement being entered is complete. * * @param source the source buffer to check * @return whether the source is ready for compilation * @since 1.4 Release 2 */ public final boolean stringIsCompilableUnit(String source) { boolean errorseen = false; CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); // no source name or source text manager, because we're just // going to throw away the result. compilerEnv.setGeneratingSource(false); Parser p = new Parser(compilerEnv, DefaultErrorReporter.instance); try { p.parse(source, null, 1); } catch (EvaluatorException ee) { errorseen = true; } // Return false only if an error occurred as a result of reading past // the end of the file, i.e. if the source could be fixed by // appending more source. if (errorseen && p.eof()) return false; else return true; } /** * @deprecated * @see #compileReader(Reader in, String sourceName, int lineno, * Object securityDomain) */ public final Script compileReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { return compileReader(in, sourceName, lineno, securityDomain); } /** * Compiles the source in the given reader. * <p> * Returns a script that may later be executed. * Will consume all the source in the reader. * * @param in the input reader * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number for reporting errors * @param securityDomain an arbitrary object that specifies security * information about the origin or owner of the script. For * implementations that don't care about security, this value * may be null. * @return a script that may later be executed * @exception IOException if an IOException was generated by the Reader * @see org.mozilla.javascript.Script */ public final Script compileReader(Reader in, String sourceName, int lineno, Object securityDomain) throws IOException { if (lineno < 0) { // For compatibility IllegalArgumentException can not be thrown here lineno = 0; } return (Script) compileImpl(null, in, null, sourceName, lineno, securityDomain, false, null, null); } /** * Compiles the source in the given string. * <p> * Returns a script that may later be executed. * * @param source the source string * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number for reporting errors * @param securityDomain an arbitrary object that specifies security * information about the origin or owner of the script. For * implementations that don't care about security, this value * may be null. * @return a script that may later be executed * @see org.mozilla.javascript.Script */ public final Script compileString(String source, String sourceName, int lineno, Object securityDomain) { if (lineno < 0) { // For compatibility IllegalArgumentException can not be thrown here lineno = 0; } return compileString(source, null, null, sourceName, lineno, securityDomain); } final Script compileString(String source, Interpreter compiler, ErrorReporter compilationErrorReporter, String sourceName, int lineno, Object securityDomain) { try { return (Script) compileImpl(null, null, source, sourceName, lineno, securityDomain, false, compiler, compilationErrorReporter); } catch (IOException ex) { // Should not happen when dealing with source as string throw new RuntimeException(); } } /** * Compile a JavaScript function. * <p> * The function source must be a function definition as defined by * ECMA (e.g., "function f(a) { return a; }"). * * @param scope the scope to compile relative to * @param source the function definition source * @param sourceName a string describing the source, such as a filename * @param lineno the starting line number * @param securityDomain an arbitrary object that specifies security * information about the origin or owner of the script. For * implementations that don't care about security, this value * may be null. * @return a Function that may later be called * @see org.mozilla.javascript.Function */ public final Function compileFunction(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain) { return compileFunction(scope, source, null, null, sourceName, lineno, securityDomain); } final Function compileFunction(Scriptable scope, String source, Interpreter compiler, ErrorReporter compilationErrorReporter, String sourceName, int lineno, Object securityDomain) { try { return (Function) compileImpl(scope, null, source, sourceName, lineno, securityDomain, true, compiler, compilationErrorReporter); } catch (IOException ioe) { // Should never happen because we just made the reader // from a String throw new RuntimeException(); } } /** * Decompile the script. * <p> * The canonical source of the script is returned. * * @param script the script to decompile * @param indent the number of spaces to indent the result * @return a string representing the script source */ public final String decompileScript(Script script, int indent) { NativeFunction scriptImpl = (NativeFunction) script; return scriptImpl.decompile(indent, 0); } /** * Decompile a JavaScript Function. * <p> * Decompiles a previously compiled JavaScript function object to * canonical source. * <p> * Returns function body of '[native code]' if no decompilation * information is available. * * @param fun the JavaScript function to decompile * @param indent the number of spaces to indent the result * @return a string representing the function source */ public final String decompileFunction(Function fun, int indent) { if (fun instanceof BaseFunction) return ((BaseFunction)fun).decompile(indent, 0); else return "function " + fun.getClassName() + "() {\n\t[native code]\n}\n"; } /** * Decompile the body of a JavaScript Function. * <p> * Decompiles the body a previously compiled JavaScript Function * object to canonical source, omitting the function header and * trailing brace. * * Returns '[native code]' if no decompilation information is available. * * @param fun the JavaScript function to decompile * @param indent the number of spaces to indent the result * @return a string representing the function body source. */ public final String decompileFunctionBody(Function fun, int indent) { if (fun instanceof BaseFunction) { BaseFunction bf = (BaseFunction)fun; return bf.decompile(indent, Decompiler.ONLY_BODY_FLAG); } // ALERT: not sure what the right response here is. return "[native code]\n"; } /** * Create a new JavaScript object. * * Equivalent to evaluating "new Object()". * @param scope the scope to search for the constructor and to evaluate * against * @return the new object */ public final Scriptable newObject(Scriptable scope) { return newObject(scope, "Object", ScriptRuntime.emptyArgs); } /** * Create a new JavaScript object by executing the named constructor. * * The call <code>newObject(scope, "Foo")</code> is equivalent to * evaluating "new Foo()". * * @param scope the scope to search for the constructor and to evaluate against * @param constructorName the name of the constructor to call * @return the new object */ public final Scriptable newObject(Scriptable scope, String constructorName) { return newObject(scope, constructorName, ScriptRuntime.emptyArgs); } /** * Creates a new JavaScript object by executing the named constructor. * * Searches <code>scope</code> for the named constructor, calls it with * the given arguments, and returns the result.<p> * * The code * <pre> * Object[] args = { "a", "b" }; * newObject(scope, "Foo", args)</pre> * is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo * constructor has been defined in <code>scope</code>. * * @param scope The scope to search for the constructor and to evaluate * against * @param constructorName the name of the constructor to call * @param args the array of arguments for the constructor * @return the new object */ public final Scriptable newObject(Scriptable scope, String constructorName, Object[] args) { scope = ScriptableObject.getTopLevelScope(scope); Function ctor = ScriptRuntime.getExistingCtor(this, scope, constructorName); if (args == null) { args = ScriptRuntime.emptyArgs; } return ctor.construct(this, scope, args); } /** * Create an array with a specified initial length. * <p> * @param scope the scope to create the object in * @param length the initial length (JavaScript arrays may have * additional properties added dynamically). * @return the new array object */ public final Scriptable newArray(Scriptable scope, int length) { NativeArray result = new NativeArray(length); ScriptRuntime.setObjectProtoAndParent(result, scope); return result; } /** * Create an array with a set of initial elements. * * @param scope the scope to create the object in. * @param elements the initial elements. Each object in this array * must be an acceptable JavaScript type and type * of array should be exactly Object[], not * SomeObjectSubclass[]. * @return the new array object. */ public final Scriptable newArray(Scriptable scope, Object[] elements) { if (elements.getClass().getComponentType() != ScriptRuntime.ObjectClass) throw new IllegalArgumentException(); NativeArray result = new NativeArray(elements); ScriptRuntime.setObjectProtoAndParent(result, scope); return result; } /** * Get the elements of a JavaScript array. * <p> * If the object defines a length property convertible to double number, * then the number is converted Uint32 value as defined in Ecma 9.6 * and Java array of that size is allocated. * The array is initialized with the values obtained by * calling get() on object for each value of i in [0,length-1]. If * there is not a defined value for a property the Undefined value * is used to initialize the corresponding element in the array. The * Java array is then returned. * If the object doesn't define a length property or it is not a number, * empty array is returned. * @param object the JavaScript array or array-like object * @return a Java array of objects * @since 1.4 release 2 */ public final Object[] getElements(Scriptable object) { return ScriptRuntime.getArrayElements(object); } /** * Convert the value to a JavaScript boolean value. * <p> * See ECMA 9.2. * * @param value a JavaScript value * @return the corresponding boolean value converted using * the ECMA rules */ public static boolean toBoolean(Object value) { return ScriptRuntime.toBoolean(value); } /** * Convert the value to a JavaScript Number value. * <p> * Returns a Java double for the JavaScript Number. * <p> * See ECMA 9.3. * * @param value a JavaScript value * @return the corresponding double value converted using * the ECMA rules */ public static double toNumber(Object value) { return ScriptRuntime.toNumber(value); } /** * Convert the value to a JavaScript String value. * <p> * See ECMA 9.8. * <p> * @param value a JavaScript value * @return the corresponding String value converted using * the ECMA rules */ public static String toString(Object value) { return ScriptRuntime.toString(value); } /** * Convert the value to an JavaScript object value. * <p> * Note that a scope must be provided to look up the constructors * for Number, Boolean, and String. * <p> * See ECMA 9.9. * <p> * Additionally, arbitrary Java objects and classes will be * wrapped in a Scriptable object with its Java fields and methods * reflected as JavaScript properties of the object. * * @param value any Java object * @param scope global scope containing constructors for Number, * Boolean, and String * @return new JavaScript object */ public static Scriptable toObject(Object value, Scriptable scope) { return ScriptRuntime.toObject(scope, value); } /** * @deprecated * @see #toObject(Object, Scriptable) */ public static Scriptable toObject(Object value, Scriptable scope, Class staticType) { return ScriptRuntime.toObject(scope, value); } /** * Convenient method to convert java value to its closest representation * in JavaScript. * <p> * If value is an instance of String, Number, Boolean, Function or * Scriptable, it is returned as it and will be treated as the corresponding * JavaScript type of string, number, boolean, function and object. * <p> * Note that for Number instances during any arithmetic operation in * JavaScript the engine will always use the result of * <tt>Number.doubleValue()</tt> resulting in a precision loss if * the number can not fit into double. * <p> * If value is an instance of Character, it will be converted to string of * length 1 and its JavaScript type will be string. * <p> * The rest of values will be wrapped as LiveConnect objects * by calling {@link WrapFactory#wrap(Context cx, Scriptable scope, * Object obj, Class staticType)} as in: * <pre> * Context cx = Context.getCurrentContext(); * return cx.getWrapFactory().wrap(cx, scope, value, null); * </pre> * * @param value any Java object * @param scope top scope object * @return value suitable to pass to any API that takes JavaScript values. */ public static Object javaToJS(Object value, Scriptable scope) { if (value instanceof String || value instanceof Number || value instanceof Boolean || value instanceof Scriptable) { return value; } else if (value instanceof Character) { return String.valueOf(((Character)value).charValue()); } else { Context cx = Context.getContext(); return cx.getWrapFactory().wrap(cx, scope, value, null); } } /** * Convert a JavaScript value into the desired type. * Uses the semantics defined with LiveConnect3 and throws an * Illegal argument exception if the conversion cannot be performed. * @param value the JavaScript value to convert * @param desiredType the Java type to convert to. Primitive Java * types are represented using the TYPE fields in the corresponding * wrapper class in java.lang. * @return the converted value * @throws EvaluatorException if the conversion cannot be performed */ public static Object jsToJava(Object value, Class desiredType) throws EvaluatorException { return NativeJavaObject.coerceTypeImpl(desiredType, value); } /** * @deprecated * @see #jsToJava(Object, Class) * @throws IllegalArgumentException if the conversion cannot be performed. * Note that {@link #jsToJava(Object, Class)} throws * {@link EvaluatorException} instead. */ public static Object toType(Object value, Class desiredType) throws IllegalArgumentException { try { return jsToJava(value, desiredType); } catch (EvaluatorException ex) { IllegalArgumentException ex2 = new IllegalArgumentException(ex.getMessage()); Kit.initCause(ex2, ex); throw ex2; } } /** * Rethrow the exception wrapping it as the script runtime exception. * Unless the exception is instance of {@link EcmaError} or * {@link EvaluatorException} it will be wrapped as * {@link WrappedException}, a subclass of {@link EvaluatorException}. * The resulting exception object always contains * source name and line number of script that triggered exception. * <p> * This method always throws an exception, its return value is provided * only for convenience to allow a usage like: * <pre> * throw Context.throwAsScriptRuntimeEx(ex); * </pre> * to indicate that code after the method is unreachable. * @throws EvaluatorException * @throws EcmaError */ public static RuntimeException throwAsScriptRuntimeEx(Throwable e) { while ((e instanceof InvocationTargetException)) { e = ((InvocationTargetException) e).getTargetException(); } // special handling of Error so scripts would not catch them if (e instanceof Error) { Context cx = getContext(); if (cx == null || !cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)) { throw (Error)e; } } if (e instanceof RhinoException) { throw (RhinoException)e; } throw new WrappedException(e); } /** * Tell whether debug information is being generated. * @since 1.3 */ public final boolean isGeneratingDebug() { return generatingDebug; } /** * Specify whether or not debug information should be generated. * <p> * Setting the generation of debug information on will set the * optimization level to zero. * @since 1.3 */ public final void setGeneratingDebug(boolean generatingDebug) { if (sealed) onSealedMutation(); generatingDebugChanged = true; if (generatingDebug && getOptimizationLevel() > 0) setOptimizationLevel(0); this.generatingDebug = generatingDebug; } /** * Tell whether source information is being generated. * @since 1.3 */ public final boolean isGeneratingSource() { return generatingSource; } /** * Specify whether or not source information should be generated. * <p> * Without source information, evaluating the "toString" method * on JavaScript functions produces only "[native code]" for * the body of the function. * Note that code generated without source is not fully ECMA * conformant. * @since 1.3 */ public final void setGeneratingSource(boolean generatingSource) { if (sealed) onSealedMutation(); this.generatingSource = generatingSource; } /** * Get the current optimization level. * <p> * The optimization level is expressed as an integer between -1 and * 9. * @since 1.3 * */ public final int getOptimizationLevel() { return optimizationLevel; } /** * Set the current optimization level. * <p> * The optimization level is expected to be an integer between -1 and * 9. Any negative values will be interpreted as -1, and any values * greater than 9 will be interpreted as 9. * An optimization level of -1 indicates that interpretive mode will * always be used. Levels 0 through 9 indicate that class files may * be generated. Higher optimization levels trade off compile time * performance for runtime performance. * The optimizer level can't be set greater than -1 if the optimizer * package doesn't exist at run time. * @param optimizationLevel an integer indicating the level of * optimization to perform * @since 1.3 * */ public final void setOptimizationLevel(int optimizationLevel) { if (sealed) onSealedMutation(); if (optimizationLevel == -2) { // To be compatible with Cocoon fork optimizationLevel = -1; } checkOptimizationLevel(optimizationLevel); if (codegenClass == null) optimizationLevel = -1; this.optimizationLevel = optimizationLevel; } public static boolean isValidOptimizationLevel(int optimizationLevel) { return -1 <= optimizationLevel && optimizationLevel <= 9; } public static void checkOptimizationLevel(int optimizationLevel) { if (isValidOptimizationLevel(optimizationLevel)) { return; } throw new IllegalArgumentException( "Optimization level outside [-1..9]: "+optimizationLevel); } /** * Returns the maximum stack depth (in terms of number of call frames) * allowed in a single invocation of interpreter. If the set depth would be * exceeded, the interpreter will throw an EvaluatorException in the script. * Defaults to Integer.MAX_VALUE. The setting only has effect for * interpreted functions (those compiled with optimization level set to -1). * As the interpreter doesn't use the Java stack but rather manages its own * stack in the heap memory, a runaway recursion in interpreted code would * eventually consume all available memory and cause OutOfMemoryError * instead of a StackOverflowError limited to only a single thread. This * setting helps prevent such situations. * * @return The current maximum interpreter stack depth. */ public final int getMaximumInterpreterStackDepth() { return maximumInterpreterStackDepth; } /** * Sets the maximum stack depth (in terms of number of call frames) * allowed in a single invocation of interpreter. If the set depth would be * exceeded, the interpreter will throw an EvaluatorException in the script. * Defaults to Integer.MAX_VALUE. The setting only has effect for * interpreted functions (those compiled with optimization level set to -1). * As the interpreter doesn't use the Java stack but rather manages its own * stack in the heap memory, a runaway recursion in interpreted code would * eventually consume all available memory and cause OutOfMemoryError * instead of a StackOverflowError limited to only a single thread. This * setting helps prevent such situations. * * @param max the new maximum interpreter stack depth * @throws IllegalStateException if this context's optimization level is not * -1 * @throws IllegalArgumentException if the new depth is not at least 1 */ public final void setMaximumInterpreterStackDepth(int max) { if(sealed) onSealedMutation(); if(optimizationLevel != -1) { throw new IllegalStateException("Cannot set maximumInterpreterStackDepth when optimizationLevel != -1"); } if(max < 1) { throw new IllegalArgumentException("Cannot set maximumInterpreterStackDepth to less than 1"); } maximumInterpreterStackDepth = max; } /** * Set the security controller for this context. * <p> SecurityController may only be set if it is currently null * and {@link SecurityController#hasGlobal()} is <tt>false</tt>. * Otherwise a SecurityException is thrown. * @param controller a SecurityController object * @throws SecurityException if there is already a SecurityController * object for this Context or globally installed. * @see SecurityController#initGlobal(SecurityController controller) * @see SecurityController#hasGlobal() */ public final void setSecurityController(SecurityController controller) { if (sealed) onSealedMutation(); if (controller == null) throw new IllegalArgumentException(); if (securityController != null) { throw new SecurityException("Can not overwrite existing SecurityController object"); } if (SecurityController.hasGlobal()) { throw new SecurityException("Can not overwrite existing global SecurityController object"); } securityController = controller; } /** * Set the LiveConnect access filter for this context. * <p> {@link ClassShutter} may only be set if it is currently null. * Otherwise a SecurityException is thrown. * @param shutter a ClassShutter object * @throws SecurityException if there is already a ClassShutter * object for this Context */ public final void setClassShutter(ClassShutter shutter) { if (sealed) onSealedMutation(); if (shutter == null) throw new IllegalArgumentException(); if (classShutter != null) { throw new SecurityException("Cannot overwrite existing " + "ClassShutter object"); } classShutter = shutter; } final ClassShutter getClassShutter() { return classShutter; } /** * Get a value corresponding to a key. * <p> * Since the Context is associated with a thread it can be * used to maintain values that can be later retrieved using * the current thread. * <p> * Note that the values are maintained with the Context, so * if the Context is disassociated from the thread the values * cannot be retrieved. Also, if private data is to be maintained * in this manner the key should be a java.lang.Object * whose reference is not divulged to untrusted code. * @param key the key used to lookup the value * @return a value previously stored using putThreadLocal. */ public final Object getThreadLocal(Object key) { if (hashtable == null) return null; return hashtable.get(key); } /** * Put a value that can later be retrieved using a given key. * <p> * @param key the key used to index the value * @param value the value to save */ public final void putThreadLocal(Object key, Object value) { if (sealed) onSealedMutation(); if (hashtable == null) hashtable = new Hashtable(); hashtable.put(key, value); } /** * Remove values from thread-local storage. * @param key the key for the entry to remove. * @since 1.5 release 2 */ public final void removeThreadLocal(Object key) { if (sealed) onSealedMutation(); if (hashtable == null) return; hashtable.remove(key); } /** * @deprecated * @see #FEATURE_DYNAMIC_SCOPE * @see #hasFeature(int) */ public final boolean hasCompileFunctionsWithDynamicScope() { return compileFunctionsWithDynamicScopeFlag; } /** * @deprecated * @see #FEATURE_DYNAMIC_SCOPE * @see #hasFeature(int) */ public final void setCompileFunctionsWithDynamicScope(boolean flag) { if (sealed) onSealedMutation(); compileFunctionsWithDynamicScopeFlag = flag; } /** * @deprecated * @see ClassCache#get(Scriptable) * @see ClassCache#setCachingEnabled(boolean) */ public static void setCachingEnabled(boolean cachingEnabled) { } /** * Set a WrapFactory for this Context. * <p> * The WrapFactory allows custom object wrapping behavior for * Java object manipulated with JavaScript. * @see WrapFactory * @since 1.5 Release 4 */ public final void setWrapFactory(WrapFactory wrapFactory) { if (sealed) onSealedMutation(); if (wrapFactory == null) throw new IllegalArgumentException(); this.wrapFactory = wrapFactory; } /** * Return the current WrapFactory, or null if none is defined. * @see WrapFactory * @since 1.5 Release 4 */ public final WrapFactory getWrapFactory() { if (wrapFactory == null) { wrapFactory = new WrapFactory(); } return wrapFactory; } /** * Return the current debugger. * @return the debugger, or null if none is attached. */ public final Debugger getDebugger() { return debugger; } /** * Return the debugger context data associated with current context. * @return the debugger data, or null if debugger is not attached */ public final Object getDebuggerContextData() { return debuggerData; } /** * Set the associated debugger. * @param debugger the debugger to be used on callbacks from * the engine. * @param contextData arbitrary object that debugger can use to store * per Context data. */ public final void setDebugger(Debugger debugger, Object contextData) { if (sealed) onSealedMutation(); this.debugger = debugger; debuggerData = contextData; } /** * Return DebuggableScript instance if any associated with the script. * If callable supports DebuggableScript implementation, the method * returns it. Otherwise null is returned. */ public static DebuggableScript getDebuggableView(Script script) { if (script instanceof NativeFunction) { return ((NativeFunction)script).getDebuggableView(); } return null; } /** * Controls certain aspects of script semantics. * Should be overwritten to alter default behavior. * <p> * The default implementation calls * {@link ContextFactory#hasFeature(Context cx, int featureIndex)} * that allows to customize Context behavior without introducing * Context subclasses. {@link ContextFactory} documentation gives * an example of hasFeature implementation. * * @param featureIndex feature index to check * @return true if the <code>featureIndex</code> feature is turned on * @see #FEATURE_NON_ECMA_GET_YEAR * @see #FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME * @see #FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER * @see #FEATURE_TO_STRING_AS_SOURCE * @see #FEATURE_PARENT_PROTO_PROPRTIES * @see #FEATURE_E4X * @see #FEATURE_DYNAMIC_SCOPE * @see #FEATURE_STRICT_VARS * @see #FEATURE_STRICT_EVAL * @see #FEATURE_LOCATION_INFORMATION_IN_ERROR * @see #FEATURE_STRICT_MODE * @see #FEATURE_WARNING_AS_ERROR * @see #FEATURE_ENHANCED_JAVA_ACCESS */ public boolean hasFeature(int featureIndex) { ContextFactory f = getFactory(); return f.hasFeature(this, featureIndex); } /** Returns an object which specifies an E4X implementation to use within this <code>Context</code>. Note that the XMLLib.Factory interface should be considered experimental. The default implementation uses the implementation provided by this <code>Context</code>'s {@link ContextFactory}. @return An XMLLib.Factory. Should not return <code>null</code> if {@link #FEATURE_E4X} is enabled. See {@link #hasFeature}. */ public XMLLib.Factory getE4xImplementationFactory() { return getFactory().getE4xImplementationFactory(); } /** * Get threshold of executed instructions counter that triggers call to * <code>observeInstructionCount()</code>. * When the threshold is zero, instruction counting is disabled, * otherwise each time the run-time executes at least the threshold value * of script instructions, <code>observeInstructionCount()</code> will * be called. */ public final int getInstructionObserverThreshold() { return instructionThreshold; } /** * Set threshold of executed instructions counter that triggers call to * <code>observeInstructionCount()</code>. * When the threshold is zero, instruction counting is disabled, * otherwise each time the run-time executes at least the threshold value * of script instructions, <code>observeInstructionCount()</code> will * be called.<p/> * Note that the meaning of "instruction" is not guaranteed to be * consistent between compiled and interpretive modes: executing a given * script or function in the different modes will result in different * instruction counts against the threshold. * {@link #setGenerateObserverCount} is called with true if * <code>threshold</code> is greater than zero, false otherwise. * @param threshold The instruction threshold */ public final void setInstructionObserverThreshold(int threshold) { if (sealed) onSealedMutation(); if (threshold < 0) throw new IllegalArgumentException(); instructionThreshold = threshold; setGenerateObserverCount(threshold > 0); } /** * Turn on or off generation of code with callbacks to * track the count of executed instructions. * Currently only affects JVM byte code generation: this slows down the * generated code, but code generated without the callbacks will not * be counted toward instruction thresholds. Rhino's interpretive * mode does instruction counting without inserting callbacks, so * there is no requirement to compile code differently. * @param generateObserverCount if true, generated code will contain * calls to accumulate an estimate of the instructions executed. */ public void setGenerateObserverCount(boolean generateObserverCount) { this.generateObserverCount = generateObserverCount; } /** * Allow application to monitor counter of executed script instructions * in Context subclasses. * Run-time calls this when instruction counting is enabled and the counter * reaches limit set by <code>setInstructionObserverThreshold()</code>. * The method is useful to observe long running scripts and if necessary * to terminate them. * <p> * The instruction counting support is available only for interpreted * scripts generated when the optimization level is set to -1. * <p> * The default implementation calls * {@link ContextFactory#observeInstructionCount(Context cx, * int instructionCount)} * that allows to customize Context behavior without introducing * Context subclasses. * * @param instructionCount amount of script instruction executed since * last call to <code>observeInstructionCount</code> * @throws Error to terminate the script * @see #setOptimizationLevel(int) */ protected void observeInstructionCount(int instructionCount) { ContextFactory f = getFactory(); f.observeInstructionCount(this, instructionCount); } /** * Create class loader for generated classes. * The method calls {@link ContextFactory#createClassLoader(ClassLoader)} * using the result of {@link #getFactory()}. */ public GeneratedClassLoader createClassLoader(ClassLoader parent) { ContextFactory f = getFactory(); return f.createClassLoader(parent); } public final ClassLoader getApplicationClassLoader() { if (applicationClassLoader == null) { ContextFactory f = getFactory(); ClassLoader loader = f.getApplicationClassLoader(); if (loader == null) { ClassLoader threadLoader = VMBridge.instance.getCurrentThreadClassLoader(); if (threadLoader != null && Kit.testIfCanLoadRhinoClasses(threadLoader)) { // Thread.getContextClassLoader is not cached since // its caching prevents it from GC which may lead to // a memory leak and hides updates to // Thread.getContextClassLoader return threadLoader; } // Thread.getContextClassLoader can not load Rhino classes, // try to use the loader of ContextFactory or Context // subclasses. Class fClass = f.getClass(); if (fClass != ScriptRuntime.ContextFactoryClass) { loader = fClass.getClassLoader(); } else { loader = getClass().getClassLoader(); } } applicationClassLoader = loader; } return applicationClassLoader; } public final void setApplicationClassLoader(ClassLoader loader) { if (sealed) onSealedMutation(); if (loader == null) { // restore default behaviour applicationClassLoader = null; return; } if (!Kit.testIfCanLoadRhinoClasses(loader)) { throw new IllegalArgumentException( "Loader can not resolve Rhino classes"); } applicationClassLoader = loader; } /********** end of API **********/ /** * Internal method that reports an error for missing calls to * enter(). */ static Context getContext() { Context cx = getCurrentContext(); if (cx == null) { throw new RuntimeException( "No Context associated with current Thread"); } return cx; } private Object compileImpl(Scriptable scope, Reader sourceReader, String sourceString, String sourceName, int lineno, Object securityDomain, boolean returnFunction, Interpreter compiler, ErrorReporter compilationErrorReporter) throws IOException { - if (securityDomain != null && securityController == null) { + if (securityDomain != null && getSecurityController() == null) { throw new IllegalArgumentException( "securityDomain should be null if setSecurityController() was never called"); } // One of sourceReader or sourceString has to be null if (!(sourceReader == null ^ sourceString == null)) Kit.codeBug(); // scope should be given if and only if compiling function if (!(scope == null ^ returnFunction)) Kit.codeBug(); CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); if (compilationErrorReporter == null) { compilationErrorReporter = compilerEnv.getErrorReporter(); } if (debugger != null) { if (sourceReader != null) { sourceString = Kit.readReader(sourceReader); sourceReader = null; } } Parser p = new Parser(compilerEnv, compilationErrorReporter); if (returnFunction) { p.calledByCompileFunction = true; } ScriptOrFnNode tree; if (sourceString != null) { tree = p.parse(sourceString, sourceName, lineno); } else { tree = p.parse(sourceReader, sourceName, lineno); } if (returnFunction) { if (!(tree.getFunctionCount() == 1 && tree.getFirstChild() != null && tree.getFirstChild().getType() == Token.FUNCTION)) { // XXX: the check just look for the first child // and allows for more nodes after it for compatibility // with sources like function() {};;; throw new IllegalArgumentException( "compileFunction only accepts source with single JS function: "+sourceString); } } if (compiler == null) { compiler = createCompiler(); } String encodedSource = p.getEncodedSource(); Object bytecode = compiler.compile(compilerEnv, tree, encodedSource, returnFunction); if (debugger != null) { if (sourceString == null) Kit.codeBug(); if (bytecode instanceof DebuggableScript) { DebuggableScript dscript = (DebuggableScript)bytecode; notifyDebugger_r(this, dscript, sourceString); } else { throw new RuntimeException("NOT SUPPORTED"); } } Object result; if (returnFunction) { result = compiler.createFunctionObject(this, scope, bytecode, securityDomain); } else { result = compiler.createScriptObject(bytecode, securityDomain); } return result; } private static void notifyDebugger_r(Context cx, DebuggableScript dscript, String debugSource) { cx.debugger.handleCompilationDone(cx, dscript, debugSource); for (int i = 0; i != dscript.getFunctionCount(); ++i) { notifyDebugger_r(cx, dscript.getFunction(i), debugSource); } } private static Class codegenClass = Kit.classOrNull( "org.mozilla.javascript.optimizer.Codegen"); private Interpreter createCompiler() { Interpreter result = null; if (optimizationLevel >= 0 && codegenClass != null) { result = (Interpreter)Kit.newInstanceOrNull(codegenClass); } if (result == null) { result = new Interpreter(); } return result; } static String getSourcePositionFromStack(int[] linep) { Context cx = getCurrentContext(); if (cx == null) return null; if (cx.lastInterpreterFrame != null) { return Interpreter.getSourcePositionFromStack(cx, linep); } /** * A bit of a hack, but the only way to get filename and line * number from an enclosing frame. */ CharArrayWriter writer = new CharArrayWriter(); RuntimeException re = new RuntimeException(); re.printStackTrace(new PrintWriter(writer)); String s = writer.toString(); int open = -1; int close = -1; int colon = -1; for (int i=0; i < s.length(); i++) { char c = s.charAt(i); if (c == ':') colon = i; else if (c == '(') open = i; else if (c == ')') close = i; else if (c == '\n' && open != -1 && close != -1 && colon != -1 && open < colon && colon < close) { String fileStr = s.substring(open + 1, colon); if (!fileStr.endsWith(".java")) { String lineStr = s.substring(colon + 1, close); try { linep[0] = Integer.parseInt(lineStr); if (linep[0] < 0) { linep[0] = 0; } return fileStr; } catch (NumberFormatException e) { // fall through } } open = close = colon = -1; } } return null; } RegExpProxy getRegExpProxy() { if (regExpProxy == null) { Class cl = Kit.classOrNull( "org.mozilla.javascript.regexp.RegExpImpl"); if (cl != null) { regExpProxy = (RegExpProxy)Kit.newInstanceOrNull(cl); } } return regExpProxy; } final boolean isVersionECMA1() { return version == VERSION_DEFAULT || version >= VERSION_1_3; } // The method must NOT be public or protected SecurityController getSecurityController() { SecurityController global = SecurityController.global(); if (global != null) { return global; } return securityController; } public final boolean isGeneratingDebugChanged() { return generatingDebugChanged; } /** * Add a name to the list of names forcing the creation of real * activation objects for functions. * * @param name the name of the object to add to the list */ public void addActivationName(String name) { if (sealed) onSealedMutation(); if (activationNames == null) activationNames = new Hashtable(5); activationNames.put(name, name); } /** * Check whether the name is in the list of names of objects * forcing the creation of activation objects. * * @param name the name of the object to test * * @return true if an function activation object is needed. */ public final boolean isActivationNeeded(String name) { return activationNames != null && activationNames.containsKey(name); } /** * Remove a name from the list of names forcing the creation of real * activation objects for functions. * * @param name the name of the object to remove from the list */ public void removeActivationName(String name) { if (sealed) onSealedMutation(); if (activationNames != null) activationNames.remove(name); } private static String implementationVersion; private ContextFactory factory; private boolean sealed; private Object sealKey; Scriptable topCallScope; NativeCall currentActivationCall; XMLLib cachedXMLLib; // for Objects, Arrays to tag themselves as being printed out, // so they don't print themselves out recursively. // Use ObjToIntMap instead of java.util.HashSet for JDK 1.1 compatibility ObjToIntMap iterating; Object interpreterSecurityDomain; int version; private SecurityController securityController; private ClassShutter classShutter; private ErrorReporter errorReporter; RegExpProxy regExpProxy; private Locale locale; private boolean generatingDebug; private boolean generatingDebugChanged; private boolean generatingSource=true; boolean compileFunctionsWithDynamicScopeFlag; boolean useDynamicScope; private int optimizationLevel; private int maximumInterpreterStackDepth; private WrapFactory wrapFactory; Debugger debugger; private Object debuggerData; private int enterCount; private Object propertyListeners; private Hashtable hashtable; private ClassLoader applicationClassLoader; private boolean creationEventWasSent; /** * This is the list of names of objects forcing the creation of * function activation records. */ Hashtable activationNames; // For the interpreter to store the last frame for error reports etc. Object lastInterpreterFrame; // For the interpreter to store information about previous invocations // interpreter invocations ObjArray previousInterpreterInvocations; // For instruction counting (interpreter only) int instructionCount; int instructionThreshold; // It can be used to return the second index-like result from function int scratchIndex; // It can be used to return the second uint32 result from function long scratchUint32; // It can be used to return the second Scriptable result from function Scriptable scratchScriptable; // Generate an observer count on compiled code public boolean generateObserverCount = false; }
true
true
private Object compileImpl(Scriptable scope, Reader sourceReader, String sourceString, String sourceName, int lineno, Object securityDomain, boolean returnFunction, Interpreter compiler, ErrorReporter compilationErrorReporter) throws IOException { if (securityDomain != null && securityController == null) { throw new IllegalArgumentException( "securityDomain should be null if setSecurityController() was never called"); } // One of sourceReader or sourceString has to be null if (!(sourceReader == null ^ sourceString == null)) Kit.codeBug(); // scope should be given if and only if compiling function if (!(scope == null ^ returnFunction)) Kit.codeBug(); CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); if (compilationErrorReporter == null) { compilationErrorReporter = compilerEnv.getErrorReporter(); } if (debugger != null) { if (sourceReader != null) { sourceString = Kit.readReader(sourceReader); sourceReader = null; } } Parser p = new Parser(compilerEnv, compilationErrorReporter); if (returnFunction) { p.calledByCompileFunction = true; } ScriptOrFnNode tree; if (sourceString != null) { tree = p.parse(sourceString, sourceName, lineno); } else { tree = p.parse(sourceReader, sourceName, lineno); } if (returnFunction) { if (!(tree.getFunctionCount() == 1 && tree.getFirstChild() != null && tree.getFirstChild().getType() == Token.FUNCTION)) { // XXX: the check just look for the first child // and allows for more nodes after it for compatibility // with sources like function() {};;; throw new IllegalArgumentException( "compileFunction only accepts source with single JS function: "+sourceString); } } if (compiler == null) { compiler = createCompiler(); } String encodedSource = p.getEncodedSource(); Object bytecode = compiler.compile(compilerEnv, tree, encodedSource, returnFunction); if (debugger != null) { if (sourceString == null) Kit.codeBug(); if (bytecode instanceof DebuggableScript) { DebuggableScript dscript = (DebuggableScript)bytecode; notifyDebugger_r(this, dscript, sourceString); } else { throw new RuntimeException("NOT SUPPORTED"); } } Object result; if (returnFunction) { result = compiler.createFunctionObject(this, scope, bytecode, securityDomain); } else { result = compiler.createScriptObject(bytecode, securityDomain); } return result; }
private Object compileImpl(Scriptable scope, Reader sourceReader, String sourceString, String sourceName, int lineno, Object securityDomain, boolean returnFunction, Interpreter compiler, ErrorReporter compilationErrorReporter) throws IOException { if (securityDomain != null && getSecurityController() == null) { throw new IllegalArgumentException( "securityDomain should be null if setSecurityController() was never called"); } // One of sourceReader or sourceString has to be null if (!(sourceReader == null ^ sourceString == null)) Kit.codeBug(); // scope should be given if and only if compiling function if (!(scope == null ^ returnFunction)) Kit.codeBug(); CompilerEnvirons compilerEnv = new CompilerEnvirons(); compilerEnv.initFromContext(this); if (compilationErrorReporter == null) { compilationErrorReporter = compilerEnv.getErrorReporter(); } if (debugger != null) { if (sourceReader != null) { sourceString = Kit.readReader(sourceReader); sourceReader = null; } } Parser p = new Parser(compilerEnv, compilationErrorReporter); if (returnFunction) { p.calledByCompileFunction = true; } ScriptOrFnNode tree; if (sourceString != null) { tree = p.parse(sourceString, sourceName, lineno); } else { tree = p.parse(sourceReader, sourceName, lineno); } if (returnFunction) { if (!(tree.getFunctionCount() == 1 && tree.getFirstChild() != null && tree.getFirstChild().getType() == Token.FUNCTION)) { // XXX: the check just look for the first child // and allows for more nodes after it for compatibility // with sources like function() {};;; throw new IllegalArgumentException( "compileFunction only accepts source with single JS function: "+sourceString); } } if (compiler == null) { compiler = createCompiler(); } String encodedSource = p.getEncodedSource(); Object bytecode = compiler.compile(compilerEnv, tree, encodedSource, returnFunction); if (debugger != null) { if (sourceString == null) Kit.codeBug(); if (bytecode instanceof DebuggableScript) { DebuggableScript dscript = (DebuggableScript)bytecode; notifyDebugger_r(this, dscript, sourceString); } else { throw new RuntimeException("NOT SUPPORTED"); } } Object result; if (returnFunction) { result = compiler.createFunctionObject(this, scope, bytecode, securityDomain); } else { result = compiler.createScriptObject(bytecode, securityDomain); } return result; }
diff --git a/src/main/java/com/google/dart/Dart2JsMojo.java b/src/main/java/com/google/dart/Dart2JsMojo.java index 9accd55..3405a65 100644 --- a/src/main/java/com/google/dart/Dart2JsMojo.java +++ b/src/main/java/com/google/dart/Dart2JsMojo.java @@ -1,665 +1,667 @@ package com.google.dart; /* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ import com.google.common.collect.ImmutableSet; import com.google.dart.util.OsUtil; import org.apache.commons.io.FileUtils; import org.apache.commons.io.output.StringBuilderWriter; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.codehaus.plexus.compiler.util.scan.InclusionScanException; import org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner; import org.codehaus.plexus.compiler.util.scan.StaleSourceScanner; import org.codehaus.plexus.compiler.util.scan.mapping.SourceMapping; import org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping; import org.codehaus.plexus.util.cli.Arg; import org.codehaus.plexus.util.cli.CommandLineException; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; import org.codehaus.plexus.util.cli.StreamConsumer; import org.codehaus.plexus.util.cli.WriterStreamConsumer; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Goal to compile dart files to javascript. * * @author Daniel Zwicker */ @Mojo(name = "dart2js", defaultPhase = LifecyclePhase.COMPILE, threadSafe = true) public class Dart2JsMojo extends PubMojo { /** * Where to find packages, that is, "package:..." imports. * * @since 2.0 */ private final static String ARGUMENT_CHECKED_MODE = "-c"; /** * Generate the output into <file> * * @since 1.0 */ private final static String ARGUMENT_OUTPUT_FILE = "-o"; /** * Where to find packages, that is, "package:..." imports. * * @since 2.0 */ private final static String ARGUMENT_PACKAGE_PATH = "-p"; /** * Display verbose information. * * @since 1.0.3 */ private final static String ARGUMENT_VERBOSE = "-v"; /** * Analyze all code. Without this option, the compiler only analyzes code that is reachable from [main]. * This option is useful for finding errors in libraries, * but using it can result in bigger and slower output. * * @since 1.0.3 */ private final static String ARGUMENT_ANALYSE_ALL = "--analyze-all"; /** * Generate minified output. * * @since 1.0.3 */ private final static String ARGUMENT_MINIFY = "--minify"; /** * Do not display any warnings. * * @since 1.0.3 */ private final static String ARGUMENT_SUPPRESS_WARNINGS = "--suppress-warnings"; /** * Add colors to diagnostic messages. * * @since 1.0.3 */ private final static String ARGUMENT_DIAGNOSTIC_COLORS = "--enable-diagnostic-colors"; /** * Name of the global variable used by dart2js compiler in the generated code. * The name must match the regular expression "\$[a-z]*". * * @since 2.1.2 */ private final static String ARGUMENT_GLOBAL_JS_NAME = "--global-js-name="; /** * Skip the execution of dart2js. * * @since 1.1 */ @Parameter(defaultValue = "false", property = "dart.skip") private boolean skipDart2Js; /** * Insert runtime type checks and enable assertions (checked mode). * * @since 1.0 */ @Parameter(defaultValue = "false", property = "dart.checkedMode") private boolean checkedMode; /** * Display verbose information. * * @since 1.0.3 */ @Parameter(defaultValue = "false", property = "dart.verbose") private boolean verbose; /** * Analyze all code. Without this option, the compiler only analyzes code that is reachable from [main]. * This option is useful for finding errors in libraries, * but using it can result in bigger and slower output. * * @since 1.0.3 */ @Parameter(defaultValue = "false", property = "dart.analyseAll") private boolean analyseAll; /** * Generate minified output. * * @since 1.0.3 */ @Parameter(defaultValue = "false", property = "dart.minify") private boolean minify; /** * Do not display any warnings. * * @since 1.0.3 */ @Parameter(defaultValue = "false", property = "dart.suppressWarnings") private boolean suppressWarnings; /** * Add colors to diagnostic messages. * * @since 1.0.3 */ @Parameter(defaultValue = "false", property = "dart.diagnosticColors") private boolean diagnosticColors; /** * Where to find packages, that is, "package:..." imports. * * @since 2.0 */ @Parameter(property = "dart.packagepath") private File packagePath; /** * Force compilation of all files. * * @since 2.0.2 */ @Parameter(defaultValue = "false", property = "dart.force") private boolean force; /** * The directory to place the js files after compiling. * <p/> * If not specified the default is 'target/dart'. * * @since 1.0 */ @Parameter(defaultValue = "${project.build.directory}/dart", required = true, property = "dart.outputDirectory") private File outputDirectory; /** * A list of inclusion filters for the dart2js compiler. * <p/> * If not specified the default is 'web&#47;**&#47;*.dart' * * @since 1.0 */ @Parameter private Set<String> includes = new HashSet<>(); /** * A list of exclusion filters for the dart2js compiler. * <p/> * If not specified the default is 'web&#47;**&#47;packages&#47;**' * * @since 1.0 */ @Parameter private final Set<String> excludes = new HashSet<>(); /** * Sets the granularity in milliseconds of the last modification * date for testing whether a dart source needs recompilation. * * @since 1.0 */ @Parameter(property = "lastModGranularityMs", defaultValue = "0") private int staleMillis; /** * Set this to 'true' to skip running dart's packagemanager pub. * * @since 2.0.1 */ @Parameter(defaultValue = "false", property = "dart.pup.skip") private boolean skipPub; /** * Name of the global variable used by dart2js compiler in the generated code. * The name must match the regular expression "\$[a-z]*". * * @since 2.1.2 */ @Parameter(defaultValue = "$", property = "dart.global.js.name") private String globalJsName; /** * The number of threads used to span dart2js instances. * * @since 3.0.0 */ @Parameter(defaultValue = "1", property = "dart.thread.count") private int threadCount; /** * The maximum time in ms all dart files should be compiled. * * @since 3.0.0 */ @Parameter(defaultValue = "0", property = "dart.thread.timeout") private int timeout; public void execute() throws MojoExecutionException { if (isSkipDart2Js()) { getLog().info("skipping dart2js execution"); return; } final Set<File> dartPackageRoots = findDartPackageRoots(); processPubDependencies(dartPackageRoots); processDart2Js(dartPackageRoots); } private void processDart2Js(final Set<File> dartPackageRoots) throws MojoExecutionException { if (isForce()) { clearOutputDirectory(); } final Set<File> staleDartSources = computeStaleSources(dartPackageRoots, getSourceInclusionScanner()); if (getLog().isDebugEnabled()) { getLog().debug("staleMillis: " + staleMillis); getLog().debug("basedir: " + getBasedir()); getLog().debug("outputDirectory: " + outputDirectory); getLog().debug("Source includes:"); for (final String include : getIncludes()) { getLog().debug(" " + include); } getLog().debug("Source excludes:"); for (final String exclude : getExcludes()) { getLog().debug(" " + exclude); } } checkAndCreateOutputDirectory(); System.out.println(); System.out.println(); //threads if (staleDartSources.isEmpty()) { getLog().info("Nothing to compile - all dart javascripts are up to date"); } else { checkDart2Js(); final ExecutorService executor = Executors.newFixedThreadPool(threadCount); getLog().info("Run " + threadCount + " dart2js's in parallel."); getLog().info("Compile " + staleDartSources.size() + " dart files"); final List<Future<List<String>>> logging = new ArrayList<>(staleDartSources.size()); for (final File dartSourceFile : staleDartSources) { getLog().info("Queue " + dartSourceFile.getAbsolutePath() + " to compile."); logging.add( executor.submit(new Callable<List<String>>() { @Override public List<String> call() throws Exception { getLog().info("compile " + dartSourceFile.getAbsolutePath()); final List<String> messages = new ArrayList<>(); try { final Commandline cl = createBaseCommandline(messages); final Arg outPutFileArg = cl.createArg(); final Arg dartFileArg = cl.createArg(); final File dartOutputFile = createOutputFileArgument(messages, outPutFileArg, dartSourceFile); createDartFileArgument(messages, dartFileArg, dartSourceFile); if (getLog().isDebugEnabled()) { messages.add("debug#" + cl.toString()); } if (!dartOutputFile.getParentFile().exists()) { if (getLog().isDebugEnabled()) { messages.add("debug#Create directory " + dartOutputFile.getParentFile().getAbsolutePath()); } dartOutputFile.getParentFile().mkdirs(); } if (getLog().isDebugEnabled()) { messages.add("debug#" + cl.toString()); } final StringBuilderWriter writer = new StringBuilderWriter(); final StreamConsumer output = new WriterStreamConsumer(writer); final int returnValue = CommandLineUtils.executeCommandLine(cl, output, output); writer.flush(); writer.close(); final StringBuilder stringBuilder = writer.getBuilder(); messages.add("info#" + stringBuilder.toString()); if (getLog().isDebugEnabled()) { messages.add("debug#dart2js return code: " + returnValue); } if (returnValue != 0) { throw new MojoExecutionException("Dart2Js returned error code " + returnValue); } System.out.println(); System.out.println(); } catch (final CommandLineException e) { messages.add("error#dart2js error: " + e.getMessage()); getLog().error("dart2js error", e); } getLog().info("done " + dartSourceFile.getAbsolutePath()); return messages; } }) ); } executor.shutdown(); try { if (timeout > 0) { executor.awaitTermination(timeout, TimeUnit.MILLISECONDS); } logResults(logging); getLog().info( "Compiling " + staleDartSources.size() + " dart file" + (staleDartSources.size() == 1 ? "" : "s") + " to " + outputDirectory.getAbsolutePath()); - } catch (InterruptedException | ExecutionException | TimeoutException e) { - throw new MojoExecutionException("Unable to compile al dart files with in " + timeout + "ms. Perhaps increase it."); + } catch (InterruptedException | TimeoutException e) { + throw new MojoExecutionException("Unable to compile al dart files with in " + timeout + "ms. Perhaps increase it.", e); + } catch (ExecutionException e) { + throw new MojoExecutionException("Unable to compile al dart files.", e); } } System.out.println(); System.out.println(); } private void logResults(List<Future<List<String>>> logging) throws InterruptedException, ExecutionException, TimeoutException { for (final Future<List<String>> future : logging) { final List<String> messages = future.get(0, TimeUnit.MILLISECONDS); for (final String logMessage : messages) { final String[] m = logMessage.split("#"); if (m.length > 1) { final String level = m[0]; final String message = m[1]; switch (level) { case "debug": getLog().debug(message); break; case "info": getLog().info(message); break; case "warn": getLog().warn(message); break; case "error": getLog().error(message); break; } } else { // defaults to info getLog().info(logMessage); } } } } private Commandline createBaseCommandline(List<String> messages) throws MojoExecutionException { final String dart2jsPath = getDart2JsExecutable().getAbsolutePath(); if (getLog().isDebugEnabled()) { messages.add("debug#Using dart2js '" + dart2jsPath + "'."); messages.add("debug#Source directories: " + getCompileSourceRoots().toString().replace(',', '\n')); messages.add("debug#Output directory: " + getOutputDirectory()); } final Commandline cl = new Commandline(); cl.setExecutable(dart2jsPath); if (isCheckedMode()) { cl.createArg().setValue(ARGUMENT_CHECKED_MODE); } if (isVerbose()) { cl.createArg().setValue(ARGUMENT_VERBOSE); } if (isAnalyseAll()) { cl.createArg().setValue(ARGUMENT_ANALYSE_ALL); } if (isMinify()) { cl.createArg().setValue(ARGUMENT_MINIFY); } if (isSuppressWarnings()) { cl.createArg().setValue(ARGUMENT_SUPPRESS_WARNINGS); } if (isDiagnosticColors()) { cl.createArg().setValue(ARGUMENT_DIAGNOSTIC_COLORS); } if (isPackagePath()) { cl.createArg().setValue(ARGUMENT_PACKAGE_PATH + packagePath.getAbsolutePath()); } cl.createArg().setValue(ARGUMENT_GLOBAL_JS_NAME + globalJsName); if (getLog().isDebugEnabled()) { messages.add("debug#Base dart2js command: " + cl.toString()); } return cl; } protected void checkDart2Js() { checkDartSdk(); if (!getDart2JsExecutable().canExecute()) { throw new IllegalArgumentException("Dart2js not executable! Configuration error for dartSdk? dartSdk=" + getDartSdk().getAbsolutePath()); } } protected File getDart2JsExecutable() { return new File(getDartSdk(), "bin/dart2js" + (OsUtil.isWindows() ? ".bat" : "")); } private void clearOutputDirectory() throws MojoExecutionException { try { if (outputDirectory.exists()) { FileUtils.cleanDirectory(outputDirectory); getLog().info("Cleared all compiled dart-files."); } } catch (IOException e) { getLog().debug("Unable to clear directory '" + outputDirectory.getAbsolutePath() + "'.", e); throw new MojoExecutionException("Unable to clear directory '" + outputDirectory.getAbsolutePath() + "'.", e); } } private void checkAndCreateOutputDirectory() throws MojoExecutionException { if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } else if (!outputDirectory.isDirectory()) { throw new MojoExecutionException( "Fatal error compiling dart to js. Output directory is not a directory"); } } private void createDartFileArgument(List<String> messages, final Arg compilerArguments, final File dartSourceFile) { final String dartSourceFileAbsolutePath = dartSourceFile.getAbsolutePath(); compilerArguments.setValue(dartSourceFileAbsolutePath); messages.add("info#dart2js for '" + relativePath(dartSourceFile) + "'"); } private File createOutputFileArgument(List<String> messages, final Arg outPutFileArg, final File dartSourceFile) throws MojoExecutionException { final String dartSourceFileAbsolutePath = dartSourceFile.getAbsolutePath(); String dartOutputFileRelativeToBasedir = null; for (final File compileSourceRoot : getCompileSourceRoots()) { final String compileSourceRootAsString = compileSourceRoot.getAbsolutePath(); if (dartSourceFileAbsolutePath.startsWith(compileSourceRootAsString)) { dartOutputFileRelativeToBasedir = dartSourceFileAbsolutePath.replace(compileSourceRootAsString, ""); dartOutputFileRelativeToBasedir += ".js"; break; } } if (dartOutputFileRelativeToBasedir == null) { messages.add("error#Unable to find compilerSourceRoot for dart file '" + dartSourceFileAbsolutePath + "'"); messages.add("error#compilerSourceRoots are:"); for (final File compileSourceRoot : getCompileSourceRoots()) { getLog().error(compileSourceRoot.getAbsolutePath()); } System.out.println(""); System.out.println(""); throw new MojoExecutionException("There is something wrong. "); } final String dartOutputFile = outputDirectory.getAbsolutePath() + dartOutputFileRelativeToBasedir; if (getLog().isDebugEnabled()) { messages.add("debug#dart2js compiles dart-file '" + dartSourceFileAbsolutePath + "' to outputdirectory '" + dartOutputFile + "'"); } outPutFileArg.setValue(ARGUMENT_OUTPUT_FILE + dartOutputFile); return new File(dartOutputFile); } private Set<File> computeStaleSources(final Set<File> packageRoots, final SourceInclusionScanner scanner) throws MojoExecutionException { final SourceMapping mapping = new SuffixMapping("dart", "dart.js"); scanner.addSourceMapping(mapping); final Set<File> staleSources = new HashSet<>(); for (final File packageRoot : packageRoots) { try { final File packageOutputDirectory = getPackageOutputDirectory(packageRoot); staleSources.addAll(scanner.getIncludedSources(packageRoot, packageOutputDirectory)); } catch (final InclusionScanException e) { throw new MojoExecutionException( "Error scanning source root: \'" + relativePath(packageRoot) + "\' for stale files to recompile.", e); } } return staleSources; } private File getPackageOutputDirectory(final File packageRoot) { String packageRootOffset = packageRoot.getAbsolutePath(); for (final File compileSourceRoot : getCompileSourceRoots()) { final String compileSourceRootAsString = compileSourceRoot.getAbsolutePath(); if (packageRootOffset.startsWith(compileSourceRootAsString)) { packageRootOffset = packageRootOffset.replace(compileSourceRootAsString + "/", ""); break; } } return new File(getOutputDirectory(), packageRootOffset); } private SourceInclusionScanner getSourceInclusionScanner() { return new StaleSourceScanner(getStaleMillis(), getIncludes(), getExcludes()); } public Set<String> getIncludes() { if (includes.isEmpty()) { return ImmutableSet.copyOf(Arrays.asList(new String[]{"web/**/*.dart"})); } return includes; } protected Set<String> getExcludes() { if (excludes.isEmpty()) { return ImmutableSet.copyOf(Arrays.asList(new String[]{"web/**/packages/**"})); } return excludes; } @Override public boolean isPubSkipped() { return skipPub; } protected boolean isSkipDart2Js() { return skipDart2Js; } protected File getOutputDirectory() { return outputDirectory; } protected boolean isCheckedMode() { return checkedMode; } protected int getStaleMillis() { return staleMillis; } protected boolean isVerbose() { return verbose; } protected boolean isAnalyseAll() { return analyseAll; } protected boolean isMinify() { return minify; } protected boolean isSuppressWarnings() { return suppressWarnings; } protected boolean isDiagnosticColors() { return diagnosticColors; } protected boolean isForce() { return force; } protected boolean isPackagePath() { return packagePath != null; } }
true
true
private void processDart2Js(final Set<File> dartPackageRoots) throws MojoExecutionException { if (isForce()) { clearOutputDirectory(); } final Set<File> staleDartSources = computeStaleSources(dartPackageRoots, getSourceInclusionScanner()); if (getLog().isDebugEnabled()) { getLog().debug("staleMillis: " + staleMillis); getLog().debug("basedir: " + getBasedir()); getLog().debug("outputDirectory: " + outputDirectory); getLog().debug("Source includes:"); for (final String include : getIncludes()) { getLog().debug(" " + include); } getLog().debug("Source excludes:"); for (final String exclude : getExcludes()) { getLog().debug(" " + exclude); } } checkAndCreateOutputDirectory(); System.out.println(); System.out.println(); //threads if (staleDartSources.isEmpty()) { getLog().info("Nothing to compile - all dart javascripts are up to date"); } else { checkDart2Js(); final ExecutorService executor = Executors.newFixedThreadPool(threadCount); getLog().info("Run " + threadCount + " dart2js's in parallel."); getLog().info("Compile " + staleDartSources.size() + " dart files"); final List<Future<List<String>>> logging = new ArrayList<>(staleDartSources.size()); for (final File dartSourceFile : staleDartSources) { getLog().info("Queue " + dartSourceFile.getAbsolutePath() + " to compile."); logging.add( executor.submit(new Callable<List<String>>() { @Override public List<String> call() throws Exception { getLog().info("compile " + dartSourceFile.getAbsolutePath()); final List<String> messages = new ArrayList<>(); try { final Commandline cl = createBaseCommandline(messages); final Arg outPutFileArg = cl.createArg(); final Arg dartFileArg = cl.createArg(); final File dartOutputFile = createOutputFileArgument(messages, outPutFileArg, dartSourceFile); createDartFileArgument(messages, dartFileArg, dartSourceFile); if (getLog().isDebugEnabled()) { messages.add("debug#" + cl.toString()); } if (!dartOutputFile.getParentFile().exists()) { if (getLog().isDebugEnabled()) { messages.add("debug#Create directory " + dartOutputFile.getParentFile().getAbsolutePath()); } dartOutputFile.getParentFile().mkdirs(); } if (getLog().isDebugEnabled()) { messages.add("debug#" + cl.toString()); } final StringBuilderWriter writer = new StringBuilderWriter(); final StreamConsumer output = new WriterStreamConsumer(writer); final int returnValue = CommandLineUtils.executeCommandLine(cl, output, output); writer.flush(); writer.close(); final StringBuilder stringBuilder = writer.getBuilder(); messages.add("info#" + stringBuilder.toString()); if (getLog().isDebugEnabled()) { messages.add("debug#dart2js return code: " + returnValue); } if (returnValue != 0) { throw new MojoExecutionException("Dart2Js returned error code " + returnValue); } System.out.println(); System.out.println(); } catch (final CommandLineException e) { messages.add("error#dart2js error: " + e.getMessage()); getLog().error("dart2js error", e); } getLog().info("done " + dartSourceFile.getAbsolutePath()); return messages; } }) ); } executor.shutdown(); try { if (timeout > 0) { executor.awaitTermination(timeout, TimeUnit.MILLISECONDS); } logResults(logging); getLog().info( "Compiling " + staleDartSources.size() + " dart file" + (staleDartSources.size() == 1 ? "" : "s") + " to " + outputDirectory.getAbsolutePath()); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new MojoExecutionException("Unable to compile al dart files with in " + timeout + "ms. Perhaps increase it."); } } System.out.println(); System.out.println(); }
private void processDart2Js(final Set<File> dartPackageRoots) throws MojoExecutionException { if (isForce()) { clearOutputDirectory(); } final Set<File> staleDartSources = computeStaleSources(dartPackageRoots, getSourceInclusionScanner()); if (getLog().isDebugEnabled()) { getLog().debug("staleMillis: " + staleMillis); getLog().debug("basedir: " + getBasedir()); getLog().debug("outputDirectory: " + outputDirectory); getLog().debug("Source includes:"); for (final String include : getIncludes()) { getLog().debug(" " + include); } getLog().debug("Source excludes:"); for (final String exclude : getExcludes()) { getLog().debug(" " + exclude); } } checkAndCreateOutputDirectory(); System.out.println(); System.out.println(); //threads if (staleDartSources.isEmpty()) { getLog().info("Nothing to compile - all dart javascripts are up to date"); } else { checkDart2Js(); final ExecutorService executor = Executors.newFixedThreadPool(threadCount); getLog().info("Run " + threadCount + " dart2js's in parallel."); getLog().info("Compile " + staleDartSources.size() + " dart files"); final List<Future<List<String>>> logging = new ArrayList<>(staleDartSources.size()); for (final File dartSourceFile : staleDartSources) { getLog().info("Queue " + dartSourceFile.getAbsolutePath() + " to compile."); logging.add( executor.submit(new Callable<List<String>>() { @Override public List<String> call() throws Exception { getLog().info("compile " + dartSourceFile.getAbsolutePath()); final List<String> messages = new ArrayList<>(); try { final Commandline cl = createBaseCommandline(messages); final Arg outPutFileArg = cl.createArg(); final Arg dartFileArg = cl.createArg(); final File dartOutputFile = createOutputFileArgument(messages, outPutFileArg, dartSourceFile); createDartFileArgument(messages, dartFileArg, dartSourceFile); if (getLog().isDebugEnabled()) { messages.add("debug#" + cl.toString()); } if (!dartOutputFile.getParentFile().exists()) { if (getLog().isDebugEnabled()) { messages.add("debug#Create directory " + dartOutputFile.getParentFile().getAbsolutePath()); } dartOutputFile.getParentFile().mkdirs(); } if (getLog().isDebugEnabled()) { messages.add("debug#" + cl.toString()); } final StringBuilderWriter writer = new StringBuilderWriter(); final StreamConsumer output = new WriterStreamConsumer(writer); final int returnValue = CommandLineUtils.executeCommandLine(cl, output, output); writer.flush(); writer.close(); final StringBuilder stringBuilder = writer.getBuilder(); messages.add("info#" + stringBuilder.toString()); if (getLog().isDebugEnabled()) { messages.add("debug#dart2js return code: " + returnValue); } if (returnValue != 0) { throw new MojoExecutionException("Dart2Js returned error code " + returnValue); } System.out.println(); System.out.println(); } catch (final CommandLineException e) { messages.add("error#dart2js error: " + e.getMessage()); getLog().error("dart2js error", e); } getLog().info("done " + dartSourceFile.getAbsolutePath()); return messages; } }) ); } executor.shutdown(); try { if (timeout > 0) { executor.awaitTermination(timeout, TimeUnit.MILLISECONDS); } logResults(logging); getLog().info( "Compiling " + staleDartSources.size() + " dart file" + (staleDartSources.size() == 1 ? "" : "s") + " to " + outputDirectory.getAbsolutePath()); } catch (InterruptedException | TimeoutException e) { throw new MojoExecutionException("Unable to compile al dart files with in " + timeout + "ms. Perhaps increase it.", e); } catch (ExecutionException e) { throw new MojoExecutionException("Unable to compile al dart files.", e); } } System.out.println(); System.out.println(); }
diff --git a/src/gui/NuevaPersonaController.java b/src/gui/NuevaPersonaController.java index eeb29cf..7651642 100644 --- a/src/gui/NuevaPersonaController.java +++ b/src/gui/NuevaPersonaController.java @@ -1,34 +1,34 @@ package gui; import core.Persona; import persistence.Persistence; public class NuevaPersonaController { private Persona _persona; private NuevaPersona _screen; public NuevaPersonaController(int tipo) { this._screen = new NuevaPersona(tipo); } public NuevaPersona getScreen() { return _screen; } public Persona getPersona() { return _persona; } public void guardarPersona() { Persistence guardado = new Persistence(); - _persona = new Persona(1, _screen.getCedula(), _screen.getNombre(), + _persona = new Persona(_screen.getTipo(), _screen.getCedula(), _screen.getNombre(), _screen.getTelefono(), _screen.getDireccion(), _screen.getCorreo(), _screen.getNotas()); try { guardado.guardarPersona(_persona); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
true
public void guardarPersona() { Persistence guardado = new Persistence(); _persona = new Persona(1, _screen.getCedula(), _screen.getNombre(), _screen.getTelefono(), _screen.getDireccion(), _screen.getCorreo(), _screen.getNotas()); try { guardado.guardarPersona(_persona); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void guardarPersona() { Persistence guardado = new Persistence(); _persona = new Persona(_screen.getTipo(), _screen.getCedula(), _screen.getNombre(), _screen.getTelefono(), _screen.getDireccion(), _screen.getCorreo(), _screen.getNotas()); try { guardado.guardarPersona(_persona); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/src/net/sf/gogui/gui/GameInfo.java b/src/net/sf/gogui/gui/GameInfo.java index 8e029c9b..bea3c0da 100644 --- a/src/net/sf/gogui/gui/GameInfo.java +++ b/src/net/sf/gogui/gui/GameInfo.java @@ -1,170 +1,170 @@ //---------------------------------------------------------------------------- // $Id$ // $Source$ //---------------------------------------------------------------------------- package net.sf.gogui.gui; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import net.sf.gogui.game.Node; import net.sf.gogui.game.NodeUtils; import net.sf.gogui.go.Board; import net.sf.gogui.go.GoColor; import net.sf.gogui.go.GoPoint; import net.sf.gogui.go.Move; //---------------------------------------------------------------------------- /** Panel displaying information about the current position. */ public class GameInfo extends JPanel implements ActionListener { public GameInfo(Clock clock) { super(new GridLayout(0, 2, GuiUtils.SMALL_PAD, GuiUtils.SMALL_PAD)); m_clock = clock; m_move = addEntry("To play:"); m_number = addEntry("Moves:"); m_last = addEntry("Last move:"); m_variation = addEntry("Variation:"); m_captB = addEntry("Captured Black:"); m_captW = addEntry("Captured White:"); m_timeB = addEntry("Time Black:"); m_timeW = addEntry("Time White:"); m_timeB.setText("00:00"); m_timeW.setText("00:00"); new javax.swing.Timer(1000, this).start(); } public void actionPerformed(ActionEvent evt) { if (m_clock.isRunning()) updateTime(); } public void fastUpdateMoveNumber(Node node) { updateMoveNumber(node); m_number.paintImmediately(m_number.getVisibleRect()); } public void update(Node node, Board board) { if (board.getToMove() == GoColor.BLACK) m_move.setText("Black"); else m_move.setText("White"); int capturedB = board.getCapturedB(); if (capturedB == 0) m_captB.setText(""); else m_captB.setText(Integer.toString(capturedB)); int capturedW = board.getCapturedW(); if (capturedW == 0) m_captW.setText(""); else - m_captW.setText(Integer.toString(capturedB)); + m_captW.setText(Integer.toString(capturedW)); updateMoveNumber(node); String lastMove = ""; Move move = node.getMove(); if (move != null) { GoColor c = move.getColor(); GoPoint p = move.getPoint(); lastMove = (c == GoColor.BLACK ? "B " : "W "); if (p == null) lastMove += "PASS"; else lastMove += p.toString(); } m_last.setText(lastMove); m_variation.setText(NodeUtils.getVariationString(node)); double timeLeftBlack = node.getTimeLeft(GoColor.BLACK); int movesLeftBlack = node.getMovesLeft(GoColor.BLACK); if (! Double.isNaN(timeLeftBlack)) m_timeB.setText(Clock.getTimeString(timeLeftBlack, movesLeftBlack)); double timeLeftWhite = node.getTimeLeft(GoColor.WHITE); int movesLeftWhite = node.getMovesLeft(GoColor.WHITE); if (! Double.isNaN(timeLeftWhite)) m_timeW.setText(Clock.getTimeString(timeLeftWhite, movesLeftWhite)); } public void updateTime() { updateTime(GoColor.BLACK); updateTime(GoColor.WHITE); } /** Serial version to suppress compiler warning. Contains a marker comment for serialver.sourceforge.net */ private static final long serialVersionUID = 0L; // SUID private final JTextField m_move; private final JTextField m_number; private final JTextField m_last; private final JTextField m_captB; private final JTextField m_captW; private final JTextField m_timeB; private final JTextField m_timeW; private final JTextField m_variation; private final Clock m_clock; private JTextField addEntry(String text) { JLabel label = new JLabel(text); label.setHorizontalAlignment(SwingConstants.LEFT); add(label); JTextField entry = new JTextField(" "); entry.setHorizontalAlignment(SwingConstants.LEFT); entry.setEditable(false); entry.setFocusable(false); add(entry); return entry; } private void updateMoveNumber(Node node) { int moveNumber = NodeUtils.getMoveNumber(node); int movesLeft = NodeUtils.getMovesLeft(node); if (moveNumber == 0 && movesLeft == 0) m_number.setText(""); else { String numberString = Integer.toString(moveNumber); if (movesLeft > 0) numberString += "/" + (moveNumber + movesLeft); m_number.setText(numberString); } } private void updateTime(GoColor color) { String text = m_clock.getTimeString(color); if (text == null) text = " "; if (color == GoColor.BLACK) m_timeB.setText(text); else m_timeW.setText(text); } } //----------------------------------------------------------------------------
true
true
public void update(Node node, Board board) { if (board.getToMove() == GoColor.BLACK) m_move.setText("Black"); else m_move.setText("White"); int capturedB = board.getCapturedB(); if (capturedB == 0) m_captB.setText(""); else m_captB.setText(Integer.toString(capturedB)); int capturedW = board.getCapturedW(); if (capturedW == 0) m_captW.setText(""); else m_captW.setText(Integer.toString(capturedB)); updateMoveNumber(node); String lastMove = ""; Move move = node.getMove(); if (move != null) { GoColor c = move.getColor(); GoPoint p = move.getPoint(); lastMove = (c == GoColor.BLACK ? "B " : "W "); if (p == null) lastMove += "PASS"; else lastMove += p.toString(); } m_last.setText(lastMove); m_variation.setText(NodeUtils.getVariationString(node)); double timeLeftBlack = node.getTimeLeft(GoColor.BLACK); int movesLeftBlack = node.getMovesLeft(GoColor.BLACK); if (! Double.isNaN(timeLeftBlack)) m_timeB.setText(Clock.getTimeString(timeLeftBlack, movesLeftBlack)); double timeLeftWhite = node.getTimeLeft(GoColor.WHITE); int movesLeftWhite = node.getMovesLeft(GoColor.WHITE); if (! Double.isNaN(timeLeftWhite)) m_timeW.setText(Clock.getTimeString(timeLeftWhite, movesLeftWhite)); }
public void update(Node node, Board board) { if (board.getToMove() == GoColor.BLACK) m_move.setText("Black"); else m_move.setText("White"); int capturedB = board.getCapturedB(); if (capturedB == 0) m_captB.setText(""); else m_captB.setText(Integer.toString(capturedB)); int capturedW = board.getCapturedW(); if (capturedW == 0) m_captW.setText(""); else m_captW.setText(Integer.toString(capturedW)); updateMoveNumber(node); String lastMove = ""; Move move = node.getMove(); if (move != null) { GoColor c = move.getColor(); GoPoint p = move.getPoint(); lastMove = (c == GoColor.BLACK ? "B " : "W "); if (p == null) lastMove += "PASS"; else lastMove += p.toString(); } m_last.setText(lastMove); m_variation.setText(NodeUtils.getVariationString(node)); double timeLeftBlack = node.getTimeLeft(GoColor.BLACK); int movesLeftBlack = node.getMovesLeft(GoColor.BLACK); if (! Double.isNaN(timeLeftBlack)) m_timeB.setText(Clock.getTimeString(timeLeftBlack, movesLeftBlack)); double timeLeftWhite = node.getTimeLeft(GoColor.WHITE); int movesLeftWhite = node.getMovesLeft(GoColor.WHITE); if (! Double.isNaN(timeLeftWhite)) m_timeW.setText(Clock.getTimeString(timeLeftWhite, movesLeftWhite)); }
diff --git a/src/java/com/idega/block/cal/presentation/CalendarView.java b/src/java/com/idega/block/cal/presentation/CalendarView.java index d7daf76..6316a62 100644 --- a/src/java/com/idega/block/cal/presentation/CalendarView.java +++ b/src/java/com/idega/block/cal/presentation/CalendarView.java @@ -1,1191 +1,1191 @@ /* * Created on Jan 16, 2004 */ package com.idega.block.cal.presentation; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import com.idega.block.cal.business.CalBusiness; import com.idega.block.cal.data.CalendarEntry; import com.idega.block.cal.data.CalendarLedger; import com.idega.idegaweb.IWApplicationContext; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWResourceBundle; import com.idega.idegaweb.presentation.CalendarParameters; import com.idega.idegaweb.presentation.SmallCalendar; import com.idega.presentation.Block; import com.idega.presentation.IWContext; import com.idega.presentation.Image; import com.idega.presentation.Layer; import com.idega.presentation.Page; import com.idega.presentation.Table; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.user.business.UserBusiness; import com.idega.user.data.Group; import com.idega.user.data.User; import com.idega.util.IWCalendar; import com.idega.util.IWTimestamp; /** * Description: <br> * Copyright: Idega Software 2004 <br> * Company: Idega Software <br> * @author <a href="mailto:[email protected]">Birna Iris Jonsdottir</a> */ public class CalendarView extends Block{ private final static String IW_BUNDLE_IDENTIFIER = "com.idega.block.cal"; private int view = CalendarParameters.MONTH; private final static String PARAMETER_ISI_GROUP_ID = "group_id"; private IWTimestamp now = null; private IWTimestamp timeStamp = null; private IWCalendar cal = null; private int beginHour = 6; private int endHour = 24; private String borderWhiteTableStyle = "borderAllWhite"; private String mainTableStyle = "main"; private String menuTableStyle = "menu"; private String borderLeftTopRight = "borderLeftTopRight"; private String styledLink = "styledLink"; private String entryLink = "entryLink"; private String entryLinkActive = "entryLinkActive"; private String bold = "bold"; private String headline ="headline"; private String ledgerListStyle = "ledgerList"; public static String ACTION = "action"; public static String OPEN = "open"; public static String CLOSE = "close"; private String action = null; private CalBusiness calBiz; private int userID = -1; private int groupID = -2; public CalendarView() { } public String getCategoryType() { return ""; } public boolean getMultible() { return true; } /** * draws the day view of the CalendarView * By default the day view varies from 8:00 until 17:00 * but can be changed via setBeginHour(int hour) and setEndHour(int hour) */ public Table dayView(IWContext iwc, IWTimestamp stamp) { //row is 2 because in the first row info on the day (name etc. are printed) int row = 2; now = new IWTimestamp(); Link right = getRightLink(iwc); Link left = getLeftLink(iwc); addNextDayPrm(right,timeStamp); addLastDayPrm(left,timeStamp); Table backTable = new Table(); backTable.setColor("#cccccc"); backTable.setCellspacing(1); backTable.setCellpadding(0); backTable.setWidth(500); backTable.setHeight(400); backTable.mergeCells(1,1,2,1); String dateString = stamp.getDateString("dd MMMMMMMM, yyyy",iwc.getCurrentLocale()); Table headTable = new Table(); headTable.setCellpadding(0); headTable.setCellspacing(0); headTable.setWidth("100%"); headTable.setHeight("100%"); headTable.setStyleClass(mainTableStyle); headTable.setVerticalAlignment(1,1,"top"); headTable.add(left,1,1); headTable.add(Text.NON_BREAKING_SPACE,1,1); headTable.add(dateString,1,1); headTable.add(Text.NON_BREAKING_SPACE,1,1); headTable.add(right,1,1); headTable.setAlignment(2,1,"right"); headTable.add(getIconTable(iwc),2,1); backTable.add(headTable,1,1); //the outer for-loop goes through the hours and prints out //the style for each cell, //the entrylist for each hour for(int i=beginHour;i<=endHour;i++) { backTable.setHeight(1,row,"40"); backTable.setHeight(2,row,"40"); Table dayTable = new Table(); dayTable.setCellspacing(0); dayTable.setCellpadding(1); dayTable.setWidth("100%"); dayTable.setHeight("100%"); Table entryTable = new Table(); entryTable.setCellspacing(0); entryTable.setCellpadding(1); entryTable.setWidth("100%"); entryTable.setHeight("100%"); entryTable.setColor(1,1,"#ffffff"); now.setTime(i,0,0); dayTable.add(now.getTime().toString(),1,1); dayTable.setColor(1,1,"#ffffff"); backTable.add(dayTable,1,row); backTable.setWidth(1,row,"20%"); Timestamp fromStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S")); fromStamp.setHours(beginHour); fromStamp.setMinutes(0); fromStamp.setNanos(0); Timestamp toStamp =Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S")); toStamp.setHours(endHour); toStamp.setMinutes(0); toStamp.setNanos(0); List listOfEntries = (List) getCalBusiness(iwc).getEntriesBetweenTimestamps(fromStamp,toStamp); User user = null; Integer userID = null; if(iwc.isLoggedOn()) { user = iwc.getCurrentUser(); userID = (Integer) user.getPrimaryKey(); } //the inner for-loop goes through the list of entries and prints them out as a link //the link opens the view for the entry for(int j=0; j<listOfEntries.size(); j++) { CalendarEntry entry = (CalendarEntry) listOfEntries.get(j); CalendarLedger ledger = null; int groupIDInLedger = -1; boolean isInGroup = false; //get a collection of groups the current user may view Collection viewGroups = null; if(user != null) { try { viewGroups = getUserBusiness(iwc).getUserGroups(user); }catch(Exception e) { e.printStackTrace(); } } if(entry.getLedgerID() != -1) { ledger = getCalBusiness(iwc).getLedger(entry.getLedgerID()); if(ledger != null) { groupIDInLedger = ledger.getGroupID(); } } else { groupIDInLedger = -1; } if(viewGroups != null) { Iterator viewGroupsIter = viewGroups.iterator(); //goes through the groups the user may view and prints out the entry if //the group connected to the entry is the same as the group the user may view while(viewGroupsIter.hasNext()) { Group group =(Group) viewGroupsIter.next(); Integer groupID = (Integer) group.getPrimaryKey(); if(entry.getGroupID() == groupID.intValue() || groupIDInLedger == groupID.intValue()) { isInGroup = true; } } } if(groupIDInLedger == getViewGroupID()) { isInGroup = true; } if(isInGroup || iwc.isSuperAdmin() || getViewGroupID() == entry.getGroupID() || userID.intValue() == entry.getUserID()) { Timestamp fStamp = entry.getDate(); Timestamp tStamp = entry.getEndDate(); //i is the current hour if(i <= tStamp.getHours() && i >= fStamp.getHours()) { entry.getGroupID(); String headline = getEntryHeadline(entry); Link headlineLink = new Link(headline); headlineLink.addParameter(ACTION,OPEN); headlineLink.addParameter(CalendarParameters.PARAMETER_VIEW,view); headlineLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear()); headlineLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth()); headlineLink.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay()); headlineLink.addParameter("entryID", entry.getPrimaryKey().toString()); if(!iwc.getAccessController().hasRole("cal_view_entry_creator",iwc)) { headlineLink.setWindowToOpen(EntryInfoWindow.class); } headlineLink.setStyleClass(entryLink); entryTable.add(headlineLink,1,1); entryTable.add("<br>",1,1); } } } backTable.add(entryTable,2,row); row++; } return backTable; } /** * draws the week view of the CalendarView * By default the week view varies from 8:00 until 17:00 * but can be changed via setBeginHour(int hour) and setEndHour(int hour) */ public Table weekView(IWContext iwc,IWTimestamp stamp) { IWResourceBundle iwrb = getResourceBundle(iwc); int row = 1; int column = 1; int day = 0; /* * now holds the current time */ now = new IWTimestamp(); // Link right = getRightLink(iwc); // Link left = getLeftLink(iwc); // addNextWeekPrm(right,timeStamp); // addLastWeekPrm(left,timeStamp); Table backTable = new Table(); backTable.setColor("#cccccc"); backTable.setCellspacing(1); backTable.setCellpadding(0); backTable.setWidth(500); backTable.setHeight(400); /* * timeStamp is used to traverse trough the week */ // IWTimestamp tStamp = new IWTimestamp(); cal = new IWCalendar(); Text nameOfDay = new Text(); Table headTable = new Table(); headTable.setWidth("100%"); headTable.setHeight("100%"); headTable.setCellpadding(0); headTable.setCellspacing(0); headTable.setStyleClass(mainTableStyle); headTable.setAlignment(2,1,"right"); String yearString = stamp.getDateString("yyyy"); // headTable.add(left,1,1); headTable.add(iwrb.getLocalizedString("calView.week_of_year","Week of the year") + " " + stamp.getWeekOfYear() + "<br>" + yearString,1,1); // headTable.add(right,1,1); headTable.add(getIconTable(iwc),2,1); backTable.mergeCells(1,1,8,1); backTable.add(headTable,1,1); int weekdays = 8; int weekday = cal.getDayOfWeek(now.getYear(),now.getMonth(),now.getDay()); int today = stamp.getDay(); /* * The outer for-loop runs through the columns of the weekTable * the weekdays */ for(int i=0;i<weekdays; i++) { row = 2; /* * The inner for-loop runs through the rows of the weekTable * the hours */ for(int j=beginHour;j<=endHour;j++) { Table weekTable = new Table(); weekTable.setWidth("100%"); weekTable.setHeight("100%"); weekTable.setColor("#ffffff"); weekTable.setCellpadding(1); weekTable.setCellspacing(0); if(column == 1 && row != 2) { stamp.setTime(j,0,0); weekTable.add(stamp.getTime().toString(),1,1); backTable.add(weekTable,column,row); } else if(row == 2 && column != 1) { if(i==weekday) { weekTable.setColor("#e9e9e9"); } nameOfDay = new Text(cal.getDayName(i, iwc.getCurrentLocale(), IWCalendar.LONG).toString()); if(i < weekday) { if(today == 1) { int lengthOfPreviousMonth = 0; if(stamp.getMonth() == 1) { /* * if January the lengthOfPreviousMonth is the length of Desember the year before */ lengthOfPreviousMonth = cal.getLengthOfMonth(12,stamp.getYear()-1); } else { /* * else lengthOfPreviousMonth is the length of the month before in the current year */ lengthOfPreviousMonth = cal.getLengthOfMonth(stamp.getMonth()-1,stamp.getYear()); } day = (today + lengthOfPreviousMonth) - (weekday - i); } else { day = today - (weekday - i); } stamp.setDay(day); }// end if weekTable.add(nameOfDay,1,1); weekTable.add("-" + stamp.getDateString("dd.MM"),1,1); backTable.add(weekTable,column,row); stamp.addDays(1); }// end else if else { // weekTable.setStyleClass(column,row,borderWhiteTableStyle); Timestamp fromStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S")); fromStamp.setHours(beginHour); fromStamp.setMinutes(0); fromStamp.setNanos(0); Timestamp toStamp =Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S")); toStamp.setHours(endHour); toStamp.setMinutes(0); toStamp.setNanos(0); List listOfEntries = (List) getCalBusiness(iwc).getEntriesBetweenTimestamps(fromStamp,toStamp); User user = null; Integer userID = null; if(iwc.isLoggedOn()) { user = iwc.getCurrentUser(); userID = (Integer) user.getPrimaryKey(); } for(int h=0; h<listOfEntries.size(); h++) { CalendarEntry entry = (CalendarEntry) listOfEntries.get(h); Collection viewGroups = null; CalendarLedger ledger = null; boolean isInGroup = false; int groupIDInLedger = -1; if(user != null) { try { viewGroups = getUserBusiness(iwc).getUserGroups(user); }catch(Exception e) { e.printStackTrace(); } } if(entry.getLedgerID() != -1) { ledger = getCalBusiness(iwc).getLedger(entry.getLedgerID()); if(ledger != null) { groupIDInLedger = ledger.getGroupID(); } } else { groupIDInLedger = 1; } if(viewGroups != null) { Iterator viewGroupsIter = viewGroups.iterator(); //goes through the groups the user may view and prints out the entry if //the group connected to the entry is the same as the group the user may view while(viewGroupsIter.hasNext()) { Group group =(Group) viewGroupsIter.next(); Integer groupID = (Integer) group.getPrimaryKey(); if(entry.getGroupID() == groupID.intValue() || groupIDInLedger == groupID.intValue()) { isInGroup = true; } } } if(groupIDInLedger == getViewGroupID()) { isInGroup = true; } if(isInGroup || iwc.isSuperAdmin() || getViewGroupID() == entry.getGroupID() || userID.intValue() == entry.getUserID()) { Timestamp fStamp = entry.getDate(); Timestamp ttStamp = entry.getEndDate(); if(j <= ttStamp.getHours() && j >= fStamp.getHours()) { String headline = getEntryHeadline(entry); Link headlineLink = new Link(headline); headlineLink.addParameter(ACTION,OPEN); headlineLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear()); headlineLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth()); headlineLink.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay()); headlineLink.addParameter("entryID", entry.getPrimaryKey().toString()); if(!iwc.getAccessController().hasRole("cal_view_entry_creator",iwc)) { headlineLink.setWindowToOpen(EntryInfoWindow.class); } headlineLink.setStyleClass(entryLink); headlineLink.addParameter(CalendarParameters.PARAMETER_VIEW,view); weekTable.add(headlineLink,1,1); weekTable.add("<br>",1,1); // backTable.add(weekTable,column,row); } } } //end for backTable.setHeight(column,row,"40"); backTable.add(weekTable,column,row); } row++; } //end inner for column++; }//end outer for return backTable; } /** * * @return a table displaying the days of the current month */ public Table monthView(IWContext iwc, IWTimestamp stamp) { /* * now holds the current time */ now = IWTimestamp.RightNow(); cal = new IWCalendar(); Text nameOfDay = new Text(); Text t = new Text(); Link right = getRightLink(iwc); Link left = getLeftLink(iwc); addNextMonthPrm(right, timeStamp); addLastMonthPrm(left, timeStamp); int weekdays = 8; int daycount = cal.getLengthOfMonth(stamp.getMonth(),stamp.getYear()); int firstWeekDayOfMonth = cal.getDayOfWeek(stamp.getYear(),stamp.getMonth(),1); // int dayOfMonth = cal.getDay(); int row = 3; int column = firstWeekDayOfMonth; int n = 1; Table backTable = new Table(); backTable.setColor("#cccccc"); backTable.setCellspacing(1); backTable.setCellpadding(0); backTable.setWidth(500); backTable.setHeight(400); String dateString = stamp.getDateString("MMMMMMMM, yyyy",iwc.getCurrentLocale()); backTable.mergeCells(1,1,7,1); Table headTable = new Table(); headTable.setWidth("100%"); headTable.setStyleClass(mainTableStyle); headTable.setVerticalAlignment(1,1,"top"); headTable.add(left,1,1); headTable.add(Text.NON_BREAKING_SPACE,1,1); headTable.add(dateString,1,1); headTable.add(Text.NON_BREAKING_SPACE,1,1); headTable.add(right,1,1); headTable.setAlignment(2,1,"right"); headTable.add(getIconTable(iwc),2,1); backTable.add(headTable,1,1); int weekday = 1; for(int i=1; i<weekdays; i++) { weekday = i % 7; if (weekday == 0) weekday = 7; nameOfDay = new Text(cal.getDayName(weekday, iwc.getCurrentLocale(), IWCalendar.LONG).toString().toLowerCase()); backTable.add(nameOfDay,i,2); backTable.setWidth(i,2,"200"); backTable.setStyleClass(i,2,"main"); } while (n <= daycount) { Table dayCell = new Table(); dayCell.setCellspacing(0); dayCell.setCellpadding(1); dayCell.setWidth("100%"); dayCell.setHeight("100%"); dayCell.setVerticalAlignment(1,1,"top"); t = new Text(String.valueOf(n)); int cellRow = 2; backTable.setWidth(column,row,"200"); backTable.setHeight(column,row,"105"); if(n == now.getDay()) { dayCell.setColor("#e9e9e9"); } else { dayCell.setColor("#ffffff"); } Link dayLink = new Link(t); dayLink.setStyleClass(styledLink); dayLink.addParameter(CalendarParameters.PARAMETER_VIEW,CalendarParameters.DAY); dayLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear()); dayLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth()); dayLink.addParameter(CalendarParameters.PARAMETER_DAY, n); if(groupID != -2) { dayLink.addParameter(PARAMETER_ISI_GROUP_ID,groupID); } dayCell.add(dayLink,1,1); dayCell.setHeight(1,1,"12"); dayCell.add("<br>",1,1); dayCell.setAlignment(1,1,"right"); Timestamp fromStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S")); fromStamp.setDate(n); fromStamp.setHours(0); fromStamp.setMinutes(0); fromStamp.setNanos(0); Timestamp toStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S")); toStamp.setDate(n); toStamp.setHours(23); toStamp.setMinutes(59); toStamp.setNanos(0); List listOfEntries = (List) getCalBusiness(iwc).getEntriesBetweenTimestamps(fromStamp,toStamp); Collections.sort(listOfEntries,new Comparator() { public int compare(Object arg0, Object arg1) { return ((CalendarEntry) arg0).getDate().compareTo(((CalendarEntry) arg1).getDate()); } }); User user = null; Integer userID = null; if(iwc.isLoggedOn()) { user = iwc.getCurrentUser(); userID = (Integer) user.getPrimaryKey(); } else { - userID = new Integer(-1); + userID = new Integer(-2); } for(int h=0; h<listOfEntries.size(); h++) { CalendarEntry entry = (CalendarEntry) listOfEntries.get(h); CalendarLedger ledger = null; int groupIDInLedger = 0; int coachGroupIDInLedger = 0; boolean isInGroup = false; Collection viewGroups = null; if(user != null) { try { viewGroups = getUserBusiness(iwc).getUserGroups(user); }catch(Exception e) { e.printStackTrace(); } } if(entry.getLedgerID() != -1) { ledger = getCalBusiness(iwc).getLedger(entry.getLedgerID()); if(ledger != null) { groupIDInLedger = ledger.getGroupID(); coachGroupIDInLedger = ledger.getCoachGroupID(); } } else { groupIDInLedger = -1; coachGroupIDInLedger = -1; } if(viewGroups != null) { Iterator viewGroupsIter = viewGroups.iterator(); //goes through the groups the user may view and prints out the entry if //the group connected to the entry is the same as the group the user may view while(viewGroupsIter.hasNext()) { Group group =(Group) viewGroupsIter.next(); Integer groupID = (Integer) group.getPrimaryKey(); if(entry.getGroupID() == groupID.intValue() || groupIDInLedger == groupID.intValue()){ isInGroup = true; } } } if(groupIDInLedger == getViewGroupID()) { isInGroup = true; } if(coachGroupIDInLedger == getViewGroupID()) { isInGroup = true; } if(isInGroup || iwc.isSuperAdmin() || getViewGroupID() == entry.getGroupID() || userID.intValue() == entry.getUserID()) { String headline = getEntryHeadline(entry); Link headlineLink = new Link(headline); headlineLink.addParameter(ACTION,OPEN); headlineLink.addParameter(CalendarParameters.PARAMETER_VIEW,view); headlineLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear()); headlineLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth()); headlineLink.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay()); headlineLink.addParameter(CalendarEntryCreator.entryIDParameterName, entry.getPrimaryKey().toString()); if(!iwc.getAccessController().hasRole("cal_view_entry_creator",iwc)) { headlineLink.setWindowToOpen(EntryInfoWindow.class); } headlineLink.setStyleClass(entryLink); //TODO: something - the headlineLink is entryLinkActive even though calentrycreator is empty String e = iwc.getParameter(CalendarEntryCreator.entryIDParameterName); CalendarEntry ent = null; if(e == null || e.equals("")) { e = ""; } else { try { ent = getCalBusiness(iwc).getEntry(Integer.parseInt(e)); }catch(Exception ex) { ent = null; } } if(ent != null) { if(ent.getPrimaryKey().equals(entry.getPrimaryKey())) { headlineLink.setStyleClass(entryLinkActive); } } dayCell.add(headlineLink,1,cellRow); dayCell.setVerticalAlignment(1,cellRow,"top"); dayCell.add("<br>",1,cellRow++); } } backTable.add(dayCell,column,row); backTable.setColor(column,row,"#ffffff"); backTable.add(Text.NON_BREAKING_SPACE,column,row); backTable.setVerticalAlignment(column,row,"top"); column = column % 7 + 1; if (column == 1) row++; n++; } return backTable; } /** * @param entry * @return */ private String getEntryHeadline(CalendarEntry entry) { Timestamp startDate = entry.getDate(); int startHours = startDate.getHours(); int startMinutes = startDate.getMinutes(); Timestamp endDate = entry.getEndDate(); int endHours = endDate.getHours(); int endMinutes = endDate.getMinutes(); String headline = getTimeString(startHours,startMinutes) + "-" + getTimeString(endHours,endMinutes) + " " + entry.getName(); return headline; } /** * * @param hours * @param minutes * @return */ private String getTimeString(int hours, int minutes) { String timeString; String mi; if(minutes<10) { mi = "0"+minutes; } else { mi = ""+minutes; } timeString = hours + ":" + mi; return timeString; } public Table yearView(IWContext iwc, IWTimestamp stamp) { now = new IWTimestamp(); Link right = getRightLink(iwc); Link left = getLeftLink(iwc); addNextYearPrm(right,timeStamp); addLastYearPrm(left,timeStamp); Table yearTable = new Table(); Table headTable = new Table(); headTable.setWidth("100%"); headTable.setHeight("100%"); headTable.setStyleClass(mainTableStyle); headTable.setCellpadding(0); headTable.setCellspacing(0); headTable.setVerticalAlignment(1,1,"top"); headTable.add(left,1,1); headTable.add(Text.NON_BREAKING_SPACE,1,1); headTable.add("" + stamp.getYear(),1,1); headTable.add(Text.NON_BREAKING_SPACE,1,1); headTable.add(right,1,1); headTable.setAlignment(2,1,"right"); headTable.add(getIconTable(iwc),2,1); yearTable.mergeCells(1,1,4,1); yearTable.add(headTable,1,1); IWTimestamp yearStamp = null; SmallCalendar smallCalendar = null; int row = 2; int column = 1; for (int a = 1; a <= 12; a++) { yearStamp = new IWTimestamp(stamp.getDay(), a, stamp.getYear()); smallCalendar = new SmallCalendar(yearStamp); smallCalendar.setDaysAsLink(true); smallCalendar.addParameterToLink(CalendarParameters.PARAMETER_VIEW,CalendarParameters.DAY); yearTable.add(smallCalendar,column, row); yearTable.setStyleClass(column,row,borderWhiteTableStyle); yearTable.setRowVerticalAlignment(row, "top"); yearTable.setAlignment("center"); column = column % 4 + 1; if (column == 1) row++; } return yearTable; } public Table getIconTable(IWContext iwc) { Table iconTable = new Table(); /* * dayView, weekView, monthView and yearView trigger a change of the calendar view */ IWBundle iwb = getBundle(iwc); Image day_on = iwb.getImage("day_on_blue.gif"); Link dayView = new Link(); addLinkParameters(dayView,CalendarParameters.DAY,timeStamp); dayView.setImage(day_on); Image week_on = iwb.getImage("week_on_blue.gif"); Link weekView = new Link(); addLinkParameters(weekView,CalendarParameters.WEEK,timeStamp); weekView.setImage(week_on); Image month_on = iwb.getImage("month_on_blue.gif"); Link monthView = new Link(); addLinkParameters(monthView,CalendarParameters.MONTH,timeStamp); monthView.setImage(month_on); Image year_on = iwb.getImage("year_on_blue.gif"); Link yearView = new Link(); addLinkParameters(yearView,CalendarParameters.YEAR,timeStamp); yearView.setImage(year_on); iconTable.add(dayView,1,1); iconTable.add(weekView,2,1); iconTable.add(monthView,3,1); iconTable.add(yearView,4,1); return iconTable; } public Link getRightLink(IWContext iwc) { IWBundle iwb = getBundle(iwc); Image rightArrow = iwb.getImage("right_arrow.gif"); Link right = new Link(); right.setImage(rightArrow); right.addParameter(CalendarParameters.PARAMETER_VIEW,view); return right; } public Link getLeftLink(IWContext iwc) { IWBundle iwb = getBundle(iwc); Image leftArrow = iwb.getImage("left_arrow.gif"); Link left = new Link(); left.setImage(leftArrow); left.addParameter(CalendarParameters.PARAMETER_VIEW,view); return left; } public void main(IWContext iwc) throws Exception{ IWResourceBundle iwrb = getResourceBundle(iwc); Page parentPage = this.getParentPage(); String styleSrc = iwc.getIWMainApplication().getBundle(getBundleIdentifier()).getResourcesURL(); String styleSheetName = "CalStyle.css"; styleSrc = styleSrc + "/" + styleSheetName; parentPage.addStyleSheetURL(styleSrc); if (timeStamp == null) { String day = iwc.getParameter(CalendarParameters.PARAMETER_DAY); String month = iwc.getParameter(CalendarParameters.PARAMETER_MONTH); String year = iwc.getParameter(CalendarParameters.PARAMETER_YEAR); if(month != null && !month.equals("") && day != null && !day.equals("") && year != null && !year.equals("")) { timeStamp = getTimestamp(day,month,year); } else { timeStamp = IWTimestamp.RightNow(); } } CalendarEntryCreator creator = new CalendarEntryCreator(); String save = iwc.getParameter(creator.saveButtonParameterName); if(save != null) { creator.saveEntry(iwc,parentPage); } /* * view is set to the current view */ String viewString = iwc.getParameter(CalendarParameters.PARAMETER_VIEW); if (viewString != null && !viewString.equals("")) { view = Integer.parseInt(viewString); } action = iwc.getParameter(ACTION); Table table = new Table(); table.setCellspacing(0); table.setCellpadding(0); table.setHeight("100%"); table.mergeCells(1,1,1,2); table.setAlignment(1,2,"center"); table.setWidth(2,1,"8"); table.mergeCells(2,1,2,2); table.setVerticalAlignment("top"); table.setVerticalAlignment(3,1,"top"); table.setVerticalAlignment(3,3,"top"); table.setVerticalAlignment(3,5,"top"); User user = null; if(iwc.isLoggedOn()) { user = iwc.getCurrentUser(); } Table viewTable = new Table(); switch (view) { case CalendarParameters.DAY : viewTable = dayView(iwc, timeStamp); break; case CalendarParameters.WEEK : viewTable = weekView(iwc,timeStamp); break; case CalendarParameters.MONTH : viewTable = monthView(iwc,timeStamp); break; case CalendarParameters.YEAR : viewTable = yearView(iwc,timeStamp); break; } table.setVerticalAlignment(1,1,Table.VERTICAL_ALIGN_TOP); table.add(viewTable,1,1); // table.setBorder(1); if(iwc.getAccessController().hasRole("cal_view_entry_creator",iwc)) { table.setWidth(800); Table headlineTable = new Table(); headlineTable.setCellpadding(0); headlineTable.setCellspacing(0); headlineTable.setStyleClass(borderLeftTopRight); headlineTable.setStyleClass(1,1,menuTableStyle); headlineTable.setWidth(400); Text ledgerText = new Text(iwrb.getLocalizedString("calendarView.ledgers", "Ledgers")); ledgerText.setStyleClass(headline); ledgerText.setBold(); headlineTable.setAlignment(1,1,Table.HORIZONTAL_ALIGN_CENTER); headlineTable.add(ledgerText,1,1); table.setHeight(3,1,200); table.add(headlineTable,3,1); int row = 2; Table ledgerTable = new Table(); ledgerTable.setCellpadding(2); ledgerTable.setCellspacing(0); Text linkText = new Text(iwrb.getLocalizedString("calendarwindow.new_ledger","New Ledger")); Link newLedgerLink = new Link(linkText); newLedgerLink.setWindowToOpen(CreateLedgerWindow.class); newLedgerLink.setAsImageButton(true,true); ledgerTable.setAlignment(1,1,Table.HORIZONTAL_ALIGN_RIGHT); ledgerTable.add(newLedgerLink,1,1); Iterator ledgerIter = getCalBusiness(iwc).getAllLedgers().iterator(); while(ledgerIter.hasNext()) { CalendarLedger ledger = (CalendarLedger) ledgerIter.next(); Link ledgerLink =new Link(ledger.getName()); ledgerLink.setStyleClass(styledLink); ledgerLink.addParameter(LedgerWindow.LEDGER,ledger.getPrimaryKey().toString()); ledgerLink.addParameter(CalendarParameters.PARAMETER_DAY,timeStamp.getDay()); ledgerLink.addParameter(CalendarParameters.PARAMETER_MONTH,timeStamp.getMonth()); ledgerLink.addParameter(CalendarParameters.PARAMETER_YEAR,timeStamp.getYear()); ledgerLink.setWindowToOpen(LedgerWindow.class); if(user != null) { if(((Integer) user.getPrimaryKey()).intValue() == ledger.getCoachID() || user.getPrimaryGroupID() == ledger.getCoachGroupID()) { ledgerTable.add(" - ",1,row); ledgerTable.add(ledgerLink,1,row++); } } } Layer layer = new Layer(Layer.DIV); layer.setStyleClass(ledgerListStyle); layer.add(ledgerTable); table.add(layer,3,1); table.setVerticalAlignment(3,2,Table.VERTICAL_ALIGN_TOP); table.add(Text.BREAK,3,2); table.add(creator,3,2); } else { table.setWidth(500); } add(table); } /** * * @param l * @param viewValue * @param stamp */ public void addLinkParameters(Link l, int viewValue, IWTimestamp stamp) { if(groupID != -2) { l.addParameter("group_id",groupID); } l.addParameter(CalendarParameters.PARAMETER_VIEW, viewValue); l.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear()); l.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth()); l.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay()); l.addParameter(ACTION,action); } /** * * @param hour - the time of day when the CalenderView - day- or weekView, starts */ public void setBeginHour(int hour) { beginHour = hour; } /** * * @param hour - the time of day when the CalendarView - day- or weekView, ends */ public void setEndHour(int hour) { endHour = hour; } public void setViewInGroupID(int id) { groupID = id; } public void setViewInUserID(int id) { userID = id; } public int getViewGroupID() { return groupID; } public int getViewUserID() { return userID; } /** * Adds parameters for the next day to the next day link * @param L * @param idts */ public void addNextDayPrm(Link L, IWTimestamp idts) { if(groupID != -2) { L.addParameter(PARAMETER_ISI_GROUP_ID,groupID); } IWCalendar cal = new IWCalendar(); int lastDayOfMonth = cal.getLengthOfMonth(idts.getMonth(),idts.getYear()); if(idts.getDay() == lastDayOfMonth) { if(idts.getMonth() == 12) { L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() + 1)); L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(1)); } else { L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear())); L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth() + 1)); } L.addParameter(CalendarParameters.PARAMETER_DAY, String.valueOf(1)); } else { L.addParameter(CalendarParameters.PARAMETER_DAY, String.valueOf(idts.getDay() + 1)); L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth())); L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear())); } } /** * * @param L * @param idts */ public void addLastDayPrm(Link L, IWTimestamp idts) { if(groupID != -2) { L.addParameter(PARAMETER_ISI_GROUP_ID,groupID); } IWCalendar cal = new IWCalendar(); int lastDayOfPreviousMonthThisYear = cal.getLengthOfMonth(idts.getMonth() - 1,idts.getYear()); int lastDayOfPreviousMonthLastYear = cal.getLengthOfMonth(idts.getMonth() - 1,idts.getYear() - 1); if(idts.getDay() == 1) { if(idts.getMonth() == 1) { L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() - 1)); L.addParameter(CalendarParameters.PARAMETER_DAY, String.valueOf(lastDayOfPreviousMonthLastYear)); L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(12)); } else { L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear())); L.addParameter(CalendarParameters.PARAMETER_DAY, String.valueOf(lastDayOfPreviousMonthThisYear)); L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth() - 1)); } } else { L.addParameter(CalendarParameters.PARAMETER_DAY, String.valueOf(idts.getDay() - 1)); L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth())); L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear())); } } public void addNextWeekPrm(Link L, IWTimestamp idts) { GregorianCalendar calendar = new GregorianCalendar(idts.getYear(),idts.getMonth(),idts.getDay()); Timestamp ts = idts.getTimestamp(); calendar.add(calendar.DAY_OF_MONTH,6); if(calendar.get(calendar.DAY_OF_MONTH) < idts.getDay()) { calendar.add(calendar.MONTH,1); if(calendar.get(calendar.MONTH) < idts.getMonth()) { calendar.add(calendar.YEAR,1); } } Date sd = calendar.getTime(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.S"); String f = format.format(sd); ts = Timestamp.valueOf(f); // int year = sd.getYear() + 1900; // ts.setYear(year); idts = new IWTimestamp(ts); L.addParameter(CalendarParameters.PARAMETER_DAY,String.valueOf(idts.getDay())); L.addParameter(CalendarParameters.PARAMETER_MONTH,String.valueOf(idts.getMonth())); L.addParameter(CalendarParameters.PARAMETER_YEAR,String.valueOf(idts.getYear())); } public void addLastWeekPrm(Link L, IWTimestamp idts) { } /** * The same method as in SmallCalendar.java * @param L * @param idts */ public void addNextMonthPrm(Link L, IWTimestamp idts) { if(groupID != -2) { L.addParameter(PARAMETER_ISI_GROUP_ID,groupID); } if (idts.getMonth() == 12) { L.addParameter(CalendarParameters.PARAMETER_DAY, idts.getDay()); L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(1)); L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() + 1)); } else { L.addParameter(CalendarParameters.PARAMETER_DAY, idts.getDay()); L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth() + 1)); L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear())); } } /** * The same method as in SmallCalendar.java * @param L * @param idts */ public void addLastMonthPrm(Link L, IWTimestamp idts) { if(groupID != -2) { L.addParameter(PARAMETER_ISI_GROUP_ID,groupID); } if (idts.getMonth() == 1) { L.addParameter(CalendarParameters.PARAMETER_DAY,idts.getDay()); L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(12)); L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() - 1)); } else { L.addParameter(CalendarParameters.PARAMETER_DAY,idts.getDay()); L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth() - 1)); L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear())); } } public void addNextYearPrm(Link L, IWTimestamp idts) { L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth())); L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() + 1)); } public void addLastYearPrm(Link L, IWTimestamp idts) { L.addParameter(CalendarParameters.PARAMETER_MONTH, String.valueOf(idts.getMonth())); L.addParameter(CalendarParameters.PARAMETER_YEAR, String.valueOf(idts.getYear() - 1)); } public static IWTimestamp getTimestamp(String day, String month, String year) { IWTimestamp stamp = new IWTimestamp(); if (day != null) { stamp.setDay(Integer.parseInt(day)); } // removed dubius behavior A /*else { stamp.setDay(1); } */ if (month != null) { stamp.setMonth(Integer.parseInt(month)); } if (year != null) { stamp.setYear(Integer.parseInt(year)); } stamp.setHour(0); stamp.setMinute(0); stamp.setSecond(0); return stamp; } public String getBundleIdentifier() { return IW_BUNDLE_IDENTIFIER; } public CalBusiness getCalBusiness(IWApplicationContext iwc) { if (calBiz == null) { try { calBiz = (CalBusiness) com.idega.business.IBOLookup.getServiceInstance(iwc, CalBusiness.class); } catch (java.rmi.RemoteException rme) { throw new RuntimeException(rme.getMessage()); } } return calBiz; } protected UserBusiness getUserBusiness(IWApplicationContext iwc) { UserBusiness userBusiness = null; if (userBusiness == null) { try { userBusiness = (UserBusiness) com.idega.business.IBOLookup.getServiceInstance(iwc, UserBusiness.class); } catch (java.rmi.RemoteException rme) { throw new RuntimeException(rme.getMessage()); } } return userBusiness; } }
true
true
public Table monthView(IWContext iwc, IWTimestamp stamp) { /* * now holds the current time */ now = IWTimestamp.RightNow(); cal = new IWCalendar(); Text nameOfDay = new Text(); Text t = new Text(); Link right = getRightLink(iwc); Link left = getLeftLink(iwc); addNextMonthPrm(right, timeStamp); addLastMonthPrm(left, timeStamp); int weekdays = 8; int daycount = cal.getLengthOfMonth(stamp.getMonth(),stamp.getYear()); int firstWeekDayOfMonth = cal.getDayOfWeek(stamp.getYear(),stamp.getMonth(),1); // int dayOfMonth = cal.getDay(); int row = 3; int column = firstWeekDayOfMonth; int n = 1; Table backTable = new Table(); backTable.setColor("#cccccc"); backTable.setCellspacing(1); backTable.setCellpadding(0); backTable.setWidth(500); backTable.setHeight(400); String dateString = stamp.getDateString("MMMMMMMM, yyyy",iwc.getCurrentLocale()); backTable.mergeCells(1,1,7,1); Table headTable = new Table(); headTable.setWidth("100%"); headTable.setStyleClass(mainTableStyle); headTable.setVerticalAlignment(1,1,"top"); headTable.add(left,1,1); headTable.add(Text.NON_BREAKING_SPACE,1,1); headTable.add(dateString,1,1); headTable.add(Text.NON_BREAKING_SPACE,1,1); headTable.add(right,1,1); headTable.setAlignment(2,1,"right"); headTable.add(getIconTable(iwc),2,1); backTable.add(headTable,1,1); int weekday = 1; for(int i=1; i<weekdays; i++) { weekday = i % 7; if (weekday == 0) weekday = 7; nameOfDay = new Text(cal.getDayName(weekday, iwc.getCurrentLocale(), IWCalendar.LONG).toString().toLowerCase()); backTable.add(nameOfDay,i,2); backTable.setWidth(i,2,"200"); backTable.setStyleClass(i,2,"main"); } while (n <= daycount) { Table dayCell = new Table(); dayCell.setCellspacing(0); dayCell.setCellpadding(1); dayCell.setWidth("100%"); dayCell.setHeight("100%"); dayCell.setVerticalAlignment(1,1,"top"); t = new Text(String.valueOf(n)); int cellRow = 2; backTable.setWidth(column,row,"200"); backTable.setHeight(column,row,"105"); if(n == now.getDay()) { dayCell.setColor("#e9e9e9"); } else { dayCell.setColor("#ffffff"); } Link dayLink = new Link(t); dayLink.setStyleClass(styledLink); dayLink.addParameter(CalendarParameters.PARAMETER_VIEW,CalendarParameters.DAY); dayLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear()); dayLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth()); dayLink.addParameter(CalendarParameters.PARAMETER_DAY, n); if(groupID != -2) { dayLink.addParameter(PARAMETER_ISI_GROUP_ID,groupID); } dayCell.add(dayLink,1,1); dayCell.setHeight(1,1,"12"); dayCell.add("<br>",1,1); dayCell.setAlignment(1,1,"right"); Timestamp fromStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S")); fromStamp.setDate(n); fromStamp.setHours(0); fromStamp.setMinutes(0); fromStamp.setNanos(0); Timestamp toStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S")); toStamp.setDate(n); toStamp.setHours(23); toStamp.setMinutes(59); toStamp.setNanos(0); List listOfEntries = (List) getCalBusiness(iwc).getEntriesBetweenTimestamps(fromStamp,toStamp); Collections.sort(listOfEntries,new Comparator() { public int compare(Object arg0, Object arg1) { return ((CalendarEntry) arg0).getDate().compareTo(((CalendarEntry) arg1).getDate()); } }); User user = null; Integer userID = null; if(iwc.isLoggedOn()) { user = iwc.getCurrentUser(); userID = (Integer) user.getPrimaryKey(); } else { userID = new Integer(-1); } for(int h=0; h<listOfEntries.size(); h++) { CalendarEntry entry = (CalendarEntry) listOfEntries.get(h); CalendarLedger ledger = null; int groupIDInLedger = 0; int coachGroupIDInLedger = 0; boolean isInGroup = false; Collection viewGroups = null; if(user != null) { try { viewGroups = getUserBusiness(iwc).getUserGroups(user); }catch(Exception e) { e.printStackTrace(); } } if(entry.getLedgerID() != -1) { ledger = getCalBusiness(iwc).getLedger(entry.getLedgerID()); if(ledger != null) { groupIDInLedger = ledger.getGroupID(); coachGroupIDInLedger = ledger.getCoachGroupID(); } } else { groupIDInLedger = -1; coachGroupIDInLedger = -1; } if(viewGroups != null) { Iterator viewGroupsIter = viewGroups.iterator(); //goes through the groups the user may view and prints out the entry if //the group connected to the entry is the same as the group the user may view while(viewGroupsIter.hasNext()) { Group group =(Group) viewGroupsIter.next(); Integer groupID = (Integer) group.getPrimaryKey(); if(entry.getGroupID() == groupID.intValue() || groupIDInLedger == groupID.intValue()){ isInGroup = true; } } } if(groupIDInLedger == getViewGroupID()) { isInGroup = true; } if(coachGroupIDInLedger == getViewGroupID()) { isInGroup = true; } if(isInGroup || iwc.isSuperAdmin() || getViewGroupID() == entry.getGroupID() || userID.intValue() == entry.getUserID()) { String headline = getEntryHeadline(entry); Link headlineLink = new Link(headline); headlineLink.addParameter(ACTION,OPEN); headlineLink.addParameter(CalendarParameters.PARAMETER_VIEW,view); headlineLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear()); headlineLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth()); headlineLink.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay()); headlineLink.addParameter(CalendarEntryCreator.entryIDParameterName, entry.getPrimaryKey().toString()); if(!iwc.getAccessController().hasRole("cal_view_entry_creator",iwc)) { headlineLink.setWindowToOpen(EntryInfoWindow.class); } headlineLink.setStyleClass(entryLink); //TODO: something - the headlineLink is entryLinkActive even though calentrycreator is empty String e = iwc.getParameter(CalendarEntryCreator.entryIDParameterName); CalendarEntry ent = null; if(e == null || e.equals("")) { e = ""; } else { try { ent = getCalBusiness(iwc).getEntry(Integer.parseInt(e)); }catch(Exception ex) { ent = null; } } if(ent != null) { if(ent.getPrimaryKey().equals(entry.getPrimaryKey())) { headlineLink.setStyleClass(entryLinkActive); } } dayCell.add(headlineLink,1,cellRow); dayCell.setVerticalAlignment(1,cellRow,"top"); dayCell.add("<br>",1,cellRow++); } } backTable.add(dayCell,column,row); backTable.setColor(column,row,"#ffffff"); backTable.add(Text.NON_BREAKING_SPACE,column,row); backTable.setVerticalAlignment(column,row,"top"); column = column % 7 + 1; if (column == 1) row++; n++; } return backTable; }
public Table monthView(IWContext iwc, IWTimestamp stamp) { /* * now holds the current time */ now = IWTimestamp.RightNow(); cal = new IWCalendar(); Text nameOfDay = new Text(); Text t = new Text(); Link right = getRightLink(iwc); Link left = getLeftLink(iwc); addNextMonthPrm(right, timeStamp); addLastMonthPrm(left, timeStamp); int weekdays = 8; int daycount = cal.getLengthOfMonth(stamp.getMonth(),stamp.getYear()); int firstWeekDayOfMonth = cal.getDayOfWeek(stamp.getYear(),stamp.getMonth(),1); // int dayOfMonth = cal.getDay(); int row = 3; int column = firstWeekDayOfMonth; int n = 1; Table backTable = new Table(); backTable.setColor("#cccccc"); backTable.setCellspacing(1); backTable.setCellpadding(0); backTable.setWidth(500); backTable.setHeight(400); String dateString = stamp.getDateString("MMMMMMMM, yyyy",iwc.getCurrentLocale()); backTable.mergeCells(1,1,7,1); Table headTable = new Table(); headTable.setWidth("100%"); headTable.setStyleClass(mainTableStyle); headTable.setVerticalAlignment(1,1,"top"); headTable.add(left,1,1); headTable.add(Text.NON_BREAKING_SPACE,1,1); headTable.add(dateString,1,1); headTable.add(Text.NON_BREAKING_SPACE,1,1); headTable.add(right,1,1); headTable.setAlignment(2,1,"right"); headTable.add(getIconTable(iwc),2,1); backTable.add(headTable,1,1); int weekday = 1; for(int i=1; i<weekdays; i++) { weekday = i % 7; if (weekday == 0) weekday = 7; nameOfDay = new Text(cal.getDayName(weekday, iwc.getCurrentLocale(), IWCalendar.LONG).toString().toLowerCase()); backTable.add(nameOfDay,i,2); backTable.setWidth(i,2,"200"); backTable.setStyleClass(i,2,"main"); } while (n <= daycount) { Table dayCell = new Table(); dayCell.setCellspacing(0); dayCell.setCellpadding(1); dayCell.setWidth("100%"); dayCell.setHeight("100%"); dayCell.setVerticalAlignment(1,1,"top"); t = new Text(String.valueOf(n)); int cellRow = 2; backTable.setWidth(column,row,"200"); backTable.setHeight(column,row,"105"); if(n == now.getDay()) { dayCell.setColor("#e9e9e9"); } else { dayCell.setColor("#ffffff"); } Link dayLink = new Link(t); dayLink.setStyleClass(styledLink); dayLink.addParameter(CalendarParameters.PARAMETER_VIEW,CalendarParameters.DAY); dayLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear()); dayLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth()); dayLink.addParameter(CalendarParameters.PARAMETER_DAY, n); if(groupID != -2) { dayLink.addParameter(PARAMETER_ISI_GROUP_ID,groupID); } dayCell.add(dayLink,1,1); dayCell.setHeight(1,1,"12"); dayCell.add("<br>",1,1); dayCell.setAlignment(1,1,"right"); Timestamp fromStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S")); fromStamp.setDate(n); fromStamp.setHours(0); fromStamp.setMinutes(0); fromStamp.setNanos(0); Timestamp toStamp = Timestamp.valueOf(stamp.getDateString("yyyy-MM-dd hh:mm:ss.S")); toStamp.setDate(n); toStamp.setHours(23); toStamp.setMinutes(59); toStamp.setNanos(0); List listOfEntries = (List) getCalBusiness(iwc).getEntriesBetweenTimestamps(fromStamp,toStamp); Collections.sort(listOfEntries,new Comparator() { public int compare(Object arg0, Object arg1) { return ((CalendarEntry) arg0).getDate().compareTo(((CalendarEntry) arg1).getDate()); } }); User user = null; Integer userID = null; if(iwc.isLoggedOn()) { user = iwc.getCurrentUser(); userID = (Integer) user.getPrimaryKey(); } else { userID = new Integer(-2); } for(int h=0; h<listOfEntries.size(); h++) { CalendarEntry entry = (CalendarEntry) listOfEntries.get(h); CalendarLedger ledger = null; int groupIDInLedger = 0; int coachGroupIDInLedger = 0; boolean isInGroup = false; Collection viewGroups = null; if(user != null) { try { viewGroups = getUserBusiness(iwc).getUserGroups(user); }catch(Exception e) { e.printStackTrace(); } } if(entry.getLedgerID() != -1) { ledger = getCalBusiness(iwc).getLedger(entry.getLedgerID()); if(ledger != null) { groupIDInLedger = ledger.getGroupID(); coachGroupIDInLedger = ledger.getCoachGroupID(); } } else { groupIDInLedger = -1; coachGroupIDInLedger = -1; } if(viewGroups != null) { Iterator viewGroupsIter = viewGroups.iterator(); //goes through the groups the user may view and prints out the entry if //the group connected to the entry is the same as the group the user may view while(viewGroupsIter.hasNext()) { Group group =(Group) viewGroupsIter.next(); Integer groupID = (Integer) group.getPrimaryKey(); if(entry.getGroupID() == groupID.intValue() || groupIDInLedger == groupID.intValue()){ isInGroup = true; } } } if(groupIDInLedger == getViewGroupID()) { isInGroup = true; } if(coachGroupIDInLedger == getViewGroupID()) { isInGroup = true; } if(isInGroup || iwc.isSuperAdmin() || getViewGroupID() == entry.getGroupID() || userID.intValue() == entry.getUserID()) { String headline = getEntryHeadline(entry); Link headlineLink = new Link(headline); headlineLink.addParameter(ACTION,OPEN); headlineLink.addParameter(CalendarParameters.PARAMETER_VIEW,view); headlineLink.addParameter(CalendarParameters.PARAMETER_YEAR, stamp.getYear()); headlineLink.addParameter(CalendarParameters.PARAMETER_MONTH, stamp.getMonth()); headlineLink.addParameter(CalendarParameters.PARAMETER_DAY, stamp.getDay()); headlineLink.addParameter(CalendarEntryCreator.entryIDParameterName, entry.getPrimaryKey().toString()); if(!iwc.getAccessController().hasRole("cal_view_entry_creator",iwc)) { headlineLink.setWindowToOpen(EntryInfoWindow.class); } headlineLink.setStyleClass(entryLink); //TODO: something - the headlineLink is entryLinkActive even though calentrycreator is empty String e = iwc.getParameter(CalendarEntryCreator.entryIDParameterName); CalendarEntry ent = null; if(e == null || e.equals("")) { e = ""; } else { try { ent = getCalBusiness(iwc).getEntry(Integer.parseInt(e)); }catch(Exception ex) { ent = null; } } if(ent != null) { if(ent.getPrimaryKey().equals(entry.getPrimaryKey())) { headlineLink.setStyleClass(entryLinkActive); } } dayCell.add(headlineLink,1,cellRow); dayCell.setVerticalAlignment(1,cellRow,"top"); dayCell.add("<br>",1,cellRow++); } } backTable.add(dayCell,column,row); backTable.setColor(column,row,"#ffffff"); backTable.add(Text.NON_BREAKING_SPACE,column,row); backTable.setVerticalAlignment(column,row,"top"); column = column % 7 + 1; if (column == 1) row++; n++; } return backTable; }
diff --git a/source/de/tuclausthal/submissioninterface/servlets/view/EditMultipleGroupsFormView.java b/source/de/tuclausthal/submissioninterface/servlets/view/EditMultipleGroupsFormView.java index ccdd80d..517b2ac 100644 --- a/source/de/tuclausthal/submissioninterface/servlets/view/EditMultipleGroupsFormView.java +++ b/source/de/tuclausthal/submissioninterface/servlets/view/EditMultipleGroupsFormView.java @@ -1,83 +1,83 @@ /* * Copyright 2011 Sven Strickroth <[email protected]> * * This file is part of the SubmissionInterface. * * SubmissionInterface is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * SubmissionInterface is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SubmissionInterface. If not, see <http://www.gnu.org/licenses/>. */ package de.tuclausthal.submissioninterface.servlets.view; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import de.tuclausthal.submissioninterface.persistence.datamodel.Group; import de.tuclausthal.submissioninterface.persistence.datamodel.Lecture; import de.tuclausthal.submissioninterface.template.Template; import de.tuclausthal.submissioninterface.template.TemplateFactory; import de.tuclausthal.submissioninterface.util.Util; /** * View-Servlet for displaying a form for editing a group * @author Sven Strickroth */ public class EditMultipleGroupsFormView extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Template template = TemplateFactory.getTemplate(request, response); PrintWriter out = response.getWriter(); Lecture lecture = (Lecture) request.getAttribute("lecture"); template.addKeepAlive(); template.printTemplateHeader("Mehrere Gruppen bearbeiten", lecture); - out.println("<form action=\"" + response.encodeURL("?") + "\" method=post>"); + out.println("<form action=\"" + response.encodeURL("?lecture=" + lecture.getId()) + "\" method=post>"); out.println("<table class=border>"); out.println("<tr>"); out.println("<th>Studenten k�nnen sich eintragen:</th>"); out.println("<td><input type=checkbox name=allowStudentsToSignup></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Studenten k�nnen wechseln:</th>"); out.println("<td><input type=checkbox name=allowStudentsToQuit></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Max. Studenten:</th>"); out.println("<td><input type=text name=maxStudents> (leer: keine Speicherung)</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Abgabegruppe:</th>"); out.println("<td><input type=checkbox name=submissionGroup></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Setzen f�r:</th>"); out.println("<td><select multiple size=15 name=gids>"); for (Group group : lecture.getGroups()) { out.println("<option value=" + group.getGid() + ">" + Util.escapeHTML(group.getName()) + "</option>"); } out.println("</select></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td colspan=2 class=mid><input type=submit value=speichern> <a href=\"" + response.encodeURL("ShowLecture?lecture=" + lecture.getId()) + "\">Abbrechen</a></td>"); out.println("</tr>"); out.println("</table>"); out.println("</form>"); template.printTemplateFooter(); } }
true
true
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Template template = TemplateFactory.getTemplate(request, response); PrintWriter out = response.getWriter(); Lecture lecture = (Lecture) request.getAttribute("lecture"); template.addKeepAlive(); template.printTemplateHeader("Mehrere Gruppen bearbeiten", lecture); out.println("<form action=\"" + response.encodeURL("?") + "\" method=post>"); out.println("<table class=border>"); out.println("<tr>"); out.println("<th>Studenten k�nnen sich eintragen:</th>"); out.println("<td><input type=checkbox name=allowStudentsToSignup></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Studenten k�nnen wechseln:</th>"); out.println("<td><input type=checkbox name=allowStudentsToQuit></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Max. Studenten:</th>"); out.println("<td><input type=text name=maxStudents> (leer: keine Speicherung)</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Abgabegruppe:</th>"); out.println("<td><input type=checkbox name=submissionGroup></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Setzen f�r:</th>"); out.println("<td><select multiple size=15 name=gids>"); for (Group group : lecture.getGroups()) { out.println("<option value=" + group.getGid() + ">" + Util.escapeHTML(group.getName()) + "</option>"); } out.println("</select></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td colspan=2 class=mid><input type=submit value=speichern> <a href=\"" + response.encodeURL("ShowLecture?lecture=" + lecture.getId()) + "\">Abbrechen</a></td>"); out.println("</tr>"); out.println("</table>"); out.println("</form>"); template.printTemplateFooter(); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Template template = TemplateFactory.getTemplate(request, response); PrintWriter out = response.getWriter(); Lecture lecture = (Lecture) request.getAttribute("lecture"); template.addKeepAlive(); template.printTemplateHeader("Mehrere Gruppen bearbeiten", lecture); out.println("<form action=\"" + response.encodeURL("?lecture=" + lecture.getId()) + "\" method=post>"); out.println("<table class=border>"); out.println("<tr>"); out.println("<th>Studenten k�nnen sich eintragen:</th>"); out.println("<td><input type=checkbox name=allowStudentsToSignup></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Studenten k�nnen wechseln:</th>"); out.println("<td><input type=checkbox name=allowStudentsToQuit></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Max. Studenten:</th>"); out.println("<td><input type=text name=maxStudents> (leer: keine Speicherung)</td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Abgabegruppe:</th>"); out.println("<td><input type=checkbox name=submissionGroup></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<th>Setzen f�r:</th>"); out.println("<td><select multiple size=15 name=gids>"); for (Group group : lecture.getGroups()) { out.println("<option value=" + group.getGid() + ">" + Util.escapeHTML(group.getName()) + "</option>"); } out.println("</select></td>"); out.println("</tr>"); out.println("<tr>"); out.println("<td colspan=2 class=mid><input type=submit value=speichern> <a href=\"" + response.encodeURL("ShowLecture?lecture=" + lecture.getId()) + "\">Abbrechen</a></td>"); out.println("</tr>"); out.println("</table>"); out.println("</form>"); template.printTemplateFooter(); }
diff --git a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java index 718e40fea..d371b6081 100644 --- a/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java +++ b/core/plugins/org.eclipse.dltk.core/search/org/eclipse/dltk/internal/core/mixin/MixinBuilder.java @@ -1,257 +1,257 @@ /******************************************************************************* * Copyright (c) 2005, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * *******************************************************************************/ package org.eclipse.dltk.internal.core.mixin; import java.io.IOException; import java.text.MessageFormat; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.dltk.core.DLTKCore; import org.eclipse.dltk.core.DLTKLanguageManager; import org.eclipse.dltk.core.IDLTKLanguageToolkit; import org.eclipse.dltk.core.IModelElement; import org.eclipse.dltk.core.IProjectFragment; import org.eclipse.dltk.core.IScriptProject; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.core.ModelException; import org.eclipse.dltk.core.builder.IScriptBuilder; import org.eclipse.dltk.core.mixin.IMixinParser; import org.eclipse.dltk.core.search.SearchEngine; import org.eclipse.dltk.core.search.SearchParticipant; import org.eclipse.dltk.core.search.index.Index; import org.eclipse.dltk.core.search.indexing.IndexManager; import org.eclipse.dltk.core.search.indexing.InternalSearchDocument; import org.eclipse.dltk.core.search.indexing.ReadWriteMonitor; import org.eclipse.dltk.internal.core.BuiltinProjectFragment; import org.eclipse.dltk.internal.core.BuiltinSourceModule; import org.eclipse.dltk.internal.core.ExternalProjectFragment; import org.eclipse.dltk.internal.core.ExternalSourceModule; import org.eclipse.dltk.internal.core.ModelManager; import org.eclipse.dltk.internal.core.SourceModule; import org.eclipse.dltk.internal.core.search.DLTKSearchDocument; public class MixinBuilder implements IScriptBuilder { public IStatus buildResources(IScriptProject project, List resources, IProgressMonitor monitor, int status) { return null; } public IStatus buildModelElements(IScriptProject project, List elements, IProgressMonitor monitor, int status) { return this.buildModelElements(project, elements, monitor, true); } public IStatus buildModelElements(IScriptProject project, List elements, final IProgressMonitor monitor, boolean saveIndex) { if (elements.size() == 0) { return null; } IndexManager manager = ModelManager.getModelManager().getIndexManager(); final int elementsSize = elements.size(); IDLTKLanguageToolkit toolkit = null; IMixinParser parser = null; try { toolkit = DLTKLanguageManager.getLanguageToolkit(project); if (toolkit != null) { parser = MixinManager.getMixinParser(toolkit.getNatureId()); } } catch (CoreException e1) { if (DLTKCore.DEBUG) { e1.printStackTrace(); } } if (parser == null || toolkit == null) { return null; } Map indexes = new HashMap(); // Map imons = new HashMap(); Index mixinIndex = null; ReadWriteMonitor imon = null; try { // waitUntilIndexReady(toolkit); IPath fullPath = project.getProject().getFullPath(); String fullContainerPath = ((fullPath.getDevice() == null) ? fullPath.toString() : fullPath.toOSString()); mixinIndex = manager.getSpecialIndex("mixin", //$NON-NLS-1$ /* project.getProject() */fullPath.toString(), fullContainerPath); imon = mixinIndex.monitor; imon.enterWrite(); String name = MessageFormat.format( Messages.MixinBuilder_buildingRuntimeModelFor, new Object[] { project.getElementName() }); if (monitor != null) { monitor.beginTask(name, elementsSize); } int fileIndex = 0; for (Iterator iterator = elements.iterator(); iterator.hasNext();) { ISourceModule element = (ISourceModule) iterator.next(); Index currentIndex = mixinIndex; if (monitor != null) { if (monitor.isCanceled()) { return null; } } String taskTitle = MessageFormat.format( Messages.MixinBuilder_buildingRuntimeModelFor2, new Object[] { project.getElementName(), new Integer(elements.size() - fileIndex), element.getElementName() }); ++fileIndex; if (monitor != null) { monitor.subTask(taskTitle); } // monitor.beginTask(taskTitle, 1); IProjectFragment projectFragment = (IProjectFragment) element .getAncestor(IModelElement.PROJECT_FRAGMENT); IPath containerPath = project.getPath(); if (projectFragment instanceof ExternalProjectFragment || projectFragment instanceof BuiltinProjectFragment) { IPath path = projectFragment.getPath(); if (indexes.containsKey(path)) { currentIndex = (Index) indexes.get(path); containerPath = path; } else { String contPath = ((path.getDevice() == null) ? path.toString() : path.toOSString()); Index index = manager.getSpecialIndex("mixin", //$NON-NLS-1$ path.toString(), contPath); if (index != null) { currentIndex = index; if (!indexes.values().contains(index)) { index.monitor.enterWrite(); indexes.put(path, index); } containerPath = path; } } } SearchParticipant participant = SearchEngine .getDefaultSearchParticipant(); char[] content; try { content = element.getSourceAsCharArray(); } catch (ModelException e) { content = new char[0]; } DLTKSearchDocument document = new DLTKSearchDocument(element.getPath() .toString(), containerPath, content , participant, element instanceof ExternalSourceModule); // System.out.println("mixin indexing:" + document.getPath()); ((InternalSearchDocument) document).toolkit = toolkit; String containerRelativePath = null; if (element instanceof ExternalSourceModule) { containerRelativePath = (element.getPath() .removeFirstSegments(containerPath.segmentCount()) .setDevice(null).toString()); } else if (element instanceof SourceModule) { containerRelativePath = (element.getPath() - .removeFirstSegments(1).toOSString()); + .removeFirstSegments(1).toPortableString()); } else if (element instanceof BuiltinSourceModule) { containerRelativePath = document.getPath(); // (element.getPath() // .removeFirstSegments().toOSString()); } ((InternalSearchDocument) document) .setContainerRelativePath(containerRelativePath); currentIndex.remove(containerRelativePath); ((InternalSearchDocument) document).setIndex(currentIndex); new MixinIndexer(document, element, currentIndex) .indexDocument(); if (monitor != null) { monitor.worked(1); } } } finally { final Set saveIndexesSet = new HashSet(); if (mixinIndex != null) { if (saveIndex) { saveIndexesSet.add(mixinIndex); } else { imon.exitWrite(); } } Iterator iterator = indexes.values().iterator(); while (iterator.hasNext()) { Index index = (Index) iterator.next(); if (saveIndex) { saveIndexesSet.add(index); } else { index.monitor.exitWrite(); } } if (saveIndex) { for (Iterator ind = saveIndexesSet.iterator(); ind.hasNext();) { Index index = (Index) ind.next(); if (monitor != null) { String containerPath = index.containerPath; if (containerPath.startsWith("#special#")) { //$NON-NLS-1$ containerPath = containerPath.substring( containerPath.lastIndexOf("#"), //$NON-NLS-1$ containerPath.length()); } monitor.subTask(MessageFormat.format( Messages.MixinBuilder_savingIndexFor, new Object[] { containerPath })); } try { index.save(); } catch (IOException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } finally { index.monitor.exitWrite(); } } } if (monitor != null) { monitor.done(); } } return null; } private static MixinBuilder builder = new MixinBuilder(); public static MixinBuilder getDefault() { return builder; } public int estimateElementsToBuild(List elements) { return elements.size(); } public Set getDependencies(IScriptProject project, Set resources, Set allResources, Set oldExternalFolders, Set externalFolders) { return null; } }
true
true
public IStatus buildModelElements(IScriptProject project, List elements, final IProgressMonitor monitor, boolean saveIndex) { if (elements.size() == 0) { return null; } IndexManager manager = ModelManager.getModelManager().getIndexManager(); final int elementsSize = elements.size(); IDLTKLanguageToolkit toolkit = null; IMixinParser parser = null; try { toolkit = DLTKLanguageManager.getLanguageToolkit(project); if (toolkit != null) { parser = MixinManager.getMixinParser(toolkit.getNatureId()); } } catch (CoreException e1) { if (DLTKCore.DEBUG) { e1.printStackTrace(); } } if (parser == null || toolkit == null) { return null; } Map indexes = new HashMap(); // Map imons = new HashMap(); Index mixinIndex = null; ReadWriteMonitor imon = null; try { // waitUntilIndexReady(toolkit); IPath fullPath = project.getProject().getFullPath(); String fullContainerPath = ((fullPath.getDevice() == null) ? fullPath.toString() : fullPath.toOSString()); mixinIndex = manager.getSpecialIndex("mixin", //$NON-NLS-1$ /* project.getProject() */fullPath.toString(), fullContainerPath); imon = mixinIndex.monitor; imon.enterWrite(); String name = MessageFormat.format( Messages.MixinBuilder_buildingRuntimeModelFor, new Object[] { project.getElementName() }); if (monitor != null) { monitor.beginTask(name, elementsSize); } int fileIndex = 0; for (Iterator iterator = elements.iterator(); iterator.hasNext();) { ISourceModule element = (ISourceModule) iterator.next(); Index currentIndex = mixinIndex; if (monitor != null) { if (monitor.isCanceled()) { return null; } } String taskTitle = MessageFormat.format( Messages.MixinBuilder_buildingRuntimeModelFor2, new Object[] { project.getElementName(), new Integer(elements.size() - fileIndex), element.getElementName() }); ++fileIndex; if (monitor != null) { monitor.subTask(taskTitle); } // monitor.beginTask(taskTitle, 1); IProjectFragment projectFragment = (IProjectFragment) element .getAncestor(IModelElement.PROJECT_FRAGMENT); IPath containerPath = project.getPath(); if (projectFragment instanceof ExternalProjectFragment || projectFragment instanceof BuiltinProjectFragment) { IPath path = projectFragment.getPath(); if (indexes.containsKey(path)) { currentIndex = (Index) indexes.get(path); containerPath = path; } else { String contPath = ((path.getDevice() == null) ? path.toString() : path.toOSString()); Index index = manager.getSpecialIndex("mixin", //$NON-NLS-1$ path.toString(), contPath); if (index != null) { currentIndex = index; if (!indexes.values().contains(index)) { index.monitor.enterWrite(); indexes.put(path, index); } containerPath = path; } } } SearchParticipant participant = SearchEngine .getDefaultSearchParticipant(); char[] content; try { content = element.getSourceAsCharArray(); } catch (ModelException e) { content = new char[0]; } DLTKSearchDocument document = new DLTKSearchDocument(element.getPath() .toString(), containerPath, content , participant, element instanceof ExternalSourceModule); // System.out.println("mixin indexing:" + document.getPath()); ((InternalSearchDocument) document).toolkit = toolkit; String containerRelativePath = null; if (element instanceof ExternalSourceModule) { containerRelativePath = (element.getPath() .removeFirstSegments(containerPath.segmentCount()) .setDevice(null).toString()); } else if (element instanceof SourceModule) { containerRelativePath = (element.getPath() .removeFirstSegments(1).toOSString()); } else if (element instanceof BuiltinSourceModule) { containerRelativePath = document.getPath(); // (element.getPath() // .removeFirstSegments().toOSString()); } ((InternalSearchDocument) document) .setContainerRelativePath(containerRelativePath); currentIndex.remove(containerRelativePath); ((InternalSearchDocument) document).setIndex(currentIndex); new MixinIndexer(document, element, currentIndex) .indexDocument(); if (monitor != null) { monitor.worked(1); } } } finally { final Set saveIndexesSet = new HashSet(); if (mixinIndex != null) { if (saveIndex) { saveIndexesSet.add(mixinIndex); } else { imon.exitWrite(); } } Iterator iterator = indexes.values().iterator(); while (iterator.hasNext()) { Index index = (Index) iterator.next(); if (saveIndex) { saveIndexesSet.add(index); } else { index.monitor.exitWrite(); } } if (saveIndex) { for (Iterator ind = saveIndexesSet.iterator(); ind.hasNext();) { Index index = (Index) ind.next(); if (monitor != null) { String containerPath = index.containerPath; if (containerPath.startsWith("#special#")) { //$NON-NLS-1$ containerPath = containerPath.substring( containerPath.lastIndexOf("#"), //$NON-NLS-1$ containerPath.length()); } monitor.subTask(MessageFormat.format( Messages.MixinBuilder_savingIndexFor, new Object[] { containerPath })); } try { index.save(); } catch (IOException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } finally { index.monitor.exitWrite(); } } } if (monitor != null) { monitor.done(); } } return null; }
public IStatus buildModelElements(IScriptProject project, List elements, final IProgressMonitor monitor, boolean saveIndex) { if (elements.size() == 0) { return null; } IndexManager manager = ModelManager.getModelManager().getIndexManager(); final int elementsSize = elements.size(); IDLTKLanguageToolkit toolkit = null; IMixinParser parser = null; try { toolkit = DLTKLanguageManager.getLanguageToolkit(project); if (toolkit != null) { parser = MixinManager.getMixinParser(toolkit.getNatureId()); } } catch (CoreException e1) { if (DLTKCore.DEBUG) { e1.printStackTrace(); } } if (parser == null || toolkit == null) { return null; } Map indexes = new HashMap(); // Map imons = new HashMap(); Index mixinIndex = null; ReadWriteMonitor imon = null; try { // waitUntilIndexReady(toolkit); IPath fullPath = project.getProject().getFullPath(); String fullContainerPath = ((fullPath.getDevice() == null) ? fullPath.toString() : fullPath.toOSString()); mixinIndex = manager.getSpecialIndex("mixin", //$NON-NLS-1$ /* project.getProject() */fullPath.toString(), fullContainerPath); imon = mixinIndex.monitor; imon.enterWrite(); String name = MessageFormat.format( Messages.MixinBuilder_buildingRuntimeModelFor, new Object[] { project.getElementName() }); if (monitor != null) { monitor.beginTask(name, elementsSize); } int fileIndex = 0; for (Iterator iterator = elements.iterator(); iterator.hasNext();) { ISourceModule element = (ISourceModule) iterator.next(); Index currentIndex = mixinIndex; if (monitor != null) { if (monitor.isCanceled()) { return null; } } String taskTitle = MessageFormat.format( Messages.MixinBuilder_buildingRuntimeModelFor2, new Object[] { project.getElementName(), new Integer(elements.size() - fileIndex), element.getElementName() }); ++fileIndex; if (monitor != null) { monitor.subTask(taskTitle); } // monitor.beginTask(taskTitle, 1); IProjectFragment projectFragment = (IProjectFragment) element .getAncestor(IModelElement.PROJECT_FRAGMENT); IPath containerPath = project.getPath(); if (projectFragment instanceof ExternalProjectFragment || projectFragment instanceof BuiltinProjectFragment) { IPath path = projectFragment.getPath(); if (indexes.containsKey(path)) { currentIndex = (Index) indexes.get(path); containerPath = path; } else { String contPath = ((path.getDevice() == null) ? path.toString() : path.toOSString()); Index index = manager.getSpecialIndex("mixin", //$NON-NLS-1$ path.toString(), contPath); if (index != null) { currentIndex = index; if (!indexes.values().contains(index)) { index.monitor.enterWrite(); indexes.put(path, index); } containerPath = path; } } } SearchParticipant participant = SearchEngine .getDefaultSearchParticipant(); char[] content; try { content = element.getSourceAsCharArray(); } catch (ModelException e) { content = new char[0]; } DLTKSearchDocument document = new DLTKSearchDocument(element.getPath() .toString(), containerPath, content , participant, element instanceof ExternalSourceModule); // System.out.println("mixin indexing:" + document.getPath()); ((InternalSearchDocument) document).toolkit = toolkit; String containerRelativePath = null; if (element instanceof ExternalSourceModule) { containerRelativePath = (element.getPath() .removeFirstSegments(containerPath.segmentCount()) .setDevice(null).toString()); } else if (element instanceof SourceModule) { containerRelativePath = (element.getPath() .removeFirstSegments(1).toPortableString()); } else if (element instanceof BuiltinSourceModule) { containerRelativePath = document.getPath(); // (element.getPath() // .removeFirstSegments().toOSString()); } ((InternalSearchDocument) document) .setContainerRelativePath(containerRelativePath); currentIndex.remove(containerRelativePath); ((InternalSearchDocument) document).setIndex(currentIndex); new MixinIndexer(document, element, currentIndex) .indexDocument(); if (monitor != null) { monitor.worked(1); } } } finally { final Set saveIndexesSet = new HashSet(); if (mixinIndex != null) { if (saveIndex) { saveIndexesSet.add(mixinIndex); } else { imon.exitWrite(); } } Iterator iterator = indexes.values().iterator(); while (iterator.hasNext()) { Index index = (Index) iterator.next(); if (saveIndex) { saveIndexesSet.add(index); } else { index.monitor.exitWrite(); } } if (saveIndex) { for (Iterator ind = saveIndexesSet.iterator(); ind.hasNext();) { Index index = (Index) ind.next(); if (monitor != null) { String containerPath = index.containerPath; if (containerPath.startsWith("#special#")) { //$NON-NLS-1$ containerPath = containerPath.substring( containerPath.lastIndexOf("#"), //$NON-NLS-1$ containerPath.length()); } monitor.subTask(MessageFormat.format( Messages.MixinBuilder_savingIndexFor, new Object[] { containerPath })); } try { index.save(); } catch (IOException e) { if (DLTKCore.DEBUG) { e.printStackTrace(); } } finally { index.monitor.exitWrite(); } } } if (monitor != null) { monitor.done(); } } return null; }
diff --git a/src/main/java/cc/kune/gspace/client/options/general/UserOptGeneralPanel.java b/src/main/java/cc/kune/gspace/client/options/general/UserOptGeneralPanel.java index f98795367..dbd9671f5 100644 --- a/src/main/java/cc/kune/gspace/client/options/general/UserOptGeneralPanel.java +++ b/src/main/java/cc/kune/gspace/client/options/general/UserOptGeneralPanel.java @@ -1,211 +1,211 @@ /* * * Copyright (C) 2007-2011 The kune development team (see CREDITS for details) * This file is part of kune. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package cc.kune.gspace.client.options.general; import cc.kune.common.client.ui.MaskWidget; import cc.kune.core.client.auth.UserFieldFactory; import cc.kune.core.client.i18n.I18nUITranslationService; import cc.kune.core.client.resources.CoreResources; import cc.kune.core.client.ui.DefaultFormUtils; import cc.kune.core.shared.dto.EmailNotificationFrequency; import cc.kune.core.shared.dto.I18nLanguageSimpleDTO; import cc.kune.gspace.client.i18n.LanguageSelectorPanel; import com.extjs.gxt.ui.client.widget.form.AdapterField; import com.extjs.gxt.ui.client.widget.form.FieldSet; import com.extjs.gxt.ui.client.widget.form.FormPanel.LabelAlign; import com.extjs.gxt.ui.client.widget.form.Radio; import com.extjs.gxt.ui.client.widget.form.TextField; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Label; import com.google.inject.Inject; public class UserOptGeneralPanel extends EntityOptGeneralPanel implements UserOptGeneralView { public static final String DAILY_TYPE_ID = "k-ngp-type_daily"; public static final String EMAIL_FIELD = "k-ngp-emial"; public static final String HOURLY_TYPE_ID = "k-ngp-type_hourly"; public static final String IMMEDIATE_TYPE_ID = "k-ngp-type_immedi"; public static final String LONG_NAME_FIELD = "k-uogp-lname"; public static final String NO_TYPE_ID = "k-ngp-type_no"; public static final String TYPEOFEMAILNOTIF_FIELD = "k-ngp-type_of_email_notif"; private final Radio dailyRadio; private final TextField<String> email; private final FieldSet emailNotifTypeFieldSet; private final Radio hourlyRadio; private final Radio immediateRadio; private final LanguageSelectorPanel langSelector; private final TextField<String> longName; private final Radio noRadio; private final AdapterField notVerifLabelAdapter; private final AdapterField resendEmailVerifAdapter; private final Button resendEmailVerifBtn; @Inject public UserOptGeneralPanel(final I18nUITranslationService i18n, final CoreResources res, final MaskWidget maskWidget, final LanguageSelectorPanel langSelector, final UserFieldFactory userFieldFactory) { - super(maskWidget, res.emblemSystem(), i18n.t("General"), i18n.t("Change this values:")); + super(maskWidget, res.emblemSystem(), i18n.t("General"), i18n.t("You can change these values:")); this.langSelector = langSelector; longName = userFieldFactory.createUserLongName(LONG_NAME_FIELD); add(longName); langSelector.setLangTitle(i18n.t("Your language")); langSelector.setLabelAlign(LabelAlign.LEFT); langSelector.setLangSeparator(":"); add(langSelector); email = userFieldFactory.createUserEmail(EMAIL_FIELD); add(email); emailNotifTypeFieldSet = DefaultFormUtils.createFieldSet(i18n.t("How often do you want to receive email notifications?")); immediateRadio = DefaultFormUtils.createRadio(emailNotifTypeFieldSet, i18n.t("almost immediately"), TYPEOFEMAILNOTIF_FIELD, i18n.t( "you will receive an email with any new messages in your inbox at [%s] almost immediately", i18n.getSiteCommonName()), IMMEDIATE_TYPE_ID); immediateRadio.setTabIndex(3); immediateRadio.setValue(true); hourlyRadio = DefaultFormUtils.createRadio(emailNotifTypeFieldSet, i18n.t("at most hourly"), TYPEOFEMAILNOTIF_FIELD, i18n.t( "you will receive an email with any new messages in your inbox at [%s] at most hourly", i18n.getSiteCommonName()), HOURLY_TYPE_ID); hourlyRadio.setTabIndex(4); hourlyRadio.setValue(false); dailyRadio = DefaultFormUtils.createRadio(emailNotifTypeFieldSet, i18n.t("at most daily"), TYPEOFEMAILNOTIF_FIELD, i18n.t( "you will receive an email with any new messages in your inbox at [%s] at most daily", i18n.getSiteCommonName()), DAILY_TYPE_ID); dailyRadio.setTabIndex(5); dailyRadio.setValue(false); noRadio = DefaultFormUtils.createRadio( emailNotifTypeFieldSet, i18n.t("I don't need email notifications"), TYPEOFEMAILNOTIF_FIELD, i18n.t("you will no receive an email with any new messages in your inbox at [%s]", i18n.getSiteCommonName()), NO_TYPE_ID); noRadio.setTabIndex(6); noRadio.setValue(false); add(emailNotifTypeFieldSet); final Label notVerified = new Label( i18n.t("Your email is not verified, so you will not receive email notifications")); notVerified.setStyleName("oc-user-msg"); notVerified.addStyleName("k-3corners"); notVerifLabelAdapter = new AdapterField(notVerified); notVerifLabelAdapter.setLabelSeparator(""); notVerifLabelAdapter.setWidth(DefaultFormUtils.BIG_FIELD_SIZE); super.add(notVerifLabelAdapter); resendEmailVerifBtn = new Button(i18n.t("Resend verification email")); resendEmailVerifBtn.addStyleName("k-button"); resendEmailVerifAdapter = new AdapterField(resendEmailVerifBtn); resendEmailVerifAdapter.setValidateOnBlur(false); resendEmailVerifAdapter.setLabelSeparator(""); resendEmailVerifAdapter.setWidth(DefaultFormUtils.BIG_FIELD_SIZE); // resendEmailVerifAdapter.setFieldLabel(i18n.t("Maybe you want receive again our verification email")); add(resendEmailVerifAdapter); } @Override public String getEmail() { return email.getValue(); } @Override public EmailNotificationFrequency getEmailNotif() { if (immediateRadio.getValue()) { return EmailNotificationFrequency.immediately; } if (hourlyRadio.getValue()) { return EmailNotificationFrequency.hourly; } if (dailyRadio.getValue()) { return EmailNotificationFrequency.daily; } // if (noRadio.getValue()) return EmailNotificationFrequency.no; } @Override public I18nLanguageSimpleDTO getLanguage() { return langSelector.getLanguage(); } @Override public String getLongName() { return longName.getValue(); } @Override public HasClickHandlers getResendEmailVerif() { return resendEmailVerifBtn; } @Override public void setEmail(final String email) { this.email.setValue(email); } @Override public void setEmailNotifChecked(final EmailNotificationFrequency freq) { switch (freq) { case no: noRadio.setValue(true); break; case hourly: hourlyRadio.setValue(true); break; case daily: dailyRadio.setValue(true); break; case immediately: immediateRadio.setValue(true); break; } } @Override public void setEmailVerified(final boolean verified) { resendEmailVerifAdapter.setVisible(!verified); notVerifLabelAdapter.setVisible(!verified); emailNotifTypeFieldSet.setVisible(verified); } @Override public void setLanguage(final I18nLanguageSimpleDTO language) { langSelector.setLanguage(language); } @Override public void setLongName(final String longName) { this.longName.setValue(longName); } @Override public void setResendEmailVerifEnabled(final boolean enabled) { resendEmailVerifBtn.setEnabled(enabled); } }
true
true
public UserOptGeneralPanel(final I18nUITranslationService i18n, final CoreResources res, final MaskWidget maskWidget, final LanguageSelectorPanel langSelector, final UserFieldFactory userFieldFactory) { super(maskWidget, res.emblemSystem(), i18n.t("General"), i18n.t("Change this values:")); this.langSelector = langSelector; longName = userFieldFactory.createUserLongName(LONG_NAME_FIELD); add(longName); langSelector.setLangTitle(i18n.t("Your language")); langSelector.setLabelAlign(LabelAlign.LEFT); langSelector.setLangSeparator(":"); add(langSelector); email = userFieldFactory.createUserEmail(EMAIL_FIELD); add(email); emailNotifTypeFieldSet = DefaultFormUtils.createFieldSet(i18n.t("How often do you want to receive email notifications?")); immediateRadio = DefaultFormUtils.createRadio(emailNotifTypeFieldSet, i18n.t("almost immediately"), TYPEOFEMAILNOTIF_FIELD, i18n.t( "you will receive an email with any new messages in your inbox at [%s] almost immediately", i18n.getSiteCommonName()), IMMEDIATE_TYPE_ID); immediateRadio.setTabIndex(3); immediateRadio.setValue(true); hourlyRadio = DefaultFormUtils.createRadio(emailNotifTypeFieldSet, i18n.t("at most hourly"), TYPEOFEMAILNOTIF_FIELD, i18n.t( "you will receive an email with any new messages in your inbox at [%s] at most hourly", i18n.getSiteCommonName()), HOURLY_TYPE_ID); hourlyRadio.setTabIndex(4); hourlyRadio.setValue(false); dailyRadio = DefaultFormUtils.createRadio(emailNotifTypeFieldSet, i18n.t("at most daily"), TYPEOFEMAILNOTIF_FIELD, i18n.t( "you will receive an email with any new messages in your inbox at [%s] at most daily", i18n.getSiteCommonName()), DAILY_TYPE_ID); dailyRadio.setTabIndex(5); dailyRadio.setValue(false); noRadio = DefaultFormUtils.createRadio( emailNotifTypeFieldSet, i18n.t("I don't need email notifications"), TYPEOFEMAILNOTIF_FIELD, i18n.t("you will no receive an email with any new messages in your inbox at [%s]", i18n.getSiteCommonName()), NO_TYPE_ID); noRadio.setTabIndex(6); noRadio.setValue(false); add(emailNotifTypeFieldSet); final Label notVerified = new Label( i18n.t("Your email is not verified, so you will not receive email notifications")); notVerified.setStyleName("oc-user-msg"); notVerified.addStyleName("k-3corners"); notVerifLabelAdapter = new AdapterField(notVerified); notVerifLabelAdapter.setLabelSeparator(""); notVerifLabelAdapter.setWidth(DefaultFormUtils.BIG_FIELD_SIZE); super.add(notVerifLabelAdapter); resendEmailVerifBtn = new Button(i18n.t("Resend verification email")); resendEmailVerifBtn.addStyleName("k-button"); resendEmailVerifAdapter = new AdapterField(resendEmailVerifBtn); resendEmailVerifAdapter.setValidateOnBlur(false); resendEmailVerifAdapter.setLabelSeparator(""); resendEmailVerifAdapter.setWidth(DefaultFormUtils.BIG_FIELD_SIZE); // resendEmailVerifAdapter.setFieldLabel(i18n.t("Maybe you want receive again our verification email")); add(resendEmailVerifAdapter); }
public UserOptGeneralPanel(final I18nUITranslationService i18n, final CoreResources res, final MaskWidget maskWidget, final LanguageSelectorPanel langSelector, final UserFieldFactory userFieldFactory) { super(maskWidget, res.emblemSystem(), i18n.t("General"), i18n.t("You can change these values:")); this.langSelector = langSelector; longName = userFieldFactory.createUserLongName(LONG_NAME_FIELD); add(longName); langSelector.setLangTitle(i18n.t("Your language")); langSelector.setLabelAlign(LabelAlign.LEFT); langSelector.setLangSeparator(":"); add(langSelector); email = userFieldFactory.createUserEmail(EMAIL_FIELD); add(email); emailNotifTypeFieldSet = DefaultFormUtils.createFieldSet(i18n.t("How often do you want to receive email notifications?")); immediateRadio = DefaultFormUtils.createRadio(emailNotifTypeFieldSet, i18n.t("almost immediately"), TYPEOFEMAILNOTIF_FIELD, i18n.t( "you will receive an email with any new messages in your inbox at [%s] almost immediately", i18n.getSiteCommonName()), IMMEDIATE_TYPE_ID); immediateRadio.setTabIndex(3); immediateRadio.setValue(true); hourlyRadio = DefaultFormUtils.createRadio(emailNotifTypeFieldSet, i18n.t("at most hourly"), TYPEOFEMAILNOTIF_FIELD, i18n.t( "you will receive an email with any new messages in your inbox at [%s] at most hourly", i18n.getSiteCommonName()), HOURLY_TYPE_ID); hourlyRadio.setTabIndex(4); hourlyRadio.setValue(false); dailyRadio = DefaultFormUtils.createRadio(emailNotifTypeFieldSet, i18n.t("at most daily"), TYPEOFEMAILNOTIF_FIELD, i18n.t( "you will receive an email with any new messages in your inbox at [%s] at most daily", i18n.getSiteCommonName()), DAILY_TYPE_ID); dailyRadio.setTabIndex(5); dailyRadio.setValue(false); noRadio = DefaultFormUtils.createRadio( emailNotifTypeFieldSet, i18n.t("I don't need email notifications"), TYPEOFEMAILNOTIF_FIELD, i18n.t("you will no receive an email with any new messages in your inbox at [%s]", i18n.getSiteCommonName()), NO_TYPE_ID); noRadio.setTabIndex(6); noRadio.setValue(false); add(emailNotifTypeFieldSet); final Label notVerified = new Label( i18n.t("Your email is not verified, so you will not receive email notifications")); notVerified.setStyleName("oc-user-msg"); notVerified.addStyleName("k-3corners"); notVerifLabelAdapter = new AdapterField(notVerified); notVerifLabelAdapter.setLabelSeparator(""); notVerifLabelAdapter.setWidth(DefaultFormUtils.BIG_FIELD_SIZE); super.add(notVerifLabelAdapter); resendEmailVerifBtn = new Button(i18n.t("Resend verification email")); resendEmailVerifBtn.addStyleName("k-button"); resendEmailVerifAdapter = new AdapterField(resendEmailVerifBtn); resendEmailVerifAdapter.setValidateOnBlur(false); resendEmailVerifAdapter.setLabelSeparator(""); resendEmailVerifAdapter.setWidth(DefaultFormUtils.BIG_FIELD_SIZE); // resendEmailVerifAdapter.setFieldLabel(i18n.t("Maybe you want receive again our verification email")); add(resendEmailVerifAdapter); }
diff --git a/src/org/plovr/cli/SoyWebCommand.java b/src/org/plovr/cli/SoyWebCommand.java index 3b936fb4..5c1039ac 100644 --- a/src/org/plovr/cli/SoyWebCommand.java +++ b/src/org/plovr/cli/SoyWebCommand.java @@ -1,64 +1,64 @@ package org.plovr.cli; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Map; import org.plovr.soy.server.Config; import org.plovr.soy.server.Server; import org.plovr.util.SoyDataUtil; import com.google.common.collect.ImmutableMap; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.template.soy.data.SoyData; public class SoyWebCommand extends AbstractCommandRunner<SoyWebCommandOptions> { @Override SoyWebCommandOptions createOptions() { return new SoyWebCommandOptions(); } @Override int runCommandWithOptions(SoyWebCommandOptions options) throws IOException { String pathToGlobals = options.getCompileTimeGlobalsFile(); Map<String, ?> globals; if (pathToGlobals == null) { globals = ImmutableMap.of(); } else { File globalsFile = new File(pathToGlobals); if (!globalsFile.exists()) { throw new RuntimeException("Could not find file: " + pathToGlobals); } JsonParser parser = new JsonParser(); JsonElement root = parser.parse(new FileReader(globalsFile)); if (!root.isJsonObject()) { throw new RuntimeException("Root of globals file must be a map"); } JsonObject json = root.getAsJsonObject(); ImmutableMap.Builder<String, SoyData> builder = ImmutableMap.builder(); for (Map.Entry<String, JsonElement> entry : json.entrySet()) { JsonElement el = entry.getValue(); builder.put(entry.getKey(), SoyDataUtil.jsonToSoyData(el)); } globals = builder.build(); } Config config = new Config( options.getPort(), new File(options.getDir()), options.isStatic(), globals); Server server = new Server(config); server.run(); - return 0; + return STATUS_NO_EXIT; } @Override String getUsageIntro() { return "Specify a directory that contains Soy files"; } }
true
true
int runCommandWithOptions(SoyWebCommandOptions options) throws IOException { String pathToGlobals = options.getCompileTimeGlobalsFile(); Map<String, ?> globals; if (pathToGlobals == null) { globals = ImmutableMap.of(); } else { File globalsFile = new File(pathToGlobals); if (!globalsFile.exists()) { throw new RuntimeException("Could not find file: " + pathToGlobals); } JsonParser parser = new JsonParser(); JsonElement root = parser.parse(new FileReader(globalsFile)); if (!root.isJsonObject()) { throw new RuntimeException("Root of globals file must be a map"); } JsonObject json = root.getAsJsonObject(); ImmutableMap.Builder<String, SoyData> builder = ImmutableMap.builder(); for (Map.Entry<String, JsonElement> entry : json.entrySet()) { JsonElement el = entry.getValue(); builder.put(entry.getKey(), SoyDataUtil.jsonToSoyData(el)); } globals = builder.build(); } Config config = new Config( options.getPort(), new File(options.getDir()), options.isStatic(), globals); Server server = new Server(config); server.run(); return 0; }
int runCommandWithOptions(SoyWebCommandOptions options) throws IOException { String pathToGlobals = options.getCompileTimeGlobalsFile(); Map<String, ?> globals; if (pathToGlobals == null) { globals = ImmutableMap.of(); } else { File globalsFile = new File(pathToGlobals); if (!globalsFile.exists()) { throw new RuntimeException("Could not find file: " + pathToGlobals); } JsonParser parser = new JsonParser(); JsonElement root = parser.parse(new FileReader(globalsFile)); if (!root.isJsonObject()) { throw new RuntimeException("Root of globals file must be a map"); } JsonObject json = root.getAsJsonObject(); ImmutableMap.Builder<String, SoyData> builder = ImmutableMap.builder(); for (Map.Entry<String, JsonElement> entry : json.entrySet()) { JsonElement el = entry.getValue(); builder.put(entry.getKey(), SoyDataUtil.jsonToSoyData(el)); } globals = builder.build(); } Config config = new Config( options.getPort(), new File(options.getDir()), options.isStatic(), globals); Server server = new Server(config); server.run(); return STATUS_NO_EXIT; }
diff --git a/src/test/org/apache/hadoop/dfs/MiniDFSCluster.java b/src/test/org/apache/hadoop/dfs/MiniDFSCluster.java index 034be8a93..f70b4762e 100644 --- a/src/test/org/apache/hadoop/dfs/MiniDFSCluster.java +++ b/src/test/org/apache/hadoop/dfs/MiniDFSCluster.java @@ -1,125 +1,129 @@ package org.apache.hadoop.dfs; import java.io.*; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.*; /** * This class creates a single-process DFS cluster for junit testing. * One thread is created for each server. * The data directories for DFS are undering the testing directory. * @author Owen O'Malley */ public class MiniDFSCluster { private Configuration conf; private Thread nameNodeThread; private Thread dataNodeThread; private NameNodeRunner nameNode; private DataNodeRunner dataNode; /** * An inner class that runs a name node. */ class NameNodeRunner implements Runnable { private NameNode node; /** * Create the name node and run it. */ public void run() { try { node = new NameNode(conf); } catch (Throwable e) { node = null; System.err.println("Name node crashed:"); e.printStackTrace(); } } /** * Shutdown the name node and wait for it to finish. */ public void shutdown() { if (node != null) { node.stop(); node.join(); } } } /** * An inner class to run the data node. */ class DataNodeRunner implements Runnable { private DataNode node; /** * Create and run the data node. */ public void run() { try { File dataDir = new File(conf.get("dfs.data.dir")); dataDir.mkdirs(); node = new DataNode(conf, dataDir.getPath()); node.run(); } catch (Throwable e) { node = null; System.err.println("Data node crashed:"); e.printStackTrace(); } } /** * Shut down the server and wait for it to finish. */ public void shutdown() { if (node != null) { node.shutdown(); } } } /** * Create the config and start up the servers. */ public MiniDFSCluster(int namenodePort, Configuration conf) throws IOException { this.conf = conf; conf.set("fs.default.name", "localhost:"+ Integer.toString(namenodePort)); File base_dir = new File(System.getProperty("test.build.data"), "dfs/"); conf.set("dfs.name.dir", new File(base_dir, "name").getPath()); conf.set("dfs.data.dir", new File(base_dir, "data").getPath()); conf.setInt("dfs.replication", 1); // this timeout seems to control the minimum time for the test, so - // set it down at 5 seconds. - conf.setInt("ipc.client.timeout", 5000); + // decrease it considerably. + conf.setInt("ipc.client.timeout", 1000); NameNode.format(conf); nameNode = new NameNodeRunner(); nameNodeThread = new Thread(nameNode); nameNodeThread.start(); + try { // let namenode get started + Thread.sleep(1000); + } catch(InterruptedException e) { + } dataNode = new DataNodeRunner(); dataNodeThread = new Thread(dataNode); dataNodeThread.start(); try { // let daemons get started Thread.sleep(1000); } catch(InterruptedException e) { } } /** * Shut down the servers. */ public void shutdown() { nameNode.shutdown(); dataNode.shutdown(); } /** * Get a client handle to the DFS cluster. */ public FileSystem getFileSystem() throws IOException { return FileSystem.get(conf); } }
false
true
public MiniDFSCluster(int namenodePort, Configuration conf) throws IOException { this.conf = conf; conf.set("fs.default.name", "localhost:"+ Integer.toString(namenodePort)); File base_dir = new File(System.getProperty("test.build.data"), "dfs/"); conf.set("dfs.name.dir", new File(base_dir, "name").getPath()); conf.set("dfs.data.dir", new File(base_dir, "data").getPath()); conf.setInt("dfs.replication", 1); // this timeout seems to control the minimum time for the test, so // set it down at 5 seconds. conf.setInt("ipc.client.timeout", 5000); NameNode.format(conf); nameNode = new NameNodeRunner(); nameNodeThread = new Thread(nameNode); nameNodeThread.start(); dataNode = new DataNodeRunner(); dataNodeThread = new Thread(dataNode); dataNodeThread.start(); try { // let daemons get started Thread.sleep(1000); } catch(InterruptedException e) { } }
public MiniDFSCluster(int namenodePort, Configuration conf) throws IOException { this.conf = conf; conf.set("fs.default.name", "localhost:"+ Integer.toString(namenodePort)); File base_dir = new File(System.getProperty("test.build.data"), "dfs/"); conf.set("dfs.name.dir", new File(base_dir, "name").getPath()); conf.set("dfs.data.dir", new File(base_dir, "data").getPath()); conf.setInt("dfs.replication", 1); // this timeout seems to control the minimum time for the test, so // decrease it considerably. conf.setInt("ipc.client.timeout", 1000); NameNode.format(conf); nameNode = new NameNodeRunner(); nameNodeThread = new Thread(nameNode); nameNodeThread.start(); try { // let namenode get started Thread.sleep(1000); } catch(InterruptedException e) { } dataNode = new DataNodeRunner(); dataNodeThread = new Thread(dataNode); dataNodeThread.start(); try { // let daemons get started Thread.sleep(1000); } catch(InterruptedException e) { } }
diff --git a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/reports/TeachingVoidAnalysisReport.java b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/reports/TeachingVoidAnalysisReport.java index 77e896ae..9bbdb337 100644 --- a/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/reports/TeachingVoidAnalysisReport.java +++ b/gr.sch.ira.minoas/src/gr/sch/ira/minoas/seam/components/reports/TeachingVoidAnalysisReport.java @@ -1,359 +1,369 @@ package gr.sch.ira.minoas.seam.components.reports; import gr.sch.ira.minoas.model.core.School; import gr.sch.ira.minoas.model.core.SchoolYear; import gr.sch.ira.minoas.model.core.SpecializationGroup; import gr.sch.ira.minoas.model.core.Unit; import gr.sch.ira.minoas.seam.components.criteria.SpecializationGroupSearchType; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.Factory; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Out; import org.jboss.seam.annotations.Scope; import org.jboss.seam.annotations.datamodel.DataModel; /** * @author <a href="mailto:[email protected]">Filippos Slavik</a> */ @Name(value = "teachingVoidAnalysisReport") @Scope(ScopeType.PAGE) public class TeachingVoidAnalysisReport extends BaseReport { /** * Comment for <code>serialVersionUID</code> */ private static final long serialVersionUID = 1L; public static final int HOURS_FOR_REGULAR_POSITION = 18; private Character region; private Boolean regularEmploymentsOnly = Boolean.FALSE; @DataModel(value = "teachingVoidReport") private List<Map<String, Object>> teachingVoidReport; private School school; private SpecializationGroup specializationGroup; private List<SpecializationGroup> specializationGroups = new ArrayList<SpecializationGroup>(); @Out(required = false, scope = ScopeType.CONVERSATION) private List<SpecializationGroup> availableSpecializationGroupsForVoidAnalysisReport; private SpecializationGroupSearchType specializationGroupSearchType = SpecializationGroupSearchType.SINGLE_SPECIALIZATION_GROUP; @Factory("availableSpecializationGroupsForVoidAnalysisReport") public void constructAvailableSpecializationGroupList() { EntityManager em = getEntityManager(); this.availableSpecializationGroupsForVoidAnalysisReport = new ArrayList(getCoreSearching().getSpecializationGroups( getCoreSearching().getActiveSchoolYear(em), em)); } public void resetReport() { info("reseting report."); setTeachingVoidReport(new ArrayList<Map<String,Object>>()); school = null; region = null; specializationGroup = null; specializationGroups = new ArrayList<SpecializationGroup>(); specializationGroupSearchType = SpecializationGroupSearchType.SINGLE_SPECIALIZATION_GROUP; constructAvailableSpecializationGroupList(); } public void generateReport() { try { long started = System.currentTimeMillis(), finished; /* our report data contains a list contaning a map with key-values. Each map entry coresponds to group report item. * Each group report item has several attributes, like 'title' and 'groups' and a special 'data' which contains * another hash map contained the rows (the actual report data) for the given group report item. For example : * * "title" - > "ΠΕ19-20" (String) * "groups" -> {SpecializationGroup} * "data" -> * "ΓΥ ΜΟΙΡΩΝΑ", xx, yy * "ΓΥ ΜΠΛΑ", zz,ff */ List<Map<String, Object>> tempReportData = new ArrayList<Map<String,Object>>(); info("generating report "); /* get the active school year */ SchoolYear activeSchoolYear = getCoreSearching().getActiveSchoolYear(getEntityManager()); /* According to the user's request, construct an array of all specialization groups * that need to appear in the report */ Collection<SpecializationGroup> reportSpecializationGroups = null; if (getSpecializationGroupSearchType() == SpecializationGroupSearchType.SINGLE_SPECIALIZATION_GROUP) { /* One specialization group type requested, therefore the report will contain * either the user's selected specialization group or all specialization groups if * the user left the field unspecified */ if (getSpecializationGroup() != null) { /* user has specified a concrete specialization group */ reportSpecializationGroups = new ArrayList<SpecializationGroup>(1); reportSpecializationGroups.add(getSpecializationGroup()); Map<String, Object> item = new LinkedHashMap<String, Object>(); item.put("title", getSpecializationGroup().getTitle()); item.put("groups", reportSpecializationGroups); tempReportData.add(item); } else { /* user did not specified a concrete specialization group, * so fetch all groups */ reportSpecializationGroups = getCoreSearching().getSpecializationGroups(activeSchoolYear, getEntityManager()); for(SpecializationGroup group : reportSpecializationGroups) { Map<String, Object> item = new LinkedHashMap<String, Object>(); item.put("title", group.getTitle()); List<SpecializationGroup> h = new ArrayList<SpecializationGroup>(); h.add(group); item.put("groups", h); tempReportData.add(item); } } } else { /* user has selected many specialization groups */ reportSpecializationGroups = new ArrayList<SpecializationGroup>(getSpecializationGroups().size()); StringBuffer sb = new StringBuffer(); for(SpecializationGroup group : getSpecializationGroups()) { sb.append(group.getTitle()); sb.append(" "); } reportSpecializationGroups.addAll(getSpecializationGroups()); Map<String, Object> item = new LinkedHashMap<String, Object>(); item.put("title", sb.toString()); item.put("groups", reportSpecializationGroups); tempReportData.add(item); } /* Determine on which schools the report should be applied */ Collection<School> schools = null; if (school != null) { schools = new ArrayList<School>(1); schools.add(school); } else { schools = getCoreSearching().getSchools(getEntityManager(), region); } /* do the report */ int requiredHours = 0; int availableHours = 0; int totalMissingRegularEmployees = 0; + float totalMissingRegularEmployeesFloat = (float)0; for(Map<String, Object> reportItem : tempReportData) { /* fetch the actual effective SpecializationGroups */ List<SpecializationGroup> effectiveGroup = (List<SpecializationGroup>)reportItem.get("groups"); /* for the report schools fetch the required hours */ String queryRequiredHours = "SELECT t.school.id, SUM(t.hours) FROM TeachingRequirement t " + "WHERE t.schoolYear=:schoolYear " + "AND t.school IN (:reportSchools) " + "AND t.specialization IN (:reportSpecializationGroups) " + "GROUP BY (t.school.id)"; Collection<Object[]> declaredRequiredHours = (Collection<Object[]>)getEntityManager().createQuery(queryRequiredHours).setParameter("schoolYear", activeSchoolYear).setParameter("reportSpecializationGroups", effectiveGroup).setParameter("reportSchools", schools).getResultList(); Map<String, Long> declaredRequiredHoursMap = new HashMap<String, Long>(declaredRequiredHours.size()); for(Object[] oo : declaredRequiredHours) { declaredRequiredHoursMap.put((String)oo[0], (Long)oo[1]); } /* fetch the cdrs for for the report schools and the desired specialization groups */ String query2 = "SELECT t.unit.id, SUM(t.hours), MAX(t.unit.title) FROM TeachingHourCDR t " + "WHERE t.schoolYear=:schoolYear " + "AND t.unit IN (:reportSchools) " + "AND EXISTS (SELECT g FROM SpecializationGroup g WHERE g IN (:reportSpecializationGroups) AND g.schoolYear=:schoolYear AND t.specialization MEMBER OF g.specializations) " + "GROUP BY (t.unit.id)"; Collection<Object[]> o2 = (Collection<Object[]>)getEntityManager().createQuery(query2).setParameter("schoolYear", activeSchoolYear).setParameter("reportSpecializationGroups", effectiveGroup).setParameter("reportSchools", schools).getResultList(); List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); for(Object[] oo : o2) { Map<String, Object> d = new HashMap<String, Object>(); Long unitAvailableHours = (Long)oo[1]; Long unitRequiredHours = declaredRequiredHoursMap.containsKey(oo[0]) ? declaredRequiredHoursMap.get(oo[0]) : new Long(0); Long unitMissingHours = new Long(unitRequiredHours.longValue()-unitAvailableHours.longValue()); Long unitMissingRegularEmployees = new Long(0); - if(unitMissingHours > HOURS_FOR_REGULAR_POSITION) { + Float unitMissingRegularEmployeesFloat = new Float(0); + if((unitMissingHours > HOURS_FOR_REGULAR_POSITION) || (unitMissingHours < HOURS_FOR_REGULAR_POSITION) ) { unitMissingRegularEmployees = new Long(unitMissingHours.longValue() / HOURS_FOR_REGULAR_POSITION); + unitMissingRegularEmployeesFloat = new Float(unitMissingHours.floatValue() / HOURS_FOR_REGULAR_POSITION); } d.put("unitAvailableHours", unitAvailableHours); d.put("school", getEntityManager().find(Unit.class, oo[0])); /* at this point we should find the required hours for the given school */ data.add(d); availableHours+=unitAvailableHours.longValue(); requiredHours+=unitRequiredHours.longValue(); totalMissingRegularEmployees+=unitMissingRegularEmployees.longValue(); + totalMissingRegularEmployeesFloat+=unitMissingRegularEmployees.floatValue(); d.put("unitRequiredHours", unitRequiredHours); d.put("unitMissingHours", unitMissingHours); d.put("unitMissingHoursNeg", unitMissingHours*(-1)); d.put("unitMissingRegularEmployees", unitMissingRegularEmployees); + d.put("unitMissingRegularEmployeesNeg", unitMissingRegularEmployees*(-1)); + d.put("unitMissingRegularEmployeesFloat", unitMissingRegularEmployeesFloat); + d.put("unitMissingRegularEmployeesFloatNeg", unitMissingRegularEmployeesFloat*(-1)); } reportItem.put("data", data); reportItem.put("totalRequiredHours", new Long(requiredHours)); reportItem.put("totalAvailableHours", new Long(availableHours)); reportItem.put("totalMissingHours", new Long(requiredHours-availableHours)); reportItem.put("totalMissingHoursNeg", new Long((-1)* (requiredHours-availableHours))); reportItem.put("totalMissingRegularEmployees", new Long(totalMissingRegularEmployees)); + reportItem.put("totalMissingRegularEmployeesNeg", new Long(totalMissingRegularEmployees*(-1))); + reportItem.put("totalMissingRegularEmployeesFloat", new Float(totalMissingRegularEmployeesFloat)); + reportItem.put("totalMissingRegularEmployeesFloatNeg", new Float(totalMissingRegularEmployeesFloat*(-1))); } setTeachingVoidReport(tempReportData); finished = System.currentTimeMillis(); info("report has been generated in #0 [ms]", (finished - started)); } catch (Exception ex) { ex.printStackTrace(System.err); throw new RuntimeException(ex); } } /** * @return the region */ public Character getRegion() { return region; } /** * @return the school */ public School getSchool() { return school; } /** * @return the specializationGroup */ public SpecializationGroup getSpecializationGroup() { return specializationGroup; } /** * @return the specializationGroups */ public List<SpecializationGroup> getSpecializationGroups() { return specializationGroups; } /** * @return the specializationGroupSearchType */ public SpecializationGroupSearchType getSpecializationGroupSearchType() { return specializationGroupSearchType; } /** * @param region the region to set */ public void setRegion(Character region) { this.region = region; } /** * @param school the school to set */ public void setSchool(School school) { this.school = school; } /** * @param specializationGroup the specializationGroup to set */ public void setSpecializationGroup(SpecializationGroup specializationGroup) { this.specializationGroup = specializationGroup; } /** * @param specializationGroups the specializationGroups to set */ public void setSpecializationGroups(List<SpecializationGroup> specializationGroups) { this.specializationGroups = specializationGroups; } /** * @param specializationGroupSearchType the specializationGroupSearchType to set */ public void setSpecializationGroupSearchType(SpecializationGroupSearchType specializationGroupSearchType) { this.specializationGroupSearchType = specializationGroupSearchType; } /** * @return the regularEmploymentsOnly */ public Boolean getRegularEmploymentsOnly() { return regularEmploymentsOnly; } /** * @param regularEmploymentsOnly the regularEmploymentsOnly to set */ public void setRegularEmploymentsOnly(Boolean regularEmploymentsOnly) { this.regularEmploymentsOnly = regularEmploymentsOnly; } /** * @return the teachingVoidReport */ public List<Map<String, Object>> getTeachingVoidReport() { return teachingVoidReport; } /** * @param teachingVoidReport the teachingVoidReport to set */ public void setTeachingVoidReport(List<Map<String, Object>> teachingVoidReport) { this.teachingVoidReport = teachingVoidReport; } /** * @return the availableSpecializationGroupsForVoidAnalysisReport */ public List<SpecializationGroup> getAvailableSpecializationGroupsForVoidAnalysisReport() { return availableSpecializationGroupsForVoidAnalysisReport; } /** * @param availableSpecializationGroupsForVoidAnalysisReport the availableSpecializationGroupsForVoidAnalysisReport to set */ public void setAvailableSpecializationGroupsForVoidAnalysisReport( List<SpecializationGroup> availableSpecializationGroupsForVoidAnalysisReport) { this.availableSpecializationGroupsForVoidAnalysisReport = availableSpecializationGroupsForVoidAnalysisReport; } }
false
true
public void generateReport() { try { long started = System.currentTimeMillis(), finished; /* our report data contains a list contaning a map with key-values. Each map entry coresponds to group report item. * Each group report item has several attributes, like 'title' and 'groups' and a special 'data' which contains * another hash map contained the rows (the actual report data) for the given group report item. For example : * * "title" - > "ΠΕ19-20" (String) * "groups" -> {SpecializationGroup} * "data" -> * "ΓΥ ΜΟΙΡΩΝΑ", xx, yy * "ΓΥ ΜΠΛΑ", zz,ff */ List<Map<String, Object>> tempReportData = new ArrayList<Map<String,Object>>(); info("generating report "); /* get the active school year */ SchoolYear activeSchoolYear = getCoreSearching().getActiveSchoolYear(getEntityManager()); /* According to the user's request, construct an array of all specialization groups * that need to appear in the report */ Collection<SpecializationGroup> reportSpecializationGroups = null; if (getSpecializationGroupSearchType() == SpecializationGroupSearchType.SINGLE_SPECIALIZATION_GROUP) { /* One specialization group type requested, therefore the report will contain * either the user's selected specialization group or all specialization groups if * the user left the field unspecified */ if (getSpecializationGroup() != null) { /* user has specified a concrete specialization group */ reportSpecializationGroups = new ArrayList<SpecializationGroup>(1); reportSpecializationGroups.add(getSpecializationGroup()); Map<String, Object> item = new LinkedHashMap<String, Object>(); item.put("title", getSpecializationGroup().getTitle()); item.put("groups", reportSpecializationGroups); tempReportData.add(item); } else { /* user did not specified a concrete specialization group, * so fetch all groups */ reportSpecializationGroups = getCoreSearching().getSpecializationGroups(activeSchoolYear, getEntityManager()); for(SpecializationGroup group : reportSpecializationGroups) { Map<String, Object> item = new LinkedHashMap<String, Object>(); item.put("title", group.getTitle()); List<SpecializationGroup> h = new ArrayList<SpecializationGroup>(); h.add(group); item.put("groups", h); tempReportData.add(item); } } } else { /* user has selected many specialization groups */ reportSpecializationGroups = new ArrayList<SpecializationGroup>(getSpecializationGroups().size()); StringBuffer sb = new StringBuffer(); for(SpecializationGroup group : getSpecializationGroups()) { sb.append(group.getTitle()); sb.append(" "); } reportSpecializationGroups.addAll(getSpecializationGroups()); Map<String, Object> item = new LinkedHashMap<String, Object>(); item.put("title", sb.toString()); item.put("groups", reportSpecializationGroups); tempReportData.add(item); } /* Determine on which schools the report should be applied */ Collection<School> schools = null; if (school != null) { schools = new ArrayList<School>(1); schools.add(school); } else { schools = getCoreSearching().getSchools(getEntityManager(), region); } /* do the report */ int requiredHours = 0; int availableHours = 0; int totalMissingRegularEmployees = 0; for(Map<String, Object> reportItem : tempReportData) { /* fetch the actual effective SpecializationGroups */ List<SpecializationGroup> effectiveGroup = (List<SpecializationGroup>)reportItem.get("groups"); /* for the report schools fetch the required hours */ String queryRequiredHours = "SELECT t.school.id, SUM(t.hours) FROM TeachingRequirement t " + "WHERE t.schoolYear=:schoolYear " + "AND t.school IN (:reportSchools) " + "AND t.specialization IN (:reportSpecializationGroups) " + "GROUP BY (t.school.id)"; Collection<Object[]> declaredRequiredHours = (Collection<Object[]>)getEntityManager().createQuery(queryRequiredHours).setParameter("schoolYear", activeSchoolYear).setParameter("reportSpecializationGroups", effectiveGroup).setParameter("reportSchools", schools).getResultList(); Map<String, Long> declaredRequiredHoursMap = new HashMap<String, Long>(declaredRequiredHours.size()); for(Object[] oo : declaredRequiredHours) { declaredRequiredHoursMap.put((String)oo[0], (Long)oo[1]); } /* fetch the cdrs for for the report schools and the desired specialization groups */ String query2 = "SELECT t.unit.id, SUM(t.hours), MAX(t.unit.title) FROM TeachingHourCDR t " + "WHERE t.schoolYear=:schoolYear " + "AND t.unit IN (:reportSchools) " + "AND EXISTS (SELECT g FROM SpecializationGroup g WHERE g IN (:reportSpecializationGroups) AND g.schoolYear=:schoolYear AND t.specialization MEMBER OF g.specializations) " + "GROUP BY (t.unit.id)"; Collection<Object[]> o2 = (Collection<Object[]>)getEntityManager().createQuery(query2).setParameter("schoolYear", activeSchoolYear).setParameter("reportSpecializationGroups", effectiveGroup).setParameter("reportSchools", schools).getResultList(); List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); for(Object[] oo : o2) { Map<String, Object> d = new HashMap<String, Object>(); Long unitAvailableHours = (Long)oo[1]; Long unitRequiredHours = declaredRequiredHoursMap.containsKey(oo[0]) ? declaredRequiredHoursMap.get(oo[0]) : new Long(0); Long unitMissingHours = new Long(unitRequiredHours.longValue()-unitAvailableHours.longValue()); Long unitMissingRegularEmployees = new Long(0); if(unitMissingHours > HOURS_FOR_REGULAR_POSITION) { unitMissingRegularEmployees = new Long(unitMissingHours.longValue() / HOURS_FOR_REGULAR_POSITION); } d.put("unitAvailableHours", unitAvailableHours); d.put("school", getEntityManager().find(Unit.class, oo[0])); /* at this point we should find the required hours for the given school */ data.add(d); availableHours+=unitAvailableHours.longValue(); requiredHours+=unitRequiredHours.longValue(); totalMissingRegularEmployees+=unitMissingRegularEmployees.longValue(); d.put("unitRequiredHours", unitRequiredHours); d.put("unitMissingHours", unitMissingHours); d.put("unitMissingHoursNeg", unitMissingHours*(-1)); d.put("unitMissingRegularEmployees", unitMissingRegularEmployees); } reportItem.put("data", data); reportItem.put("totalRequiredHours", new Long(requiredHours)); reportItem.put("totalAvailableHours", new Long(availableHours)); reportItem.put("totalMissingHours", new Long(requiredHours-availableHours)); reportItem.put("totalMissingHoursNeg", new Long((-1)* (requiredHours-availableHours))); reportItem.put("totalMissingRegularEmployees", new Long(totalMissingRegularEmployees)); } setTeachingVoidReport(tempReportData); finished = System.currentTimeMillis(); info("report has been generated in #0 [ms]", (finished - started)); } catch (Exception ex) { ex.printStackTrace(System.err); throw new RuntimeException(ex); } }
public void generateReport() { try { long started = System.currentTimeMillis(), finished; /* our report data contains a list contaning a map with key-values. Each map entry coresponds to group report item. * Each group report item has several attributes, like 'title' and 'groups' and a special 'data' which contains * another hash map contained the rows (the actual report data) for the given group report item. For example : * * "title" - > "ΠΕ19-20" (String) * "groups" -> {SpecializationGroup} * "data" -> * "ΓΥ ΜΟΙΡΩΝΑ", xx, yy * "ΓΥ ΜΠΛΑ", zz,ff */ List<Map<String, Object>> tempReportData = new ArrayList<Map<String,Object>>(); info("generating report "); /* get the active school year */ SchoolYear activeSchoolYear = getCoreSearching().getActiveSchoolYear(getEntityManager()); /* According to the user's request, construct an array of all specialization groups * that need to appear in the report */ Collection<SpecializationGroup> reportSpecializationGroups = null; if (getSpecializationGroupSearchType() == SpecializationGroupSearchType.SINGLE_SPECIALIZATION_GROUP) { /* One specialization group type requested, therefore the report will contain * either the user's selected specialization group or all specialization groups if * the user left the field unspecified */ if (getSpecializationGroup() != null) { /* user has specified a concrete specialization group */ reportSpecializationGroups = new ArrayList<SpecializationGroup>(1); reportSpecializationGroups.add(getSpecializationGroup()); Map<String, Object> item = new LinkedHashMap<String, Object>(); item.put("title", getSpecializationGroup().getTitle()); item.put("groups", reportSpecializationGroups); tempReportData.add(item); } else { /* user did not specified a concrete specialization group, * so fetch all groups */ reportSpecializationGroups = getCoreSearching().getSpecializationGroups(activeSchoolYear, getEntityManager()); for(SpecializationGroup group : reportSpecializationGroups) { Map<String, Object> item = new LinkedHashMap<String, Object>(); item.put("title", group.getTitle()); List<SpecializationGroup> h = new ArrayList<SpecializationGroup>(); h.add(group); item.put("groups", h); tempReportData.add(item); } } } else { /* user has selected many specialization groups */ reportSpecializationGroups = new ArrayList<SpecializationGroup>(getSpecializationGroups().size()); StringBuffer sb = new StringBuffer(); for(SpecializationGroup group : getSpecializationGroups()) { sb.append(group.getTitle()); sb.append(" "); } reportSpecializationGroups.addAll(getSpecializationGroups()); Map<String, Object> item = new LinkedHashMap<String, Object>(); item.put("title", sb.toString()); item.put("groups", reportSpecializationGroups); tempReportData.add(item); } /* Determine on which schools the report should be applied */ Collection<School> schools = null; if (school != null) { schools = new ArrayList<School>(1); schools.add(school); } else { schools = getCoreSearching().getSchools(getEntityManager(), region); } /* do the report */ int requiredHours = 0; int availableHours = 0; int totalMissingRegularEmployees = 0; float totalMissingRegularEmployeesFloat = (float)0; for(Map<String, Object> reportItem : tempReportData) { /* fetch the actual effective SpecializationGroups */ List<SpecializationGroup> effectiveGroup = (List<SpecializationGroup>)reportItem.get("groups"); /* for the report schools fetch the required hours */ String queryRequiredHours = "SELECT t.school.id, SUM(t.hours) FROM TeachingRequirement t " + "WHERE t.schoolYear=:schoolYear " + "AND t.school IN (:reportSchools) " + "AND t.specialization IN (:reportSpecializationGroups) " + "GROUP BY (t.school.id)"; Collection<Object[]> declaredRequiredHours = (Collection<Object[]>)getEntityManager().createQuery(queryRequiredHours).setParameter("schoolYear", activeSchoolYear).setParameter("reportSpecializationGroups", effectiveGroup).setParameter("reportSchools", schools).getResultList(); Map<String, Long> declaredRequiredHoursMap = new HashMap<String, Long>(declaredRequiredHours.size()); for(Object[] oo : declaredRequiredHours) { declaredRequiredHoursMap.put((String)oo[0], (Long)oo[1]); } /* fetch the cdrs for for the report schools and the desired specialization groups */ String query2 = "SELECT t.unit.id, SUM(t.hours), MAX(t.unit.title) FROM TeachingHourCDR t " + "WHERE t.schoolYear=:schoolYear " + "AND t.unit IN (:reportSchools) " + "AND EXISTS (SELECT g FROM SpecializationGroup g WHERE g IN (:reportSpecializationGroups) AND g.schoolYear=:schoolYear AND t.specialization MEMBER OF g.specializations) " + "GROUP BY (t.unit.id)"; Collection<Object[]> o2 = (Collection<Object[]>)getEntityManager().createQuery(query2).setParameter("schoolYear", activeSchoolYear).setParameter("reportSpecializationGroups", effectiveGroup).setParameter("reportSchools", schools).getResultList(); List<Map<String, Object>> data = new ArrayList<Map<String,Object>>(); for(Object[] oo : o2) { Map<String, Object> d = new HashMap<String, Object>(); Long unitAvailableHours = (Long)oo[1]; Long unitRequiredHours = declaredRequiredHoursMap.containsKey(oo[0]) ? declaredRequiredHoursMap.get(oo[0]) : new Long(0); Long unitMissingHours = new Long(unitRequiredHours.longValue()-unitAvailableHours.longValue()); Long unitMissingRegularEmployees = new Long(0); Float unitMissingRegularEmployeesFloat = new Float(0); if((unitMissingHours > HOURS_FOR_REGULAR_POSITION) || (unitMissingHours < HOURS_FOR_REGULAR_POSITION) ) { unitMissingRegularEmployees = new Long(unitMissingHours.longValue() / HOURS_FOR_REGULAR_POSITION); unitMissingRegularEmployeesFloat = new Float(unitMissingHours.floatValue() / HOURS_FOR_REGULAR_POSITION); } d.put("unitAvailableHours", unitAvailableHours); d.put("school", getEntityManager().find(Unit.class, oo[0])); /* at this point we should find the required hours for the given school */ data.add(d); availableHours+=unitAvailableHours.longValue(); requiredHours+=unitRequiredHours.longValue(); totalMissingRegularEmployees+=unitMissingRegularEmployees.longValue(); totalMissingRegularEmployeesFloat+=unitMissingRegularEmployees.floatValue(); d.put("unitRequiredHours", unitRequiredHours); d.put("unitMissingHours", unitMissingHours); d.put("unitMissingHoursNeg", unitMissingHours*(-1)); d.put("unitMissingRegularEmployees", unitMissingRegularEmployees); d.put("unitMissingRegularEmployeesNeg", unitMissingRegularEmployees*(-1)); d.put("unitMissingRegularEmployeesFloat", unitMissingRegularEmployeesFloat); d.put("unitMissingRegularEmployeesFloatNeg", unitMissingRegularEmployeesFloat*(-1)); } reportItem.put("data", data); reportItem.put("totalRequiredHours", new Long(requiredHours)); reportItem.put("totalAvailableHours", new Long(availableHours)); reportItem.put("totalMissingHours", new Long(requiredHours-availableHours)); reportItem.put("totalMissingHoursNeg", new Long((-1)* (requiredHours-availableHours))); reportItem.put("totalMissingRegularEmployees", new Long(totalMissingRegularEmployees)); reportItem.put("totalMissingRegularEmployeesNeg", new Long(totalMissingRegularEmployees*(-1))); reportItem.put("totalMissingRegularEmployeesFloat", new Float(totalMissingRegularEmployeesFloat)); reportItem.put("totalMissingRegularEmployeesFloatNeg", new Float(totalMissingRegularEmployeesFloat*(-1))); } setTeachingVoidReport(tempReportData); finished = System.currentTimeMillis(); info("report has been generated in #0 [ms]", (finished - started)); } catch (Exception ex) { ex.printStackTrace(System.err); throw new RuntimeException(ex); } }
diff --git a/src/impl/com/sun/ws/rest/impl/modelapi/validation/BasicValidator.java b/src/impl/com/sun/ws/rest/impl/modelapi/validation/BasicValidator.java index 96131b880..2b2d59680 100644 --- a/src/impl/com/sun/ws/rest/impl/modelapi/validation/BasicValidator.java +++ b/src/impl/com/sun/ws/rest/impl/modelapi/validation/BasicValidator.java @@ -1,90 +1,90 @@ /* * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * http://www.opensource.org/licenses/cddl1.php * See the License for the specific language governing * permissions and limitations under the License. */ package com.sun.ws.rest.impl.modelapi.validation; import com.sun.ws.rest.api.core.HttpRequestContext; import com.sun.ws.rest.api.core.HttpResponseContext; import com.sun.ws.rest.api.model.AbstractResource; import com.sun.ws.rest.api.model.AbstractResourceConstructor; import com.sun.ws.rest.api.model.AbstractResourceMethod; import com.sun.ws.rest.api.model.AbstractSubResourceLocator; import com.sun.ws.rest.api.model.AbstractSubResourceMethod; import com.sun.ws.rest.api.model.ResourceModelIssue; import com.sun.ws.rest.impl.ImplMessages; /** * * @author japod */ public class BasicValidator extends AbstractModelValidator { public void visitAbstractResource(AbstractResource resource) { // resource should have at least one resource method, subresource method or subresource locator if ((resource.getResourceMethods().size() + resource.getSubResourceMethods().size() + resource.getSubResourceLocators().size()) == 0) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_NO_SUB_RES_METHOD_LOCATOR_FOUND(resource.getResourceClass()), - true)); + false)); // there might still be Views associated with the resource } - // uri template of the resource, if present should not contain null or empty value + // uri template of the resource, if present should not contain null value if (resource.isRootResource() && ((null == resource.getUriPath()) || (null == resource.getUriPath().getValue()))) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_RES_URI_PATH_INVALID(resource.getResourceClass(), resource.getUriPath()), true)); // TODO: is it really a fatal issue? } } public void visitAbstractResourceMethod(AbstractResourceMethod method) { // TODO: check in req/resp case the method has both req and resp params if (!isRequestResponseMethod(method) && ("GET".equals(method.getHttpMethod()) && (void.class == method.getMethod().getReturnType()))) { issueList.add(new ResourceModelIssue( method, ImplMessages.ERROR_GET_RETURNS_VOID(method.getMethod()), true)); } // TODO: anything else ? } public void visitAbstractSubResourceMethod(AbstractSubResourceMethod method) { visitAbstractResourceMethod(method); if ((null == method.getUriPath()) || (null == method.getUriPath().getValue()) || (method.getUriPath().getValue().length() == 0)) { issueList.add(new ResourceModelIssue( method, ImplMessages.ERROR_SUBRES_METHOD_URI_PATH_INVALID(method.getMethod(), method.getUriPath()), true)); } } public void visitAbstractSubResourceLocator(AbstractSubResourceLocator locator) { if (void.class == locator.getMethod().getReturnType()) { issueList.add(new ResourceModelIssue( locator, ImplMessages.ERROR_SUBRES_LOC_RETURNS_VOID(locator.getMethod()), true)); } if ((null == locator.getUriPath()) || (null == locator.getUriPath().getValue()) || (locator.getUriPath().getValue().length() == 0)) { issueList.add(new ResourceModelIssue( locator, ImplMessages.ERROR_SUBRES_LOC_URI_PATH_INVALID(locator.getMethod(), locator.getUriPath()), true)); } } public void visitAbstractResourceConstructor(AbstractResourceConstructor constructor) { } // TODO: the method could probably have more then 2 params... private boolean isRequestResponseMethod(AbstractResourceMethod method) { return (method.getMethod().getParameterTypes().length == 2) && (HttpRequestContext.class == method.getMethod().getParameterTypes()[0]) && (HttpResponseContext.class == method.getMethod().getParameterTypes()[1]); } }
false
true
public void visitAbstractResource(AbstractResource resource) { // resource should have at least one resource method, subresource method or subresource locator if ((resource.getResourceMethods().size() + resource.getSubResourceMethods().size() + resource.getSubResourceLocators().size()) == 0) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_NO_SUB_RES_METHOD_LOCATOR_FOUND(resource.getResourceClass()), true)); } // uri template of the resource, if present should not contain null or empty value if (resource.isRootResource() && ((null == resource.getUriPath()) || (null == resource.getUriPath().getValue()))) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_RES_URI_PATH_INVALID(resource.getResourceClass(), resource.getUriPath()), true)); // TODO: is it really a fatal issue? } }
public void visitAbstractResource(AbstractResource resource) { // resource should have at least one resource method, subresource method or subresource locator if ((resource.getResourceMethods().size() + resource.getSubResourceMethods().size() + resource.getSubResourceLocators().size()) == 0) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_NO_SUB_RES_METHOD_LOCATOR_FOUND(resource.getResourceClass()), false)); // there might still be Views associated with the resource } // uri template of the resource, if present should not contain null value if (resource.isRootResource() && ((null == resource.getUriPath()) || (null == resource.getUriPath().getValue()))) { issueList.add(new ResourceModelIssue( resource, ImplMessages.ERROR_RES_URI_PATH_INVALID(resource.getResourceClass(), resource.getUriPath()), true)); // TODO: is it really a fatal issue? } }
diff --git a/src/main/java/org/structnetalign/PipelineManager.java b/src/main/java/org/structnetalign/PipelineManager.java index 1ec9a6c..93cad25 100644 --- a/src/main/java/org/structnetalign/PipelineManager.java +++ b/src/main/java/org/structnetalign/PipelineManager.java @@ -1,366 +1,368 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE * file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * @author dmyersturnbull */ package org.structnetalign; import java.io.File; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.structnetalign.ReportGenerator.DegenerateSetEntry; import org.structnetalign.ReportGenerator.UpdateTableEntry; import org.structnetalign.cross.CrossingManager; import org.structnetalign.cross.SimpleCrossingManager; import org.structnetalign.merge.ConcurrentBronKerboschMergeManager; import org.structnetalign.merge.MergeManager; import org.structnetalign.merge.MergeUpdate; import org.structnetalign.util.EdgeTrimmer; import org.structnetalign.util.EdgeWeighter; import org.structnetalign.util.GraphInteractionAdaptor; import org.structnetalign.util.GraphMLAdaptor; import org.structnetalign.util.IdentifierMapping; import org.structnetalign.util.IdentifierMappingFactory; import org.structnetalign.util.InteractionUpdate; import org.structnetalign.util.NetworkUtils; import org.structnetalign.weight.SimpleWeightCreator; import org.structnetalign.weight.SmarterWeightManager; import org.structnetalign.weight.WeightCreator; import org.structnetalign.weight.WeightManager; import psidev.psi.mi.xml.model.EntrySet; import edu.uci.ics.jung.graph.UndirectedGraph; import edu.uci.ics.jung.graph.util.Pair; /** * The main class of Struct-NA. Performs 3 steps: * <ol> * <li>Weighting: identifies homologs</li> * <li>Crossing: updates the probabilities of interactions that are conserved across homologs</li> * <li>Merging: merges degenerate vertex sets into a single representative per set</li> * </ol> * Reads an input MIF25 network and generates an output MIF25 network after performing the above 3 steps. * * @author dmyersturnbull * @see CLI */ public class PipelineManager { public static final int N_CORES = Math.max(Runtime.getRuntime().availableProcessors() - 1, 1); public static final double TAU = 0.5; public static final int XI = 2; public static final double ZETA = 0.7; private static final Logger logger = LogManager.getLogger("org.structnetalign"); private CrossingManager crossingManager; private MergeManager mergeManager; private int nCores; private boolean noCross; private boolean noMerge; private WeightCreator phi; private boolean report = false; private double tau = TAU; private WeightManager weightManager; private boolean writeSteps = false; private Integer xi; // depends on CrossingManager private double zeta = ZETA; public boolean isNoCross() { return noCross; } public boolean isNoMerge() { return noMerge; } public boolean isReport() { return report; } public boolean isWriteSteps() { return writeSteps; } /** * Runs the entire pipeline. */ public void run(File input, File output) { int startTime = (int) (System.currentTimeMillis() / 1000L); init(); // handle reporting // always do this even if we're not generating the report, since MergeManager etc. needs it String timestamp = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String path = output.getParent() + File.separator + "report-" + timestamp + File.separator; if (report || writeSteps) new File(path).mkdir(); // don't make a new directory if we're not reporting File reportFile = new File(path + "report.html"); ReportGenerator.setInstance(new ReportGenerator(reportFile)); if (report) { ReportGenerator.getInstance().put("n_cores", nCores); if (phi != null) ReportGenerator.getInstance().put("phi", phi.getClass().getSimpleName()); ReportGenerator.getInstance().put("tau", tau); ReportGenerator.getInstance().put("zeta", zeta); if (xi != null) ReportGenerator.getInstance().put("xi", xi); } // make a trimmer EdgeWeighter<HomologyEdge> weighter = new EdgeWeighter<HomologyEdge>() { @Override public double getWeight(HomologyEdge e) { return e.getWeight(); } }; EdgeTrimmer<Integer, HomologyEdge> trimmer = new EdgeTrimmer<>(weighter); CleverGraph graph; { // build the graph EntrySet entrySet = NetworkUtils.readNetwork(input); UndirectedGraph<Integer, InteractionEdge> interaction = GraphInteractionAdaptor.toGraph(entrySet); graph = new CleverGraph(interaction); // assign weights Map<Integer, String> uniProtIds = NetworkUtils.getUniProtIds(entrySet); weightManager.assignWeights(graph, uniProtIds); } System.gc(); // trim with tau trimmer.trim(graph.getHomology(), tau); if (report) { ReportGenerator.getInstance().saveWeighted(graph); } if (writeSteps) { GraphMLAdaptor.writeHomologyGraph(graph.getHomology(), new File(path + "hom_weighted.graphml.xml")); GraphMLAdaptor.writeInteractionGraph(graph.getInteraction(), new File(path + "int_weighted.graphml.xml")); } // cross if (!noCross) { crossingManager.cross(graph); } // trim with zeta trimmer.trim(graph.getHomology(), zeta); // report progress if (writeSteps) { GraphMLAdaptor.writeHomologyGraph(graph.getHomology(), new File(path + "hom_crossed.graphml.xml")); GraphMLAdaptor.writeInteractionGraph(graph.getInteraction(), new File(path + "int_crossed.graphml.xml")); } if (report) { ReportGenerator.getInstance().saveCrossed(graph); } // merge List<MergeUpdate> merges = null; if (!noMerge) { merges = mergeManager.merge(graph); } // report progress if (writeSteps) { GraphMLAdaptor.writeHomologyGraph(graph.getHomology(), new File(path + "hom_merged.graphml.xml")); GraphMLAdaptor.writeInteractionGraph(graph.getInteraction(), new File(path + "int_merged.graphml.xml")); } if (report) { ReportGenerator.getInstance().saveMerged(graph); } // just to free up memory crossingManager = null; mergeManager = null; trimmer = null; // now output Map<Integer, Integer> interactionsRemoved = new WeakHashMap<>(); Map<Integer, Integer> interactorsRemoved = new WeakHashMap<>(); - for (MergeUpdate update : merges) { - for (InteractionEdge e : update.getInteractionEdges()) { - interactionsRemoved.put(e.getId(), update.getV0()); - } - for (int v : update.getVertices()) { - interactorsRemoved.put(v, update.getV0()); + if (merges != null) { + for (MergeUpdate update : merges) { + for (InteractionEdge e : update.getInteractionEdges()) { + interactionsRemoved.put(e.getId(), update.getV0()); + } + for (int v : update.getVertices()) { + interactorsRemoved.put(v, update.getV0()); + } } } EntrySet entrySet = NetworkUtils.readNetwork(input); List<InteractionUpdate> updates = GraphInteractionAdaptor.modifyProbabilites(entrySet, graph.getInteraction(), interactionsRemoved, interactorsRemoved); NetworkUtils.writeNetwork(entrySet, output); int endTime = (int) (System.currentTimeMillis() / 1000L); if (report) { putUpdates(updates); putMerges(merges, entrySet); ReportGenerator.getInstance().put("time_taken", endTime - startTime); ReportGenerator.getInstance().write(); } int count = Thread.activeCount() - 1; if (count > 0) { logger.warn("There are " + count + " lingering threads. Exiting anyway."); System.exit(0); } } public void setCrossingManager(CrossingManager crossingManager) { this.crossingManager = crossingManager; } public void setMergeManager(MergeManager mergeManager) { this.mergeManager = mergeManager; } public void setNCores(int nCores) { this.nCores = nCores; } public void setNoCross(boolean noCross) { this.noCross = noCross; } public void setNoMerge(boolean noMerge) { this.noMerge = noMerge; } public void setPhi(WeightCreator phi) { this.phi = phi; } public void setReport(boolean report) { this.report = report; } /** * @param tau * The minimum threshold to apply to homology edges before doing crossing. */ public void setTau(double tau) { this.tau = tau; } public void setWeightManager(WeightManager weightManager) { this.weightManager = weightManager; } public void setWriteSteps(boolean writeSteps) { this.writeSteps = writeSteps; } /** * @param xi * The maximum search depth for traversal during crossing. */ public void setXi(int xi) { this.xi = xi; } /** * @param zeta * The minimum threshold to apply to homology edges before doing merging */ public void setZeta(double zeta) { this.zeta = zeta; } /** * Initializes a new PipelineManager using the default parameters. Once this has been performed, setting of * variables will have no effect. */ private void init() { if (nCores == 0) nCores = Runtime.getRuntime().availableProcessors() - 1; if (weightManager == null) { if (xi == null) xi = XI; if (phi == null) phi = new SimpleWeightCreator(); SmarterWeightManager weightManager = new SmarterWeightManager(phi, nCores); this.weightManager = weightManager; } if (crossingManager == null) { crossingManager = new SimpleCrossingManager(nCores, xi); } if (mergeManager == null) { mergeManager = new ConcurrentBronKerboschMergeManager(nCores); } } private void putMerges(List<MergeUpdate> merges, EntrySet entrySet) { Map<Integer, String> uniProtIds = NetworkUtils.getUniProtIds(entrySet); final IdentifierMapping mapping = IdentifierMappingFactory.getMapping(); List<DegenerateSetEntry> entries = new ArrayList<>(); for (MergeUpdate update : merges) { final int v0 = update.getV0(); DegenerateSetEntry entry = new DegenerateSetEntry(); entry.v0 = update.getV0(); entry.uniProtId0 = uniProtIds.get(v0); for (int v : update.getVertices()) { if (v == v0) continue; // for reporting, we only want non-representative degenerate vertices entry.getIds().add(v); final String uniProtId = uniProtIds.get(v); entry.getUniProtIds().add(uniProtId); entry.getPdbIds().add(mapping.uniProtToPdb(uniProtId)); entry.getScopIds().add(mapping.uniProtToScop(uniProtId)); } for (InteractionEdge edge : update.getInteractionEdges()) { entry.getInteractionIds().add(edge.getId()); } entries.add(entry); } if (!entries.isEmpty()) { ReportGenerator.getInstance().put("degenerate_sets", entries); } } private void putUpdates(List<InteractionUpdate> updates) { NumberFormat nf = new DecimalFormat(); // we do it this way because our code knows better, weirdly nf.setMaximumFractionDigits(3); final IdentifierMapping mapping = IdentifierMappingFactory.getMapping(); List<UpdateTableEntry> updated = new ArrayList<>(); for (InteractionUpdate update : updates) { if (update.isRemoved()) continue; UpdateTableEntry entry = new UpdateTableEntry(); entry.interaction = update.getEdge().getId(); entry.before = Double.parseDouble(nf.format(update.getInitialProbability())); entry.after = Double.parseDouble(nf.format(update.getEdge().getWeight())); entry.ids = update.getIds(); entry.uniProtIds = update.getUniProtIds(); String pdb1 = mapping.uniProtToPdb(update.getUniProtIds().getFirst()); pdb1 = pdb1.substring(0, pdb1.length() - 2); String pdb2 = mapping.uniProtToPdb(update.getUniProtIds().getSecond()); pdb2 = pdb2.substring(0, pdb2.length() - 2); entry.pdbIds = new Pair<String>(pdb1, pdb2); String scop1 = mapping.uniProtToScop(update.getUniProtIds().getFirst()); String scop2 = mapping.uniProtToScop(update.getUniProtIds().getSecond()); entry.scopIds = new Pair<String>(scop1, scop2); updated.add(entry); } if (!updated.isEmpty()) { ReportGenerator.getInstance().put("updated", updated); } } }
true
true
public void run(File input, File output) { int startTime = (int) (System.currentTimeMillis() / 1000L); init(); // handle reporting // always do this even if we're not generating the report, since MergeManager etc. needs it String timestamp = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String path = output.getParent() + File.separator + "report-" + timestamp + File.separator; if (report || writeSteps) new File(path).mkdir(); // don't make a new directory if we're not reporting File reportFile = new File(path + "report.html"); ReportGenerator.setInstance(new ReportGenerator(reportFile)); if (report) { ReportGenerator.getInstance().put("n_cores", nCores); if (phi != null) ReportGenerator.getInstance().put("phi", phi.getClass().getSimpleName()); ReportGenerator.getInstance().put("tau", tau); ReportGenerator.getInstance().put("zeta", zeta); if (xi != null) ReportGenerator.getInstance().put("xi", xi); } // make a trimmer EdgeWeighter<HomologyEdge> weighter = new EdgeWeighter<HomologyEdge>() { @Override public double getWeight(HomologyEdge e) { return e.getWeight(); } }; EdgeTrimmer<Integer, HomologyEdge> trimmer = new EdgeTrimmer<>(weighter); CleverGraph graph; { // build the graph EntrySet entrySet = NetworkUtils.readNetwork(input); UndirectedGraph<Integer, InteractionEdge> interaction = GraphInteractionAdaptor.toGraph(entrySet); graph = new CleverGraph(interaction); // assign weights Map<Integer, String> uniProtIds = NetworkUtils.getUniProtIds(entrySet); weightManager.assignWeights(graph, uniProtIds); } System.gc(); // trim with tau trimmer.trim(graph.getHomology(), tau); if (report) { ReportGenerator.getInstance().saveWeighted(graph); } if (writeSteps) { GraphMLAdaptor.writeHomologyGraph(graph.getHomology(), new File(path + "hom_weighted.graphml.xml")); GraphMLAdaptor.writeInteractionGraph(graph.getInteraction(), new File(path + "int_weighted.graphml.xml")); } // cross if (!noCross) { crossingManager.cross(graph); } // trim with zeta trimmer.trim(graph.getHomology(), zeta); // report progress if (writeSteps) { GraphMLAdaptor.writeHomologyGraph(graph.getHomology(), new File(path + "hom_crossed.graphml.xml")); GraphMLAdaptor.writeInteractionGraph(graph.getInteraction(), new File(path + "int_crossed.graphml.xml")); } if (report) { ReportGenerator.getInstance().saveCrossed(graph); } // merge List<MergeUpdate> merges = null; if (!noMerge) { merges = mergeManager.merge(graph); } // report progress if (writeSteps) { GraphMLAdaptor.writeHomologyGraph(graph.getHomology(), new File(path + "hom_merged.graphml.xml")); GraphMLAdaptor.writeInteractionGraph(graph.getInteraction(), new File(path + "int_merged.graphml.xml")); } if (report) { ReportGenerator.getInstance().saveMerged(graph); } // just to free up memory crossingManager = null; mergeManager = null; trimmer = null; // now output Map<Integer, Integer> interactionsRemoved = new WeakHashMap<>(); Map<Integer, Integer> interactorsRemoved = new WeakHashMap<>(); for (MergeUpdate update : merges) { for (InteractionEdge e : update.getInteractionEdges()) { interactionsRemoved.put(e.getId(), update.getV0()); } for (int v : update.getVertices()) { interactorsRemoved.put(v, update.getV0()); } } EntrySet entrySet = NetworkUtils.readNetwork(input); List<InteractionUpdate> updates = GraphInteractionAdaptor.modifyProbabilites(entrySet, graph.getInteraction(), interactionsRemoved, interactorsRemoved); NetworkUtils.writeNetwork(entrySet, output); int endTime = (int) (System.currentTimeMillis() / 1000L); if (report) { putUpdates(updates); putMerges(merges, entrySet); ReportGenerator.getInstance().put("time_taken", endTime - startTime); ReportGenerator.getInstance().write(); } int count = Thread.activeCount() - 1; if (count > 0) { logger.warn("There are " + count + " lingering threads. Exiting anyway."); System.exit(0); } }
public void run(File input, File output) { int startTime = (int) (System.currentTimeMillis() / 1000L); init(); // handle reporting // always do this even if we're not generating the report, since MergeManager etc. needs it String timestamp = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); String path = output.getParent() + File.separator + "report-" + timestamp + File.separator; if (report || writeSteps) new File(path).mkdir(); // don't make a new directory if we're not reporting File reportFile = new File(path + "report.html"); ReportGenerator.setInstance(new ReportGenerator(reportFile)); if (report) { ReportGenerator.getInstance().put("n_cores", nCores); if (phi != null) ReportGenerator.getInstance().put("phi", phi.getClass().getSimpleName()); ReportGenerator.getInstance().put("tau", tau); ReportGenerator.getInstance().put("zeta", zeta); if (xi != null) ReportGenerator.getInstance().put("xi", xi); } // make a trimmer EdgeWeighter<HomologyEdge> weighter = new EdgeWeighter<HomologyEdge>() { @Override public double getWeight(HomologyEdge e) { return e.getWeight(); } }; EdgeTrimmer<Integer, HomologyEdge> trimmer = new EdgeTrimmer<>(weighter); CleverGraph graph; { // build the graph EntrySet entrySet = NetworkUtils.readNetwork(input); UndirectedGraph<Integer, InteractionEdge> interaction = GraphInteractionAdaptor.toGraph(entrySet); graph = new CleverGraph(interaction); // assign weights Map<Integer, String> uniProtIds = NetworkUtils.getUniProtIds(entrySet); weightManager.assignWeights(graph, uniProtIds); } System.gc(); // trim with tau trimmer.trim(graph.getHomology(), tau); if (report) { ReportGenerator.getInstance().saveWeighted(graph); } if (writeSteps) { GraphMLAdaptor.writeHomologyGraph(graph.getHomology(), new File(path + "hom_weighted.graphml.xml")); GraphMLAdaptor.writeInteractionGraph(graph.getInteraction(), new File(path + "int_weighted.graphml.xml")); } // cross if (!noCross) { crossingManager.cross(graph); } // trim with zeta trimmer.trim(graph.getHomology(), zeta); // report progress if (writeSteps) { GraphMLAdaptor.writeHomologyGraph(graph.getHomology(), new File(path + "hom_crossed.graphml.xml")); GraphMLAdaptor.writeInteractionGraph(graph.getInteraction(), new File(path + "int_crossed.graphml.xml")); } if (report) { ReportGenerator.getInstance().saveCrossed(graph); } // merge List<MergeUpdate> merges = null; if (!noMerge) { merges = mergeManager.merge(graph); } // report progress if (writeSteps) { GraphMLAdaptor.writeHomologyGraph(graph.getHomology(), new File(path + "hom_merged.graphml.xml")); GraphMLAdaptor.writeInteractionGraph(graph.getInteraction(), new File(path + "int_merged.graphml.xml")); } if (report) { ReportGenerator.getInstance().saveMerged(graph); } // just to free up memory crossingManager = null; mergeManager = null; trimmer = null; // now output Map<Integer, Integer> interactionsRemoved = new WeakHashMap<>(); Map<Integer, Integer> interactorsRemoved = new WeakHashMap<>(); if (merges != null) { for (MergeUpdate update : merges) { for (InteractionEdge e : update.getInteractionEdges()) { interactionsRemoved.put(e.getId(), update.getV0()); } for (int v : update.getVertices()) { interactorsRemoved.put(v, update.getV0()); } } } EntrySet entrySet = NetworkUtils.readNetwork(input); List<InteractionUpdate> updates = GraphInteractionAdaptor.modifyProbabilites(entrySet, graph.getInteraction(), interactionsRemoved, interactorsRemoved); NetworkUtils.writeNetwork(entrySet, output); int endTime = (int) (System.currentTimeMillis() / 1000L); if (report) { putUpdates(updates); putMerges(merges, entrySet); ReportGenerator.getInstance().put("time_taken", endTime - startTime); ReportGenerator.getInstance().write(); } int count = Thread.activeCount() - 1; if (count > 0) { logger.warn("There are " + count + " lingering threads. Exiting anyway."); System.exit(0); } }
diff --git a/src/usask/hci/fastdraw/DrawView.java b/src/usask/hci/fastdraw/DrawView.java index d49e246..29a1ecc 100644 --- a/src/usask/hci/fastdraw/DrawView.java +++ b/src/usask/hci/fastdraw/DrawView.java @@ -1,1019 +1,1019 @@ package usask.hci.fastdraw; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import usask.hci.fastdraw.GestureDetector.Gesture; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.os.Handler; import android.util.Log; import android.util.SparseArray; import android.view.MotionEvent; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.NumberPicker; public class DrawView extends View { private MainActivity mMainActivity; private StudyLogger mLog; private StudyController mStudyCtl; private boolean mStudyMode; private Bitmap mBitmap; private Paint mBitmapPaint; private final int mCols = 4; private final int mRows = 5; private float mColWidth; private float mRowHeight; private boolean mShowOverlay; private long mOverlayStart; private Paint mPaint; private int mSelected; private long mPressedInsideTime; private int mFingerInside; private boolean mCheckOverlay; private Set<Integer> mFingers; private Set<Integer> mIgnoredFingers; private Selection[] mSelections; private HashMap<Gesture, Integer> mGestureSelections; private Tool mTool; private int mColor; private int mThickness; private String mToolName; private String mColorName; private String mThicknessName; private Bitmap mUndo; private Bitmap mNextUndo; private boolean mLeftHanded; private final float mThreshold = 10; // pixel distance before tool registers private SparseArray<PointF> mOrigins; private boolean mPermanentGrid; private Rect mTextBounds; private SparseArray<Long> mFlashTimes; private SparseArray<Long> mRecentTouches; private boolean mChanged; private GestureDetector mGestureDetector; private int mPossibleGestureFinger; private long mPossibleGestureFingerTime; private int mGestureFinger; private long mGestureMenuTime; private PointF mGestureFingerPos; private boolean mInstantMenu; private boolean mShowGestureMenu; private Gesture mActiveCategory; private PointF mActiveCategoryOrigin; private Gesture mSubSelection; private UI mUI; private final Handler mHandler = new Handler(); private static final int mChordDelay = 1000 * 1000 * 200; // 200 ms in ns private static final int mFlashDelay = 1000 * 1000 * 400; // 400 ms in ns private static final int mGestureMenuDelay = 1000 * 1000 * 200; // 200 ms in ns private static final int mTrialDelay = 500; // 500 ms private static final int mBlockDelay = 1000; // 1 sec private static final int mOverlayButtonIndex = 16; private static final int mGestureButtonDist = 150; private static final int mGestureButtonSize = 75; private enum UI { CHORD, GESTURE } private enum Action { SAVE, CLEAR, UNDO } private enum SelectionType { TOOL, COLOR, THICKNESS, ACTION } private class Selection { public Object object; public String name; public SelectionType type; public Selection(Object object, String name, SelectionType type) { this.object = object; this.name = name; this.type = type; } } public DrawView(Context mainActivity) { super(mainActivity); if (!(mainActivity instanceof MainActivity)) { Log.e("DrawView", "DrawView was not given the MainActivity"); return; } mUI = UI.CHORD; mMainActivity = (MainActivity) mainActivity; mStudyMode = false; mLog = new StudyLogger(mainActivity); mStudyCtl = new StudyController(mLog); mBitmapPaint = new Paint(Paint.DITHER_FLAG); mPaint = new Paint(); mPaint.setTextSize(26); mPaint.setTextAlign(Align.CENTER); mSelected = -1; mFingerInside = -1; mCheckOverlay = true; mFingers = new HashSet<Integer>(); mIgnoredFingers = new HashSet<Integer>(); mLeftHanded = false; mPermanentGrid = false; mOrigins = new SparseArray<PointF>(); mTextBounds = new Rect(); mFlashTimes = new SparseArray<Long>(); mRecentTouches = new SparseArray<Long>(); mChanged = false; mGestureDetector = new GestureDetector(); mGestureFinger = -1; mPossibleGestureFinger = -1; mInstantMenu = false; mShowGestureMenu = false; mActiveCategory = Gesture.UNKNOWN; mActiveCategoryOrigin = new PointF(); mSubSelection = Gesture.UNKNOWN; mSelections = new Selection[] { new Selection(new PaintTool(this), "Paintbrush", SelectionType.TOOL), new Selection(new LineTool(this), "Line", SelectionType.TOOL), new Selection(new CircleTool(this), "Circle", SelectionType.TOOL), new Selection(new RectangleTool(this), "Rectangle", SelectionType.TOOL), new Selection(Color.BLACK, "Black", SelectionType.COLOR), new Selection(Color.RED, "Red", SelectionType.COLOR), new Selection(Color.GREEN, "Green", SelectionType.COLOR), new Selection(Color.BLUE, "Blue", SelectionType.COLOR), new Selection(Color.WHITE, "White", SelectionType.COLOR), new Selection(Color.YELLOW, "Yellow", SelectionType.COLOR), new Selection(Color.CYAN, "Cyan", SelectionType.COLOR), new Selection(Color.MAGENTA, "Magenta", SelectionType.COLOR), new Selection(1, "Fine", SelectionType.THICKNESS), new Selection(6, "Thin", SelectionType.THICKNESS), new Selection(16, "Normal", SelectionType.THICKNESS), new Selection(50, "Wide", SelectionType.THICKNESS), null, // The position of the command map button new Selection(Action.SAVE, "Save", SelectionType.ACTION), new Selection(Action.CLEAR, "Clear", SelectionType.ACTION), new Selection(Action.UNDO, "Undo", SelectionType.ACTION) }; mGestureSelections = new HashMap<Gesture, Integer>(); mGestureSelections.put(Gesture.UP, 0); // Paintbrush mGestureSelections.put(Gesture.UP_RIGHT, 1); // Line mGestureSelections.put(Gesture.UP_DOWN, 2); // Circle mGestureSelections.put(Gesture.UP_LEFT, 3); // Rectangle mGestureSelections.put(Gesture.LEFT, 4); // Black mGestureSelections.put(Gesture.LEFT_UP, 5); // Red mGestureSelections.put(Gesture.LEFT_RIGHT, 6); // Green mGestureSelections.put(Gesture.LEFT_DOWN, 7); // Blue mGestureSelections.put(Gesture.RIGHT, 8); // White mGestureSelections.put(Gesture.RIGHT_DOWN, 9); // Yellow mGestureSelections.put(Gesture.RIGHT_LEFT, 10); // Cyan mGestureSelections.put(Gesture.RIGHT_UP, 11); // Magenta mGestureSelections.put(Gesture.DOWN_LEFT, 12); // Fine mGestureSelections.put(Gesture.DOWN_UP, 13); // Thin mGestureSelections.put(Gesture.DOWN, 14); // Normal mGestureSelections.put(Gesture.DOWN_RIGHT, 15); // Wide // Default to thin black paintbrush changeSelection(0, false); changeSelection(4, false); changeSelection(13, false); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { long now = System.nanoTime(); if (mUI == UI.CHORD) { synchronized (mFlashTimes) { for (int i = 0; i < mFlashTimes.size(); i++) { long time = mFlashTimes.valueAt(i); if (now - time > mFlashDelay) { mFlashTimes.removeAt(i); postInvalidate(); } } } if (mFingerInside != -1 && now - mPressedInsideTime > mChordDelay && mCheckOverlay && !mShowOverlay) { mOverlayStart = now; mShowOverlay = true; mLog.event("Overlay shown"); mTool.clearFingers(); postInvalidate(); } } else if (mUI == UI.GESTURE) { if (mPossibleGestureFinger != -1 && now - mPossibleGestureFingerTime > mGestureMenuDelay && !mChanged) { mGestureFinger = mPossibleGestureFinger; mIgnoredFingers.add(mGestureFinger); mPossibleGestureFinger = -1; mShowGestureMenu = true; mGestureMenuTime = now; postInvalidate(); } } } }, 25, 25); View studySetupLayout = mMainActivity.getLayoutInflater().inflate(R.layout.study_setup, null); final CheckBox studyCheckBox = (CheckBox) studySetupLayout.findViewById(R.id.study_mode_checkbox); final CheckBox gestureCheckBox = (CheckBox) studySetupLayout.findViewById(R.id.gesture_mode_checkbox); final CheckBox leftHandedCheckBox = (CheckBox) studySetupLayout.findViewById(R.id.left_handed_checkbox); final CheckBox permanentGridCheckBox = (CheckBox) studySetupLayout.findViewById(R.id.permanent_grid_checkbox); gestureCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { leftHandedCheckBox.setEnabled(!isChecked); permanentGridCheckBox.setEnabled(!isChecked); } }); final NumberPicker subjectIdPicker = (NumberPicker) studySetupLayout.findViewById(R.id.subject_id_picker); subjectIdPicker.setMinValue(0); subjectIdPicker.setMaxValue(99); subjectIdPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); // Remove the virtual keyboard final NumberPicker setNumPicker = (NumberPicker) studySetupLayout.findViewById(R.id.set_num_picker); setNumPicker.setMinValue(1); setNumPicker.setMaxValue(mStudyCtl.getNumSets()); setNumPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); // Remove the virtual keyboard final NumberPicker blockNumPicker = (NumberPicker) studySetupLayout.findViewById(R.id.block_num_picker); blockNumPicker.setMinValue(1); blockNumPicker.setMaxValue(mStudyCtl.getNumBlocks(1)); blockNumPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); // Remove the virtual keyboard setNumPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { blockNumPicker.setMaxValue(mStudyCtl.getNumBlocks(newVal)); } }); new AlertDialog.Builder(mainActivity) .setMessage(R.string.dialog_study_mode) .setCancelable(false) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mStudyMode = studyCheckBox.isChecked(); if (mStudyMode) { mStudyCtl.setSetNum(setNumPicker.getValue()); mStudyCtl.setBlockNum(blockNumPicker.getValue()); mMainActivity.setTitle("Your targets will appear here."); pauseStudy("Press OK when you are ready to begin."); } mLog.setSubjectId(subjectIdPicker.getValue()); mUI = gestureCheckBox.isChecked() ? UI.GESTURE : UI.CHORD; mLeftHanded = leftHandedCheckBox.isChecked(); mPermanentGrid = permanentGridCheckBox.isChecked(); DrawView.this.invalidate(); } }) .setView(studySetupLayout) .show(); mMainActivity.getActionBar().setIcon(R.drawable.trans); } public void pauseStudy(String message) { new AlertDialog.Builder(mMainActivity) .setMessage(message) .setCancelable(false) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Runnable waitStep = new Runnable() { @Override public void run() { mStudyCtl.waitStep(false); mMainActivity.setTitle(mStudyCtl.getPrompt()); } }; mStudyCtl.hideTargets(); waitStep.run(); mHandler.postDelayed(waitStep, mBlockDelay / 4); mHandler.postDelayed(waitStep, mBlockDelay / 2); mHandler.postDelayed(waitStep, mBlockDelay * 3 / 4); mHandler.postDelayed(waitStep, mBlockDelay); } }) .show(); } public void alert(String message) { new AlertDialog.Builder(mMainActivity) .setMessage(message) .setCancelable(false) .setPositiveButton(android.R.string.yes, null) .show(); } public int getColor() { return mColor; } public int getThickness() { return mThickness; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mBitmap); canvas.drawRGB(0xFF, 0xFF, 0xFF); mColWidth = (float)w / mCols; mRowHeight = (float)h / mRows; } private RectF getButtonBounds(int index) { int y = index / mCols; int x = index % mCols; if (mLeftHanded) x = mCols - x - 1; float top = mRowHeight * y; float bottom = top + mRowHeight; float left = mColWidth * x; float right = left + mColWidth; return new RectF(left, top, right, bottom); } private RectF getOverlayButtonBounds() { return getButtonBounds(mOverlayButtonIndex); } @Override protected void onDraw(Canvas canvas) { RectF bounds = getOverlayButtonBounds(); canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); mTool.draw(canvas); if (mShowOverlay) canvas.drawARGB(0xAA, 0xFF, 0xFF, 0xFF); mPaint.setColor(0xEEFFFFAA); canvas.drawRect(bounds, mPaint); if (mShowOverlay || (mPermanentGrid && mUI == UI.CHORD)) { mPaint.setColor(0x44666666); for (int i = 0; i < mRows; i++) { float top = i * mRowHeight; canvas.drawLine(0, top, mColWidth * mCols, top, mPaint); } for (int i = 0; i < mCols; i++) { float left = i * mColWidth; canvas.drawLine(left, 0, left, mRowHeight * mRows, mPaint); } } if (mShowOverlay) { mPaint.setColor(0xFF000000); for (int y = 0; y < mRows; y++) { for (int x = 0; x < mCols; x++) { int realX = x; if (mLeftHanded) realX = mCols - x - 1; int i = y * mCols + realX; if (mSelections[i] != null) { String name = mSelections[i].name; int heightAdj = getTextHeight(name, mPaint) / 2; canvas.drawText(name, (x + 0.5f) * mColWidth, (y + 0.5f) * mRowHeight + heightAdj, mPaint); } } } } else if (!mPermanentGrid) { mPaint.setColor(0x44666666); canvas.drawLine(bounds.left, bounds.top, bounds.right, bounds.top, mPaint); if (mLeftHanded) canvas.drawLine(bounds.left, bounds.top, bounds.left, bounds.bottom, mPaint); else canvas.drawLine(bounds.right, bounds.top, bounds.right, bounds.bottom, mPaint); } if (mUI == UI.CHORD) { synchronized (mFlashTimes) { for (int i = 0; i < mFlashTimes.size(); i++) { int selectionNum = mFlashTimes.keyAt(i); Selection selection = mSelections[selectionNum]; if (selection != null) { RectF buttonBounds = getButtonBounds(selectionNum); mPaint.setColor(0xBBF5F5F5); canvas.drawRect(buttonBounds, mPaint); mPaint.setColor(0x44666666); mPaint.setStyle(Style.STROKE); canvas.drawRect(buttonBounds, mPaint); mPaint.setStyle(Style.FILL); mPaint.setColor(0xFF000000); String name = selection.name; int heightAdj = getTextHeight(name, mPaint) / 2; canvas.drawText(name, buttonBounds.left + 0.5f * mColWidth, buttonBounds.top + 0.5f * mRowHeight + heightAdj, mPaint); } } } } mPaint.setColor(0xFF666666); canvas.drawText(mThicknessName, bounds.left + mColWidth / 2, bounds.top + mRowHeight / 2 + getTextHeight(mThicknessName, mPaint) / 2 - 30, mPaint); canvas.drawText(mColorName, bounds.left + mColWidth / 2, bounds.top + mRowHeight / 2 + getTextHeight(mColorName, mPaint) / 2, mPaint); canvas.drawText(mToolName, bounds.left + mColWidth / 2, bounds.top + mRowHeight / 2 + getTextHeight(mToolName, mPaint) / 2 + 30, mPaint); if (mShowGestureMenu) { PointF origin = mOrigins.get(mGestureFinger); Gesture gesture = mGestureDetector.recognize(); Gesture mainGesture = Gesture.UNKNOWN; Gesture subGesture = Gesture.UNKNOWN; if (gesture != Gesture.UNKNOWN) { switch (gesture) { case UP: mainGesture = Gesture.UP; subGesture = Gesture.UP; break; case UP_LEFT: mainGesture = Gesture.UP; subGesture = Gesture.LEFT; break; case UP_RIGHT: mainGesture = Gesture.UP; subGesture = Gesture.RIGHT; break; case UP_DOWN: mainGesture = Gesture.UP; subGesture = Gesture.DOWN; break; case LEFT: mainGesture = Gesture.LEFT; subGesture = Gesture.LEFT; break; case LEFT_RIGHT: mainGesture = Gesture.LEFT; subGesture = Gesture.RIGHT; break; case LEFT_UP: mainGesture = Gesture.LEFT; subGesture = Gesture.UP; break; case LEFT_DOWN: mainGesture = Gesture.LEFT; subGesture = Gesture.DOWN; break; case RIGHT: mainGesture = Gesture.RIGHT; subGesture = Gesture.RIGHT; break; case RIGHT_LEFT: mainGesture = Gesture.RIGHT; subGesture = Gesture.LEFT; break; case RIGHT_UP: mainGesture = Gesture.RIGHT; subGesture = Gesture.UP; break; case RIGHT_DOWN: mainGesture = Gesture.RIGHT; subGesture = Gesture.DOWN; break; case DOWN: mainGesture = Gesture.DOWN; subGesture = Gesture.DOWN; break; case DOWN_LEFT: mainGesture = Gesture.DOWN; subGesture = Gesture.LEFT; break; case DOWN_RIGHT: mainGesture = Gesture.DOWN; subGesture = Gesture.RIGHT; break; case DOWN_UP: mainGesture = Gesture.DOWN; subGesture = Gesture.UP; break; default: break; } } if (isInCircle(mGestureFingerPos, origin.x, origin.y - mGestureButtonDist, mGestureButtonSize)) { mActiveCategoryOrigin.x = origin.x; mActiveCategoryOrigin.y = origin.y - mGestureButtonDist; mActiveCategory = Gesture.UP; } else if (isInCircle(mGestureFingerPos, origin.x - mGestureButtonDist, origin.y, mGestureButtonSize)) { mActiveCategoryOrigin.x = origin.x - mGestureButtonDist; mActiveCategoryOrigin.y = origin.y; mActiveCategory = Gesture.LEFT; } else if (isInCircle(mGestureFingerPos, origin.x + mGestureButtonDist, origin.y, mGestureButtonSize)) { mActiveCategoryOrigin.x = origin.x + mGestureButtonDist; mActiveCategoryOrigin.y = origin.y; mActiveCategory = Gesture.RIGHT; } else if (isInCircle(mGestureFingerPos, origin.x, origin.y + mGestureButtonDist, mGestureButtonSize)) { mActiveCategoryOrigin.x = origin.x; mActiveCategoryOrigin.y = origin.y + mGestureButtonDist; mActiveCategory = Gesture.DOWN; } boolean greyout = mActiveCategory != Gesture.UNKNOWN; mPaint.setTextSize(22); int size = mGestureButtonSize; drawGestureButton(canvas, "Tools", origin.x, origin.y - mGestureButtonDist, size, mPaint, mActiveCategory == Gesture.UP, greyout); drawGestureButton(canvas, "Colors", origin.x - mGestureButtonDist, origin.y, size, mPaint, mActiveCategory == Gesture.LEFT, greyout); drawGestureButton(canvas, "Colors", origin.x + mGestureButtonDist, origin.y, size, mPaint, mActiveCategory == Gesture.RIGHT, greyout); drawGestureButton(canvas, "Widths", origin.x, origin.y + mGestureButtonDist, size, mPaint, mActiveCategory == Gesture.DOWN, greyout); mPaint.setTextSize(18); int subSize = (int)(size * 0.70); int subDist = size + subSize; float subOriginX = mActiveCategoryOrigin.x; float subOriginY = mActiveCategoryOrigin.y; if (isInCircle(mGestureFingerPos, subOriginX, subOriginY - subDist, subSize)) { mSubSelection = Gesture.UP; } else if (isInCircle(mGestureFingerPos, subOriginX - subDist, subOriginY, subSize)) { mSubSelection = Gesture.LEFT; } else if (isInCircle(mGestureFingerPos, subOriginX + subDist, subOriginY, subSize)) { mSubSelection = Gesture.RIGHT; } else if (isInCircle(mGestureFingerPos, subOriginX, subOriginY + subDist, subSize)) { mSubSelection = Gesture.DOWN; } else if (mainGesture == mActiveCategory) { mSubSelection = subGesture; } else { mSubSelection = Gesture.UNKNOWN; } switch (mActiveCategory) { case UP: drawGestureButton(canvas, "Paintbrush", subOriginX, subOriginY - subDist, subSize, mPaint, mSubSelection == Gesture.UP, false); drawGestureButton(canvas, "Rectangle", subOriginX - subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.LEFT, false); drawGestureButton(canvas, "Line", subOriginX + subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.RIGHT, false); drawGestureButton(canvas, "Circle", subOriginX, subOriginY + subDist, subSize, mPaint, mSubSelection == Gesture.DOWN, false); break; case LEFT: drawGestureButton(canvas, "Red", subOriginX, subOriginY - subDist, subSize, mPaint, mSubSelection == Gesture.UP, false); drawGestureButton(canvas, "Black", subOriginX - subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.LEFT, false); drawGestureButton(canvas, "Green", subOriginX + subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.RIGHT, false); drawGestureButton(canvas, "Blue", subOriginX, subOriginY + subDist, subSize, mPaint, mSubSelection == Gesture.DOWN, false); break; case RIGHT: drawGestureButton(canvas, "Magenta", subOriginX, subOriginY - subDist, subSize, mPaint, mSubSelection == Gesture.UP, false); drawGestureButton(canvas, "Cyan", subOriginX - subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.LEFT, false); drawGestureButton(canvas, "White", subOriginX + subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.RIGHT, false); drawGestureButton(canvas, "Yellow", subOriginX, subOriginY + subDist, subSize, mPaint, mSubSelection == Gesture.DOWN, false); break; case DOWN: drawGestureButton(canvas, "Thin", subOriginX, subOriginY - subDist, subSize, mPaint, mSubSelection == Gesture.UP, false); drawGestureButton(canvas, "Fine", subOriginX - subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.LEFT, false); drawGestureButton(canvas, "Wide", subOriginX + subDist, subOriginY, subSize, mPaint, mSubSelection == Gesture.RIGHT, false); drawGestureButton(canvas, "Normal", subOriginX, subOriginY + subDist, subSize, mPaint, mSubSelection == Gesture.DOWN, false); break; default: break; } mPaint.setTextSize(26); } } private boolean isInCircle(PointF point, float cx, float cy, float radius) { float dx = point.x - cx; float dy = point.y - cy; double distance = Math.sqrt(dx*dx + dy*dy); return distance < radius; } private void drawGestureButton(Canvas canvas, String text, float x, float y, int size, Paint paint, boolean highlight, boolean greyout) { paint.getTextBounds(text, 0, text.length(), mTextBounds); if (highlight) mPaint.setColor(0xFFAAAAAA); else if (greyout) mPaint.setColor(0xFFDDDDDD); else mPaint.setColor(0xFFCCCCCC); canvas.drawCircle(x, y, size, paint); if (greyout && !highlight) { mPaint.setColor(0xEE777777); } else { mPaint.setColor(0xEE000000); mPaint.setShadowLayer(2, 1, 1, 0x33000000); } canvas.drawText(text, x, y + mTextBounds.height() / 2, mPaint); mPaint.setShadowLayer(0, 0, 0, 0); } private int getTextHeight(String text, Paint paint) { mPaint.getTextBounds(text, 0, text.length(), mTextBounds); return mTextBounds.height(); } @Override public boolean onTouchEvent(MotionEvent event) { int index = event.getActionIndex(); float x = event.getX(index); float y = event.getY(index); int id = event.getPointerId(index); long now = System.nanoTime(); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: mLog.event("Touch down: " + id); mFingers.add(id); if (mUI == UI.CHORD) { if (event.getPointerCount() == 1) mCheckOverlay = true; if (getOverlayButtonBounds().contains(x, y)) { mFingerInside = id; mPressedInsideTime = now; mIgnoredFingers.add(mFingerInside); } else { int col = (int) (x / mColWidth); int row = (int) (y / mRowHeight); if (mLeftHanded) col = mCols - col - 1; mSelected = row * mCols + col; mRecentTouches.put(mSelected, now); } for (int i = 0; i < mRecentTouches.size(); i++) { int selection = mRecentTouches.keyAt(i); long time = mRecentTouches.valueAt(i); if ((now - time < mChordDelay && now - mPressedInsideTime < mChordDelay) || mShowOverlay) { changeSelection(selection); mCheckOverlay = false; mRecentTouches.removeAt(i); i--; } else if (now - time > mChordDelay) { mRecentTouches.removeAt(i); i--; } } } else if (mUI == UI.GESTURE) { if (mInstantMenu && !getOverlayButtonBounds().contains(x, y) && !mShowGestureMenu) { mInstantMenu = false; mGestureFinger = id; mGestureMenuTime = now; mShowGestureMenu = true; mIgnoredFingers.add(id); mGestureFingerPos = new PointF(x, y); mOrigins.put(id, mGestureFingerPos); mGestureDetector.clear(); } else if (event.getPointerCount() == 1) { mGestureDetector.clear(); if (getOverlayButtonBounds().contains(x, y)) { mIgnoredFingers.add(id); mInstantMenu = true; } else { mPossibleGestureFinger = id; mGestureFingerPos = new PointF(x, y); mPossibleGestureFingerTime = now; } } if (mShowGestureMenu) mIgnoredFingers.add(id); } if (!mShowOverlay && !mShowGestureMenu) { mOrigins.put(id, new PointF(x, y)); mTool.touchStart(id, x, y); } break; case MotionEvent.ACTION_MOVE: if (mShowOverlay) break; int count = event.getPointerCount(); for (int i = 0; i < count; i++) { int fingerId = event.getPointerId(i); + float x2 = event.getX(i); + float y2 = event.getY(i); if (fingerId == mGestureFinger) { - mGestureFingerPos = new PointF(x, y); - mGestureDetector.addPoint(x, y); + mGestureFingerPos = new PointF(x2, y2); + mGestureDetector.addPoint(x2, y2); } if(mIgnoredFingers.contains(fingerId)) continue; - float x2 = event.getX(i); - float y2 = event.getY(i); PointF origin = mOrigins.get(fingerId); if (origin != null) { float dx = origin.x - x2; float dy = origin.y - y2; double dist = Math.sqrt(dx*dx + dy*dy); if (dist > mThreshold) { mOrigins.delete(fingerId); origin = null; } } if (origin == null) { mTool.touchMove(fingerId, x2, y2); if (!mChanged) { mChanged = true; mNextUndo = mBitmap.copy(mBitmap.getConfig(), true); } } } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mLog.event("Touch up: " + id); mOrigins.delete(id); mFingers.remove(id); if (id == mFingerInside) mFingerInside = -1; if (id == mPossibleGestureFinger) mPossibleGestureFinger = -1; boolean draw = true; if (id == mGestureFinger) { mGestureFinger = -1; mShowGestureMenu = false; boolean gestureSelection; Gesture gesture = Gesture.UNKNOWN; if (mActiveCategory != Gesture.UNKNOWN && mSubSelection != Gesture.UNKNOWN) { gestureSelection = false; switch (mActiveCategory) { case UP: switch (mSubSelection) { case UP: gesture = Gesture.UP; break; case LEFT: gesture = Gesture.UP_LEFT; break; case RIGHT: gesture = Gesture.UP_RIGHT; break; case DOWN: gesture = Gesture.UP_DOWN; break; default: break; } break; case LEFT: switch (mSubSelection) { case UP: gesture = Gesture.LEFT_UP; break; case LEFT: gesture = Gesture.LEFT; break; case RIGHT: gesture = Gesture.LEFT_RIGHT; break; case DOWN: gesture = Gesture.LEFT_DOWN; break; default: break; } break; case RIGHT: switch (mSubSelection) { case UP: gesture = Gesture.RIGHT_UP; break; case LEFT: gesture = Gesture.RIGHT_LEFT; break; case RIGHT: gesture = Gesture.RIGHT; break; case DOWN: gesture = Gesture.RIGHT_DOWN; break; default: break; } break; case DOWN: switch (mSubSelection) { case UP: gesture = Gesture.DOWN_UP; break; case LEFT: gesture = Gesture.DOWN_LEFT; break; case RIGHT: gesture = Gesture.DOWN_RIGHT; break; case DOWN: gesture = Gesture.DOWN; break; default: break; } break; default: break; } } else { gestureSelection = true; gesture = mGestureDetector.recognize(); } long menuOpenNs = now - mGestureMenuTime; long menuOpenMs = menuOpenNs / 1000000; if (mStudyMode) mStudyCtl.addUITime(menuOpenNs); if (mGestureSelections.containsKey(gesture)) { if (gestureSelection) mLog.event("Menu closed with gesture selection: " + menuOpenMs + " ms"); else mLog.event("Menu closed with exact selection: " + menuOpenMs + " ms"); changeSelection(mGestureSelections.get(gesture)); } else { mLog.event("Menu closed without selection: " + menuOpenMs + " ms"); } mActiveCategory = Gesture.UNKNOWN; draw = false; } if (mIgnoredFingers.contains(id)) { mIgnoredFingers.remove(id); draw = false; } if (mShowOverlay) { if (event.getPointerCount() == 1) { mShowOverlay = false; long duration = now - mOverlayStart; mLog.event("Overlay hidden after " + duration / 1000000 + " ms"); if (mStudyMode) { if (mOverlayStart > mStudyCtl.getTrialStart()) mStudyCtl.addUITime(duration); else mStudyCtl.addUITime(now - mStudyCtl.getTrialStart()); } } } else if (draw) { if (event.getPointerCount() == 1 && mChanged) { mStudyCtl.incrementTimesPainted(); mUndo = mNextUndo; } mTool.touchStop(id, x, y, new Canvas(mBitmap)); } if (event.getPointerCount() == 1) mChanged = false; break; } invalidate(); return true; } private void changeSelection(int selected) { changeSelection(selected, true); } private void changeSelection(int selected, boolean fromUser) { if (mTool != null) mTool.clearFingers(); for (int id : mFingers) { mIgnoredFingers.add(id); } mOrigins.clear(); Selection selection = mSelections[selected]; if (selection == null) return; if (fromUser) { synchronized (mFlashTimes) { mFlashTimes.put(selected, System.nanoTime()); } invalidate(); } switch (selection.type) { case TOOL: if (fromUser) mLog.event("Tool selected: " + selection.name); mTool = (Tool) selection.object; mToolName = selection.name; break; case COLOR: if (fromUser) mLog.event("Color selected: " + selection.name); mColor = (Integer) selection.object; mColorName = selection.name; break; case THICKNESS: if (fromUser) mLog.event("Thickness selected: " + selection.name); mThickness = (Integer) selection.object; mThicknessName = selection.name; break; case ACTION: if (fromUser) mLog.event("Action selected: " + selection.name); switch ((Action) selection.object) { case SAVE: break; case CLEAR: mUndo = mBitmap.copy(mBitmap.getConfig(), true); Canvas canvas = new Canvas(mBitmap); canvas.drawRGB(0xFF, 0xFF, 0xFF); break; case UNDO: if (mUndo != null) { Bitmap temp = mBitmap; mBitmap = mUndo; mUndo = temp; } break; } break; } if (fromUser && mStudyMode) { boolean gesture = mUI == UI.GESTURE; boolean wasLastTarget = mStudyCtl.isOnLastTarget(); boolean wasLastTrial = mStudyCtl.isOnLastTrial(); if (mUI == UI.CHORD && mShowOverlay && wasLastTarget) { long now = System.nanoTime(); if (mOverlayStart > mStudyCtl.getTrialStart()) mStudyCtl.addUITime(now - mOverlayStart); else mStudyCtl.addUITime(now - mStudyCtl.getTrialStart()); } boolean correctSelection = mStudyCtl.handleSelected(selection.name, gesture); if (mStudyCtl.isFinished()) { mMainActivity.getActionBar().setIcon(R.drawable.trans); mMainActivity.setTitle(mStudyCtl.getPrompt()); if (wasLastTarget) alert("You are finished!\n\nThank you for participating!"); } else if (correctSelection && wasLastTarget) { // Clear screen and undo history Canvas canvas = new Canvas(mBitmap); canvas.drawRGB(0xFF, 0xFF, 0xFF); mUndo = mBitmap.copy(mBitmap.getConfig(), true); // Forcibly unpost the command map overlay mShowOverlay = false; long duration = System.nanoTime() - mOverlayStart; mLog.event("Overlay automatically hidden at end of trial after " + duration / 1000000 + " ms"); mMainActivity.getActionBar().setIcon(R.drawable.check); if (wasLastTrial) { mMainActivity.setTitle(mStudyCtl.getPrompt()); mStudyCtl.nextTrial(); pauseStudy("Press OK when you are ready to continue."); } else { Runnable waitStep = new Runnable() { @Override public void run() { mStudyCtl.waitStep(true); mMainActivity.setTitle(mStudyCtl.getPrompt()); } }; waitStep.run(); mHandler.postDelayed(waitStep, mTrialDelay / 4); mHandler.postDelayed(waitStep, mTrialDelay / 2); mHandler.postDelayed(waitStep, mTrialDelay * 3 / 4); mHandler.postDelayed(waitStep, mTrialDelay); mHandler.postDelayed(new Runnable() { @Override public void run() { mMainActivity.getActionBar().setIcon(R.drawable.trans); } }, mTrialDelay); } } else if (!correctSelection) { mMainActivity.getActionBar().setIcon(R.drawable.x); } else { mMainActivity.getActionBar().setIcon(R.drawable.trans); mMainActivity.setTitle(mStudyCtl.getPrompt()); } } } }
false
true
public boolean onTouchEvent(MotionEvent event) { int index = event.getActionIndex(); float x = event.getX(index); float y = event.getY(index); int id = event.getPointerId(index); long now = System.nanoTime(); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: mLog.event("Touch down: " + id); mFingers.add(id); if (mUI == UI.CHORD) { if (event.getPointerCount() == 1) mCheckOverlay = true; if (getOverlayButtonBounds().contains(x, y)) { mFingerInside = id; mPressedInsideTime = now; mIgnoredFingers.add(mFingerInside); } else { int col = (int) (x / mColWidth); int row = (int) (y / mRowHeight); if (mLeftHanded) col = mCols - col - 1; mSelected = row * mCols + col; mRecentTouches.put(mSelected, now); } for (int i = 0; i < mRecentTouches.size(); i++) { int selection = mRecentTouches.keyAt(i); long time = mRecentTouches.valueAt(i); if ((now - time < mChordDelay && now - mPressedInsideTime < mChordDelay) || mShowOverlay) { changeSelection(selection); mCheckOverlay = false; mRecentTouches.removeAt(i); i--; } else if (now - time > mChordDelay) { mRecentTouches.removeAt(i); i--; } } } else if (mUI == UI.GESTURE) { if (mInstantMenu && !getOverlayButtonBounds().contains(x, y) && !mShowGestureMenu) { mInstantMenu = false; mGestureFinger = id; mGestureMenuTime = now; mShowGestureMenu = true; mIgnoredFingers.add(id); mGestureFingerPos = new PointF(x, y); mOrigins.put(id, mGestureFingerPos); mGestureDetector.clear(); } else if (event.getPointerCount() == 1) { mGestureDetector.clear(); if (getOverlayButtonBounds().contains(x, y)) { mIgnoredFingers.add(id); mInstantMenu = true; } else { mPossibleGestureFinger = id; mGestureFingerPos = new PointF(x, y); mPossibleGestureFingerTime = now; } } if (mShowGestureMenu) mIgnoredFingers.add(id); } if (!mShowOverlay && !mShowGestureMenu) { mOrigins.put(id, new PointF(x, y)); mTool.touchStart(id, x, y); } break; case MotionEvent.ACTION_MOVE: if (mShowOverlay) break; int count = event.getPointerCount(); for (int i = 0; i < count; i++) { int fingerId = event.getPointerId(i); if (fingerId == mGestureFinger) { mGestureFingerPos = new PointF(x, y); mGestureDetector.addPoint(x, y); } if(mIgnoredFingers.contains(fingerId)) continue; float x2 = event.getX(i); float y2 = event.getY(i); PointF origin = mOrigins.get(fingerId); if (origin != null) { float dx = origin.x - x2; float dy = origin.y - y2; double dist = Math.sqrt(dx*dx + dy*dy); if (dist > mThreshold) { mOrigins.delete(fingerId); origin = null; } } if (origin == null) { mTool.touchMove(fingerId, x2, y2); if (!mChanged) { mChanged = true; mNextUndo = mBitmap.copy(mBitmap.getConfig(), true); } } } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mLog.event("Touch up: " + id); mOrigins.delete(id); mFingers.remove(id); if (id == mFingerInside) mFingerInside = -1; if (id == mPossibleGestureFinger) mPossibleGestureFinger = -1; boolean draw = true; if (id == mGestureFinger) { mGestureFinger = -1; mShowGestureMenu = false; boolean gestureSelection; Gesture gesture = Gesture.UNKNOWN; if (mActiveCategory != Gesture.UNKNOWN && mSubSelection != Gesture.UNKNOWN) { gestureSelection = false; switch (mActiveCategory) { case UP: switch (mSubSelection) { case UP: gesture = Gesture.UP; break; case LEFT: gesture = Gesture.UP_LEFT; break; case RIGHT: gesture = Gesture.UP_RIGHT; break; case DOWN: gesture = Gesture.UP_DOWN; break; default: break; } break; case LEFT: switch (mSubSelection) { case UP: gesture = Gesture.LEFT_UP; break; case LEFT: gesture = Gesture.LEFT; break; case RIGHT: gesture = Gesture.LEFT_RIGHT; break; case DOWN: gesture = Gesture.LEFT_DOWN; break; default: break; } break; case RIGHT: switch (mSubSelection) { case UP: gesture = Gesture.RIGHT_UP; break; case LEFT: gesture = Gesture.RIGHT_LEFT; break; case RIGHT: gesture = Gesture.RIGHT; break; case DOWN: gesture = Gesture.RIGHT_DOWN; break; default: break; } break; case DOWN: switch (mSubSelection) { case UP: gesture = Gesture.DOWN_UP; break; case LEFT: gesture = Gesture.DOWN_LEFT; break; case RIGHT: gesture = Gesture.DOWN_RIGHT; break; case DOWN: gesture = Gesture.DOWN; break; default: break; } break; default: break; } } else { gestureSelection = true; gesture = mGestureDetector.recognize(); } long menuOpenNs = now - mGestureMenuTime; long menuOpenMs = menuOpenNs / 1000000; if (mStudyMode) mStudyCtl.addUITime(menuOpenNs); if (mGestureSelections.containsKey(gesture)) { if (gestureSelection) mLog.event("Menu closed with gesture selection: " + menuOpenMs + " ms"); else mLog.event("Menu closed with exact selection: " + menuOpenMs + " ms"); changeSelection(mGestureSelections.get(gesture)); } else { mLog.event("Menu closed without selection: " + menuOpenMs + " ms"); } mActiveCategory = Gesture.UNKNOWN; draw = false; } if (mIgnoredFingers.contains(id)) { mIgnoredFingers.remove(id); draw = false; } if (mShowOverlay) { if (event.getPointerCount() == 1) { mShowOverlay = false; long duration = now - mOverlayStart; mLog.event("Overlay hidden after " + duration / 1000000 + " ms"); if (mStudyMode) { if (mOverlayStart > mStudyCtl.getTrialStart()) mStudyCtl.addUITime(duration); else mStudyCtl.addUITime(now - mStudyCtl.getTrialStart()); } } } else if (draw) { if (event.getPointerCount() == 1 && mChanged) { mStudyCtl.incrementTimesPainted(); mUndo = mNextUndo; } mTool.touchStop(id, x, y, new Canvas(mBitmap)); } if (event.getPointerCount() == 1) mChanged = false; break; } invalidate(); return true; }
public boolean onTouchEvent(MotionEvent event) { int index = event.getActionIndex(); float x = event.getX(index); float y = event.getY(index); int id = event.getPointerId(index); long now = System.nanoTime(); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: mLog.event("Touch down: " + id); mFingers.add(id); if (mUI == UI.CHORD) { if (event.getPointerCount() == 1) mCheckOverlay = true; if (getOverlayButtonBounds().contains(x, y)) { mFingerInside = id; mPressedInsideTime = now; mIgnoredFingers.add(mFingerInside); } else { int col = (int) (x / mColWidth); int row = (int) (y / mRowHeight); if (mLeftHanded) col = mCols - col - 1; mSelected = row * mCols + col; mRecentTouches.put(mSelected, now); } for (int i = 0; i < mRecentTouches.size(); i++) { int selection = mRecentTouches.keyAt(i); long time = mRecentTouches.valueAt(i); if ((now - time < mChordDelay && now - mPressedInsideTime < mChordDelay) || mShowOverlay) { changeSelection(selection); mCheckOverlay = false; mRecentTouches.removeAt(i); i--; } else if (now - time > mChordDelay) { mRecentTouches.removeAt(i); i--; } } } else if (mUI == UI.GESTURE) { if (mInstantMenu && !getOverlayButtonBounds().contains(x, y) && !mShowGestureMenu) { mInstantMenu = false; mGestureFinger = id; mGestureMenuTime = now; mShowGestureMenu = true; mIgnoredFingers.add(id); mGestureFingerPos = new PointF(x, y); mOrigins.put(id, mGestureFingerPos); mGestureDetector.clear(); } else if (event.getPointerCount() == 1) { mGestureDetector.clear(); if (getOverlayButtonBounds().contains(x, y)) { mIgnoredFingers.add(id); mInstantMenu = true; } else { mPossibleGestureFinger = id; mGestureFingerPos = new PointF(x, y); mPossibleGestureFingerTime = now; } } if (mShowGestureMenu) mIgnoredFingers.add(id); } if (!mShowOverlay && !mShowGestureMenu) { mOrigins.put(id, new PointF(x, y)); mTool.touchStart(id, x, y); } break; case MotionEvent.ACTION_MOVE: if (mShowOverlay) break; int count = event.getPointerCount(); for (int i = 0; i < count; i++) { int fingerId = event.getPointerId(i); float x2 = event.getX(i); float y2 = event.getY(i); if (fingerId == mGestureFinger) { mGestureFingerPos = new PointF(x2, y2); mGestureDetector.addPoint(x2, y2); } if(mIgnoredFingers.contains(fingerId)) continue; PointF origin = mOrigins.get(fingerId); if (origin != null) { float dx = origin.x - x2; float dy = origin.y - y2; double dist = Math.sqrt(dx*dx + dy*dy); if (dist > mThreshold) { mOrigins.delete(fingerId); origin = null; } } if (origin == null) { mTool.touchMove(fingerId, x2, y2); if (!mChanged) { mChanged = true; mNextUndo = mBitmap.copy(mBitmap.getConfig(), true); } } } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: mLog.event("Touch up: " + id); mOrigins.delete(id); mFingers.remove(id); if (id == mFingerInside) mFingerInside = -1; if (id == mPossibleGestureFinger) mPossibleGestureFinger = -1; boolean draw = true; if (id == mGestureFinger) { mGestureFinger = -1; mShowGestureMenu = false; boolean gestureSelection; Gesture gesture = Gesture.UNKNOWN; if (mActiveCategory != Gesture.UNKNOWN && mSubSelection != Gesture.UNKNOWN) { gestureSelection = false; switch (mActiveCategory) { case UP: switch (mSubSelection) { case UP: gesture = Gesture.UP; break; case LEFT: gesture = Gesture.UP_LEFT; break; case RIGHT: gesture = Gesture.UP_RIGHT; break; case DOWN: gesture = Gesture.UP_DOWN; break; default: break; } break; case LEFT: switch (mSubSelection) { case UP: gesture = Gesture.LEFT_UP; break; case LEFT: gesture = Gesture.LEFT; break; case RIGHT: gesture = Gesture.LEFT_RIGHT; break; case DOWN: gesture = Gesture.LEFT_DOWN; break; default: break; } break; case RIGHT: switch (mSubSelection) { case UP: gesture = Gesture.RIGHT_UP; break; case LEFT: gesture = Gesture.RIGHT_LEFT; break; case RIGHT: gesture = Gesture.RIGHT; break; case DOWN: gesture = Gesture.RIGHT_DOWN; break; default: break; } break; case DOWN: switch (mSubSelection) { case UP: gesture = Gesture.DOWN_UP; break; case LEFT: gesture = Gesture.DOWN_LEFT; break; case RIGHT: gesture = Gesture.DOWN_RIGHT; break; case DOWN: gesture = Gesture.DOWN; break; default: break; } break; default: break; } } else { gestureSelection = true; gesture = mGestureDetector.recognize(); } long menuOpenNs = now - mGestureMenuTime; long menuOpenMs = menuOpenNs / 1000000; if (mStudyMode) mStudyCtl.addUITime(menuOpenNs); if (mGestureSelections.containsKey(gesture)) { if (gestureSelection) mLog.event("Menu closed with gesture selection: " + menuOpenMs + " ms"); else mLog.event("Menu closed with exact selection: " + menuOpenMs + " ms"); changeSelection(mGestureSelections.get(gesture)); } else { mLog.event("Menu closed without selection: " + menuOpenMs + " ms"); } mActiveCategory = Gesture.UNKNOWN; draw = false; } if (mIgnoredFingers.contains(id)) { mIgnoredFingers.remove(id); draw = false; } if (mShowOverlay) { if (event.getPointerCount() == 1) { mShowOverlay = false; long duration = now - mOverlayStart; mLog.event("Overlay hidden after " + duration / 1000000 + " ms"); if (mStudyMode) { if (mOverlayStart > mStudyCtl.getTrialStart()) mStudyCtl.addUITime(duration); else mStudyCtl.addUITime(now - mStudyCtl.getTrialStart()); } } } else if (draw) { if (event.getPointerCount() == 1 && mChanged) { mStudyCtl.incrementTimesPainted(); mUndo = mNextUndo; } mTool.touchStop(id, x, y, new Canvas(mBitmap)); } if (event.getPointerCount() == 1) mChanged = false; break; } invalidate(); return true; }
diff --git a/src/java/com/idega/block/finance/presentation/AccountTariffer.java b/src/java/com/idega/block/finance/presentation/AccountTariffer.java index d31cc13..bc8ba6a 100644 --- a/src/java/com/idega/block/finance/presentation/AccountTariffer.java +++ b/src/java/com/idega/block/finance/presentation/AccountTariffer.java @@ -1,352 +1,352 @@ package com.idega.block.finance.presentation; import com.idega.block.finance.business.AccountBusiness; import com.idega.block.finance.business.AssessmentBusiness; import com.idega.block.finance.business.FinanceFinder; import com.idega.block.finance.business.FinanceHandler; import com.idega.block.finance.data.AccountKey; import com.idega.block.finance.data.FinanceAccount; import com.idega.block.finance.data.Tariff; import com.idega.block.finance.data.TariffGroup; import com.idega.business.IBOLookup; import com.idega.presentation.IWContext; import com.idega.presentation.PresentationObject; import com.idega.presentation.Table; import com.idega.presentation.text.Link; import com.idega.presentation.ui.CheckBox; import com.idega.presentation.ui.DataTable; import com.idega.presentation.ui.DateInput; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextInput; import com.idega.user.business.UserBusiness; import com.idega.user.data.User; import com.idega.util.IWTimestamp; import java.text.DecimalFormat; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Title: * Description: * Copyright: Copyright (c) 2001 * Company: * @author <a href="mailto:[email protected]">[email protected] * @version 1.0 */ public class AccountTariffer extends Finance { private static String prmGroup = "at_grp"; private FinanceAccount account; private int iAccountId = -1; private int searchPage = -1,viewPage = -1; private AccountBusiness accBuiz; private String prmNewTariff = "fin_ati_nwta"; private String prmTariffs = "fin_trf_ids"; private String prmTariffName = "fin_trf_nme"; private String prmTariffInfo = "fin_trf_ifo"; private String prmAccountKey = "fin_acc_kid"; private String prmTariffGroupId = "fin_tgr_id"; private String prmPayDate = "fin_pay_dte"; private String prmAmount = "fin_trf_amt"; private String prmDiscount = "fin_trf_dsc"; private String prmConfirm = "fin_confirm"; private String prmSaveTariff = "fin_sve_trf"; int iGroupId = -1; public AccountTariffer() { } protected void control(IWContext iwc) throws java.rmi.RemoteException{ if(isAdmin){ accBuiz = (AccountBusiness) IBOLookup.getServiceInstance(iwc,AccountBusiness.class); - iCategoryId = Finance.parseCategoryId(iwc); +// iCategoryId = Finance.parseCategoryId(iwc); List groups = FinanceFinder.getInstance().listOfTariffGroups(iCategoryId); TariffGroup group = null; if(iwc.isParameterSet(prmGroup)) iGroupId = Integer.parseInt(iwc.getParameter(prmGroup)); if(iGroupId > 0 ){ group = FinanceFinder.getInstance().getTariffGroup(iGroupId); } else if(groups !=null){ //group = (TariffGroup) groups.get(0); //iGroupId = group.getID(); } if(iwc.isParameterSet(prmAccountId)){ iAccountId = Integer.parseInt(iwc.getParameter(prmAccountId)); if(iAccountId>0){ parse(iwc); account = FinanceFinder.getInstance().getFinanceAccount(iAccountId); } } Table T = new Table(1,6); T.setCellpadding(0); T.setCellspacing(0); T.add(textFormat.format(iwrb.getLocalizedString("account_tariffer","Account tariffer"),textFormat.HEADER),1,1); T.setHeight(2,"15"); T.add(getAccountInfo(iwc),1,3); T.add(getGroupLinks(iCategoryId,iGroupId,groups),1,4); if(group!=null) T.add(getTariffTable(group),1,5); else T.add(getNewTariffTable(iwc),1,5); T.add(getTariffPropertiesTable(),1,6); //T.setWidth("450"); Form myForm = new Form(); myForm.add(new HiddenInput(prmCategoryId,String.valueOf(iCategoryId))); myForm.add(new HiddenInput(prmGroup,String.valueOf(iGroupId))); myForm.add(T); add(myForm); } } private void parse(IWContext iwc)throws java.rmi.RemoteException{ if(iwc.isParameterSet(prmConfirm)&& iwc.getParameter(prmConfirm).equals("true")){ System.err.println("confirmation"); String paydate = iwc.getParameter(prmPayDate); IWTimestamp Pd = new IWTimestamp(paydate); String SDiscount = iwc.getParameter(prmDiscount); int discount = SDiscount!=null && !SDiscount.equals("")?Integer.parseInt(SDiscount):-1; AssessmentBusiness assBuiz = (AssessmentBusiness) IBOLookup.getServiceInstance(iwc,AssessmentBusiness.class); if(iwc.isParameterSet(prmTariffs)){ System.err.println("using tariffs"); String[] tariff_ids = iwc.getParameterValues(prmTariffs); assBuiz.assessTariffsToAccount(tariff_ids,iAccountId,Pd.getSQLDate(),discount,iGroupId,iCategoryId); } else{ int keyId = iwc.isParameterSet(prmAccountKey)?Integer.parseInt(iwc.getParameter(prmAccountKey)):-1;; int price = iwc.isParameterSet(prmAmount)?Integer.parseInt(iwc.getParameter(prmAmount)):0; if(keyId>0 && price !=0){ int TariffGroupId = iwc.isParameterSet(prmTariffGroupId)?Integer.parseInt(iwc.getParameter(prmTariffGroupId)):-1; System.err.println("using new tariff"); String name = iwc.getParameter(prmTariffName); String info = iwc.getParameter(prmTariffInfo); boolean saveTariff = iwc.isParameterSet(prmSaveTariff); assBuiz.assessTariffsToAccount(price,name,info, iAccountId , keyId,Pd.getSQLDate(),TariffGroupId,iCategoryId,saveTariff); } } } } private PresentationObject getAccountInfo(IWContext iwc) throws java.rmi.RemoteException{ DataTable T = new DataTable(); T.setUseBottom(false); T.setWidth("100%"); T.setTitlesVertical(true); if(account!=null){ T.add(textFormat.format(iwrb.getLocalizedString("account_number","Account number"),textFormat.HEADER),1,1); T.add(textFormat.format(account.getAccountName()),2,1); UserBusiness uBuiz = (UserBusiness) IBOLookup.getServiceInstance(iwc,UserBusiness.class); User user = uBuiz.getUser(account.getUserId()); T.add(textFormat.format(iwrb.getLocalizedString("account_owner","Account owner"),textFormat.HEADER),1,2); T.add(textFormat.format(user.getName()),2,2); T.add(textFormat.format(iwrb.getLocalizedString("account_balance","Account balance"),textFormat.HEADER),1,3); DecimalFormat Dformat = (DecimalFormat) DecimalFormat.getCurrencyInstance(iwc.getCurrentLocale()); T.add(textFormat.format(Dformat.format(account.getBalance())),2,3); T.add(textFormat.format(iwrb.getLocalizedString("last_updated","Last updated"),textFormat.HEADER),1,4); T.add(textFormat.format(account.getLastUpdated().toString()),2,4); } return T; } private PresentationObject getGroupLinks(int iCategoryId , int iGroupId,List groups)throws java.rmi.RemoteException{ Table T = new Table(); T.setCellpadding(0); T.setCellspacing(0); int col = 1; if(groups!=null){ java.util.Iterator I = groups.iterator(); TariffGroup group; Link tab; while (I.hasNext()) { group = (TariffGroup) I.next(); tab = new Link(iwb.getImageTab(group.getName(),false)); tab.addParameter(Finance.getCategoryParameter(iCategoryId)); tab.addParameter(prmGroup,group.getID()); if(account!=null) tab.addParameter(prmAccountId,account.getAccountId()); T.add(tab,col++,1); } } Link newTariff = new Link(iwrb.getLocalizedImageTab("new","New",false)); newTariff.addParameter(getCategoryParameter(iCategoryId)); if(account!=null) newTariff.addParameter(prmAccountId,account.getAccountId()); newTariff.addParameter(prmNewTariff,"true"); //Link edit = new Link(iwrb.getLocalizedImageTab("edit","textFormat",false)); //edit.setWindowToOpen(TariffGroupWindow.class); //edit.addParameter(Finance.getCategoryParameter(iCategoryId)); T.add(newTariff,col,1); return T; } private PresentationObject getTariffTable(TariffGroup group)throws java.rmi.RemoteException{ Collection listOfTariffs = null; Map map = null; boolean hasMap = false; if(group!=null){ if(group.getHandlerId() > 0){ FinanceHandler handler = FinanceFinder.getInstance().getFinanceHandler(group.getHandlerId()); map = handler.getAttributeMap(); if(map !=null) hasMap = true; } } listOfTariffs = FinanceFinder.getInstance().listOfTariffs(group.getID()); //Table T = new Table(); DataTable T = new DataTable(); T.setUseBottom(false); T.setWidth("100%"); T.addTitle(iwrb.getLocalizedString("tariffs","Tariffs")+" "+group.getName()); T.setTitlesVertical(false); int col = 1; int row = 1; T.add(textFormat.format(iwrb.getLocalizedString("use","Use")),col++,row); if(hasMap) T.add(textFormat.format(iwrb.getLocalizedString("attribute","Attribute")),col++,row); T.add(textFormat.format(iwrb.getLocalizedString("name","Name")),col++,row); T.add(textFormat.format(iwrb.getLocalizedString("price","Price")),col++,row); row++; if(listOfTariffs!=null){ java.util.Iterator I = listOfTariffs.iterator(); Tariff tariff; while(I.hasNext()){ col = 1; tariff = (Tariff) I.next(); CheckBox chk = new CheckBox(prmTariffs,tariff.getPrimaryKey().toString()); T.add(chk,col++,row); if(hasMap) T.add(textFormat.format((String) map.get(tariff.getTariffAttribute())),col++,row); T.add(textFormat.format(tariff.getName()),col++,row); T.add(textFormat.format(Float.toString(tariff.getPrice())),col,row); row++; } T.getContentTable().setColumnAlignment(col,"right"); T.getContentTable().setAlignment(1,col,"left"); } return T; } private PresentationObject getTariffPropertiesTable()throws java.rmi.RemoteException{ DataTable T = new DataTable(); T.setUseBottom(false); T.setWidth("100%"); T.setTitlesHorizontal(true); //T.addTitle(iwrb.getLocalizedString("properties","Properties")); int row = 1; int col = 1; T.add(textFormat.format(iwrb.getLocalizedString("paydate","Paydate")),col,row++); DateInput payDate = new DateInput(prmPayDate,true); payDate.setDate(IWTimestamp.RightNow().getSQLDate()); T.add(payDate,col,row); col++; row = 1; T.add(textFormat.format(iwrb.getLocalizedString("discount","Discount")+" (%)"),col,row++); //DropdownMenu dr = getIntDrop("discount",0,100,""); TextInput discount = new TextInput(prmDiscount); discount.setContent("0"); T.add(discount,col,row); col++; row = 2; SubmitButton confirm = new SubmitButton(iwrb.getLocalizedImageButton("fin_confirm","Confirm"),prmConfirm,"true"); T.add(confirm,col,row); if(account!=null) T.add(new HiddenInput(prmAccountId,String.valueOf(account.getAccountId()))); return T; } private PresentationObject getNewTariffTable(IWContext iwc)throws java.rmi.RemoteException{ DataTable T = new DataTable(); T.setWidth("100%"); T.setUseBottom(false); T.setTitlesVertical(true); TextInput tariffName = new TextInput(prmTariffName); DropdownMenu accountKeys = getAccountKeysDrop(prmAccountKey); DropdownMenu tariffGroups = getTariffGroupsDrop(prmTariffGroupId); CheckBox saveTariff = new CheckBox(prmSaveTariff); TextInput amount = new TextInput(prmAmount); T.add(textFormat.format(iwrb.getLocalizedString("tariff.name","Tariff name")),1,1); T.add(textFormat.format(iwrb.getLocalizedString("tariff.account_key","Account key")),1,2); T.add(textFormat.format(iwrb.getLocalizedString("tariff.save_under","Save under")),1,3); T.add(textFormat.format(iwrb.getLocalizedString("tariff.amount","Amount")),1,4); T.add(textFormat.format(iwrb.getLocalizedString("tariff.save_tariff","Save tariff")),1,5); T.add(tariffName,2,1); T.add(accountKeys,2,2); T.add(tariffGroups,2,3); T.add(amount,2,4); T.add(saveTariff,2,5); return T; } private DropdownMenu getAccountKeysDrop(String name)throws java.rmi.RemoteException{ Collection keys = FinanceFinder.getInstance().listOfAccountKeys(iCategoryId); DropdownMenu drp = new DropdownMenu(name); if(keys!=null){ Iterator iter = keys.iterator(); while(iter.hasNext()){ AccountKey key = (AccountKey)iter.next(); drp.addMenuElement(key.getPrimaryKey().toString(),key.getInfo()); } } return drp; } private DropdownMenu getTariffGroupsDrop(String name)throws java.rmi.RemoteException{ //Collection groups = FinanceFinder.getInstance().listOfTariffGroups(iCategoryId); Collection groups = FinanceFinder.getInstance().listOfTariffGroupsWithOutHandlers(iCategoryId); DropdownMenu drp = new DropdownMenu(name); if(groups!=null){ Iterator iter = groups.iterator(); while(iter.hasNext()){ TariffGroup grp = (TariffGroup) iter.next(); drp.addMenuElement(grp.getPrimaryKey().toString(),grp.getName()); } } return drp; } private DropdownMenu getIntDrop(String name,int start, int end, String selected){ DropdownMenu drp = new DropdownMenu(name); for (int i = start; i <= end; i++) { drp.addMenuElement(String.valueOf(i)); } drp.setSelectedElement(selected); return drp; } public void setAccountViewPage(int pageId){ this.viewPage = pageId; } public void setAccountSearchPage(int pageId){ this.searchPage = pageId; } public void main(IWContext iwc)throws java.rmi.RemoteException{ control(iwc); } }
true
true
protected void control(IWContext iwc) throws java.rmi.RemoteException{ if(isAdmin){ accBuiz = (AccountBusiness) IBOLookup.getServiceInstance(iwc,AccountBusiness.class); iCategoryId = Finance.parseCategoryId(iwc); List groups = FinanceFinder.getInstance().listOfTariffGroups(iCategoryId); TariffGroup group = null; if(iwc.isParameterSet(prmGroup)) iGroupId = Integer.parseInt(iwc.getParameter(prmGroup)); if(iGroupId > 0 ){ group = FinanceFinder.getInstance().getTariffGroup(iGroupId); } else if(groups !=null){ //group = (TariffGroup) groups.get(0); //iGroupId = group.getID(); } if(iwc.isParameterSet(prmAccountId)){ iAccountId = Integer.parseInt(iwc.getParameter(prmAccountId)); if(iAccountId>0){ parse(iwc); account = FinanceFinder.getInstance().getFinanceAccount(iAccountId); } } Table T = new Table(1,6); T.setCellpadding(0); T.setCellspacing(0); T.add(textFormat.format(iwrb.getLocalizedString("account_tariffer","Account tariffer"),textFormat.HEADER),1,1); T.setHeight(2,"15"); T.add(getAccountInfo(iwc),1,3); T.add(getGroupLinks(iCategoryId,iGroupId,groups),1,4); if(group!=null) T.add(getTariffTable(group),1,5); else T.add(getNewTariffTable(iwc),1,5); T.add(getTariffPropertiesTable(),1,6); //T.setWidth("450"); Form myForm = new Form(); myForm.add(new HiddenInput(prmCategoryId,String.valueOf(iCategoryId))); myForm.add(new HiddenInput(prmGroup,String.valueOf(iGroupId))); myForm.add(T); add(myForm); } }
protected void control(IWContext iwc) throws java.rmi.RemoteException{ if(isAdmin){ accBuiz = (AccountBusiness) IBOLookup.getServiceInstance(iwc,AccountBusiness.class); // iCategoryId = Finance.parseCategoryId(iwc); List groups = FinanceFinder.getInstance().listOfTariffGroups(iCategoryId); TariffGroup group = null; if(iwc.isParameterSet(prmGroup)) iGroupId = Integer.parseInt(iwc.getParameter(prmGroup)); if(iGroupId > 0 ){ group = FinanceFinder.getInstance().getTariffGroup(iGroupId); } else if(groups !=null){ //group = (TariffGroup) groups.get(0); //iGroupId = group.getID(); } if(iwc.isParameterSet(prmAccountId)){ iAccountId = Integer.parseInt(iwc.getParameter(prmAccountId)); if(iAccountId>0){ parse(iwc); account = FinanceFinder.getInstance().getFinanceAccount(iAccountId); } } Table T = new Table(1,6); T.setCellpadding(0); T.setCellspacing(0); T.add(textFormat.format(iwrb.getLocalizedString("account_tariffer","Account tariffer"),textFormat.HEADER),1,1); T.setHeight(2,"15"); T.add(getAccountInfo(iwc),1,3); T.add(getGroupLinks(iCategoryId,iGroupId,groups),1,4); if(group!=null) T.add(getTariffTable(group),1,5); else T.add(getNewTariffTable(iwc),1,5); T.add(getTariffPropertiesTable(),1,6); //T.setWidth("450"); Form myForm = new Form(); myForm.add(new HiddenInput(prmCategoryId,String.valueOf(iCategoryId))); myForm.add(new HiddenInput(prmGroup,String.valueOf(iGroupId))); myForm.add(T); add(myForm); } }
diff --git a/aura-impl/src/test/java/org/auraframework/impl/AuraTestingUtilImpl.java b/aura-impl/src/test/java/org/auraframework/impl/AuraTestingUtilImpl.java index 03a7bbdd24..f05d31a5cd 100644 --- a/aura-impl/src/test/java/org/auraframework/impl/AuraTestingUtilImpl.java +++ b/aura-impl/src/test/java/org/auraframework/impl/AuraTestingUtilImpl.java @@ -1,145 +1,146 @@ /* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.impl; import java.io.File; import java.util.Collection; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.auraframework.Aura; import org.auraframework.def.DefDescriptor; import org.auraframework.def.Definition; import org.auraframework.impl.source.StringSourceLoader; import org.auraframework.impl.util.AuraImplFiles; import org.auraframework.service.DefinitionService; import org.auraframework.system.AuraContext; import org.auraframework.system.Source; import org.auraframework.system.SourceListener; import org.auraframework.system.SourceListener.SourceMonitorEvent; import org.auraframework.test.AuraTestingUtil; import com.google.common.collect.Sets; public class AuraTestingUtilImpl implements AuraTestingUtil { private final Set<DefDescriptor<?>> cleanUpDds = Sets.newHashSet(); private static AtomicLong nonce = new AtomicLong(System.currentTimeMillis()); public AuraTestingUtilImpl() { } @Override public void setUp() { // Do nothing } @Override public void tearDown() { StringSourceLoader loader = StringSourceLoader.getInstance(); for (DefDescriptor<?> dd : cleanUpDds) { loader.removeSource(dd); } cleanUpDds.clear(); } @Override public File getAuraJavascriptSourceDirectory() { return AuraImplFiles.AuraJavascriptSourceDirectory.asFile(); } @Override public String getNonce() { return Long.toString(nonce.incrementAndGet()); } @Override public String getNonce(String prefix) { return (prefix == null ? "" : prefix) + getNonce(); } @Override public <T extends Definition> Source<T> getSource(DefDescriptor<T> descriptor) { // Look up in the registry if a context is available. Otherwise, we're // probably running a context-less unit test // and better be using StringSourceLoader AuraContext context = Aura.getContextService().getCurrentContext(); if (context != null) { return context.getDefRegistry().getSource(descriptor); } else { return StringSourceLoader.getInstance().getSource(descriptor); } } @Override public <T extends Definition> DefDescriptor<T> addSourceAutoCleanup(Class<T> defClass, String contents) { return addSourceAutoCleanup(defClass, contents, null); } @Override public <T extends Definition> DefDescriptor<T> addSourceAutoCleanup(Class<T> defClass, String contents, String namePrefix) { StringSourceLoader loader = StringSourceLoader.getInstance(); DefDescriptor<T> descriptor = loader.addSource(defClass, contents, namePrefix).getDescriptor(); cleanUpDds.add(descriptor); return descriptor; } @Override public <T extends Definition> DefDescriptor<T> addSourceAutoCleanup(DefDescriptor<T> descriptor, String contents) { StringSourceLoader loader = StringSourceLoader.getInstance(); loader.putSource(descriptor, contents, false); cleanUpDds.add(descriptor); return descriptor; } @Override public <T extends Definition> void clearCachedDefs(Collection<T> defs) throws Exception { if (defs == null || defs.isEmpty()) { return; } // Get the Descriptors for the provided Definitions final DefinitionService definitionService = Aura.getDefinitionService(); final Set<DefDescriptor<?>> cached = Sets.newHashSet(); for (T def : defs) { if (def != null) { cached.add(def.getDescriptor()); } } // Wait for the change notifications to get processed. We expect listeners to get processed in the order in // which they subscribe. final CountDownLatch latch = new CountDownLatch(cached.size()); SourceListener listener = new SourceListener() { + private Set<DefDescriptor<?>> descriptors = Sets.newHashSet(cached); @Override public void onSourceChanged(DefDescriptor<?> source, SourceMonitorEvent event) { - if (cached.remove(source)) { + if (descriptors.remove(source)) { latch.countDown(); } - if (cached.isEmpty()) { + if (descriptors.isEmpty()) { definitionService.unsubscribeToChangeNotification(this); } } }; definitionService.subscribeToChangeNotification(listener); for (DefDescriptor<?> desc : cached) { definitionService.onSourceChanged(desc, SourceMonitorEvent.changed); } latch.await(30, TimeUnit.SECONDS); } }
false
true
public <T extends Definition> void clearCachedDefs(Collection<T> defs) throws Exception { if (defs == null || defs.isEmpty()) { return; } // Get the Descriptors for the provided Definitions final DefinitionService definitionService = Aura.getDefinitionService(); final Set<DefDescriptor<?>> cached = Sets.newHashSet(); for (T def : defs) { if (def != null) { cached.add(def.getDescriptor()); } } // Wait for the change notifications to get processed. We expect listeners to get processed in the order in // which they subscribe. final CountDownLatch latch = new CountDownLatch(cached.size()); SourceListener listener = new SourceListener() { @Override public void onSourceChanged(DefDescriptor<?> source, SourceMonitorEvent event) { if (cached.remove(source)) { latch.countDown(); } if (cached.isEmpty()) { definitionService.unsubscribeToChangeNotification(this); } } }; definitionService.subscribeToChangeNotification(listener); for (DefDescriptor<?> desc : cached) { definitionService.onSourceChanged(desc, SourceMonitorEvent.changed); } latch.await(30, TimeUnit.SECONDS); }
public <T extends Definition> void clearCachedDefs(Collection<T> defs) throws Exception { if (defs == null || defs.isEmpty()) { return; } // Get the Descriptors for the provided Definitions final DefinitionService definitionService = Aura.getDefinitionService(); final Set<DefDescriptor<?>> cached = Sets.newHashSet(); for (T def : defs) { if (def != null) { cached.add(def.getDescriptor()); } } // Wait for the change notifications to get processed. We expect listeners to get processed in the order in // which they subscribe. final CountDownLatch latch = new CountDownLatch(cached.size()); SourceListener listener = new SourceListener() { private Set<DefDescriptor<?>> descriptors = Sets.newHashSet(cached); @Override public void onSourceChanged(DefDescriptor<?> source, SourceMonitorEvent event) { if (descriptors.remove(source)) { latch.countDown(); } if (descriptors.isEmpty()) { definitionService.unsubscribeToChangeNotification(this); } } }; definitionService.subscribeToChangeNotification(listener); for (DefDescriptor<?> desc : cached) { definitionService.onSourceChanged(desc, SourceMonitorEvent.changed); } latch.await(30, TimeUnit.SECONDS); }
diff --git a/GettingStartedWercker/src/main/java/com/westonh/gettingstartedwercker/tests/MainActivityTest.java b/GettingStartedWercker/src/main/java/com/westonh/gettingstartedwercker/tests/MainActivityTest.java index 157edd3..4992316 100644 --- a/GettingStartedWercker/src/main/java/com/westonh/gettingstartedwercker/tests/MainActivityTest.java +++ b/GettingStartedWercker/src/main/java/com/westonh/gettingstartedwercker/tests/MainActivityTest.java @@ -1,33 +1,33 @@ package com.westonh.gettingstartedwercker.tests; import android.test.ActivityInstrumentationTestCase2; import android.widget.TextView; import com.westonh.gettingstartedwercker.MainActivity; import com.westonh.gettingstartedwercker.R; /** * Created by jacco @ wercker on 9/23/13. */ public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> { public MainActivityTest() { super("com.westonh.gettingstarterdwercker", MainActivity.class); } public void testWelcomeText() { MainActivity activity; activity = (MainActivity) getActivity(); TextView tView; tView = (TextView) activity.findViewById(R.id.introText); assertNotNull(tView); String introText; introText = tView.getText().toString(); assertNotNull(introText); - assertTrue("Check intro text", introText.equals("Hello universe!")); + assertTrue("Check intro text", introText.equals("Hello world!")); } }
true
true
public void testWelcomeText() { MainActivity activity; activity = (MainActivity) getActivity(); TextView tView; tView = (TextView) activity.findViewById(R.id.introText); assertNotNull(tView); String introText; introText = tView.getText().toString(); assertNotNull(introText); assertTrue("Check intro text", introText.equals("Hello universe!")); }
public void testWelcomeText() { MainActivity activity; activity = (MainActivity) getActivity(); TextView tView; tView = (TextView) activity.findViewById(R.id.introText); assertNotNull(tView); String introText; introText = tView.getText().toString(); assertNotNull(introText); assertTrue("Check intro text", introText.equals("Hello world!")); }
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/TemplateHandler.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/TemplateHandler.java index 8bb418a33..8f7b9f2f9 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/TemplateHandler.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/client/TemplateHandler.java @@ -1,108 +1,110 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ccvs.core.client; import java.io.*; import org.eclipse.core.resources.IContainer; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.team.internal.ccvs.core.*; import org.eclipse.team.internal.ccvs.core.resources.CVSWorkspaceRoot; import org.eclipse.team.internal.ccvs.core.util.SyncFileWriter; /** * @author Administrator * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class TemplateHandler extends ResponseHandler { /** * @see org.eclipse.team.internal.ccvs.core.client.ResponseHandler#getResponseID() */ public String getResponseID() { return "Template"; //$NON-NLS-1$ } /** * @see org.eclipse.team.internal.ccvs.core.client.ResponseHandler#handle(org.eclipse.team.internal.ccvs.core.client.Session, java.lang.String, org.eclipse.core.runtime.IProgressMonitor) */ public void handle(Session session, String localDir, IProgressMonitor monitor) throws CVSException { session.readLine(); /* read the remote dir which is not needed */ - ICVSFolder localFolder = getExistingFolder(session, localDir); + // Only read the template file if the container exists. + // This is OK as we only use the template from the project folder which must exist + ICVSFolder localFolder = session.getLocalRoot().getFolder(localDir); IContainer container = (IContainer)localFolder.getIResource(); ICVSStorage templateFile = null; - if (container != null) { + if (container != null && container.exists()) { try { templateFile = CVSWorkspaceRoot.getCVSFileFor(SyncFileWriter.getTemplateFile(container)); } catch (CVSException e) { // Log the inability to create the template file CVSProviderPlugin.log(new CVSStatus(IStatus.ERROR, "Could not write template file in " + container.getFullPath() + ": " + e.getMessage(), e)); //$NON-NLS-1$ //$NON-NLS-2$ } } if (container == null || templateFile == null) { // Create a dummy storage handle to recieve the contents from the server templateFile = new ICVSStorage() { public String getName() { return "Template"; //$NON-NLS-1$ } public void setContents( InputStream stream, int responseType, boolean keepLocalHistory, IProgressMonitor monitor) throws CVSException { try { // Transfer the contents OutputStream out = new ByteArrayOutputStream(); try { byte[] buffer = new byte[1024]; int read; while ((read = stream.read(buffer)) >= 0) { Policy.checkCanceled(monitor); out.write(buffer, 0, read); } } finally { out.close(); } } catch (IOException e) { throw CVSException.wrapException(e); //$NON-NLS-1$ } finally { try { stream.close(); } catch (IOException e1) { // Ignore close errors } } } public long getSize() { return 0; } public InputStream getContents() throws CVSException { return new ByteArrayInputStream(new byte[0]); } }; } try { session.receiveFile(templateFile, false, UpdatedHandler.HANDLE_UPDATED, monitor); } catch (CVSException e) { if (!(templateFile instanceof ICVSFile && handleInvalidResourceName(session, (ICVSFile)templateFile, e))) { throw e; } } } }
false
true
public void handle(Session session, String localDir, IProgressMonitor monitor) throws CVSException { session.readLine(); /* read the remote dir which is not needed */ ICVSFolder localFolder = getExistingFolder(session, localDir); IContainer container = (IContainer)localFolder.getIResource(); ICVSStorage templateFile = null; if (container != null) { try { templateFile = CVSWorkspaceRoot.getCVSFileFor(SyncFileWriter.getTemplateFile(container)); } catch (CVSException e) { // Log the inability to create the template file CVSProviderPlugin.log(new CVSStatus(IStatus.ERROR, "Could not write template file in " + container.getFullPath() + ": " + e.getMessage(), e)); //$NON-NLS-1$ //$NON-NLS-2$ } } if (container == null || templateFile == null) { // Create a dummy storage handle to recieve the contents from the server templateFile = new ICVSStorage() { public String getName() { return "Template"; //$NON-NLS-1$ } public void setContents( InputStream stream, int responseType, boolean keepLocalHistory, IProgressMonitor monitor) throws CVSException { try { // Transfer the contents OutputStream out = new ByteArrayOutputStream(); try { byte[] buffer = new byte[1024]; int read; while ((read = stream.read(buffer)) >= 0) { Policy.checkCanceled(monitor); out.write(buffer, 0, read); } } finally { out.close(); } } catch (IOException e) { throw CVSException.wrapException(e); //$NON-NLS-1$ } finally { try { stream.close(); } catch (IOException e1) { // Ignore close errors } } } public long getSize() { return 0; } public InputStream getContents() throws CVSException { return new ByteArrayInputStream(new byte[0]); } }; } try { session.receiveFile(templateFile, false, UpdatedHandler.HANDLE_UPDATED, monitor); } catch (CVSException e) { if (!(templateFile instanceof ICVSFile && handleInvalidResourceName(session, (ICVSFile)templateFile, e))) { throw e; } } }
public void handle(Session session, String localDir, IProgressMonitor monitor) throws CVSException { session.readLine(); /* read the remote dir which is not needed */ // Only read the template file if the container exists. // This is OK as we only use the template from the project folder which must exist ICVSFolder localFolder = session.getLocalRoot().getFolder(localDir); IContainer container = (IContainer)localFolder.getIResource(); ICVSStorage templateFile = null; if (container != null && container.exists()) { try { templateFile = CVSWorkspaceRoot.getCVSFileFor(SyncFileWriter.getTemplateFile(container)); } catch (CVSException e) { // Log the inability to create the template file CVSProviderPlugin.log(new CVSStatus(IStatus.ERROR, "Could not write template file in " + container.getFullPath() + ": " + e.getMessage(), e)); //$NON-NLS-1$ //$NON-NLS-2$ } } if (container == null || templateFile == null) { // Create a dummy storage handle to recieve the contents from the server templateFile = new ICVSStorage() { public String getName() { return "Template"; //$NON-NLS-1$ } public void setContents( InputStream stream, int responseType, boolean keepLocalHistory, IProgressMonitor monitor) throws CVSException { try { // Transfer the contents OutputStream out = new ByteArrayOutputStream(); try { byte[] buffer = new byte[1024]; int read; while ((read = stream.read(buffer)) >= 0) { Policy.checkCanceled(monitor); out.write(buffer, 0, read); } } finally { out.close(); } } catch (IOException e) { throw CVSException.wrapException(e); //$NON-NLS-1$ } finally { try { stream.close(); } catch (IOException e1) { // Ignore close errors } } } public long getSize() { return 0; } public InputStream getContents() throws CVSException { return new ByteArrayInputStream(new byte[0]); } }; } try { session.receiveFile(templateFile, false, UpdatedHandler.HANDLE_UPDATED, monitor); } catch (CVSException e) { if (!(templateFile instanceof ICVSFile && handleInvalidResourceName(session, (ICVSFile)templateFile, e))) { throw e; } } }
diff --git a/kcalculator/kcalculator-rs/src/main/java/com/kcalculator/ejb/MealServiceImpl.java b/kcalculator/kcalculator-rs/src/main/java/com/kcalculator/ejb/MealServiceImpl.java index a2c56ac..d984901 100644 --- a/kcalculator/kcalculator-rs/src/main/java/com/kcalculator/ejb/MealServiceImpl.java +++ b/kcalculator/kcalculator-rs/src/main/java/com/kcalculator/ejb/MealServiceImpl.java @@ -1,114 +1,114 @@ package com.kcalculator.ejb; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceException; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.kcalculator.api.MealService; import com.kcalculator.api.data.TOMeal; import com.kcalculator.conversion.MealConverter; import com.kcalculator.domain.DailyMealPlan; import com.kcalculator.domain.Meal; import com.kcalculator.ex.DeletionException; import com.kcalculator.ex.ObjectNotFoundException; import com.kcalculator.ex.ValidationException; @Stateless @Remote(MealService.class) @Path("/meal") @TransactionAttribute(TransactionAttributeType.REQUIRED) public class MealServiceImpl extends ValidatingService implements MealService { private static final Logger logger = LoggerFactory.getLogger(MealServiceImpl.class); @PersistenceContext(unitName = "kcalculator") EntityManager em; @POST @Consumes("application/json") @Produces("application/json") @Override public TOMeal addMeal(TOMeal mealTO) throws ValidationException, ObjectNotFoundException { validateItem(mealTO); Meal mealToAdd = MealConverter.toDomainObject(mealTO); mealToAdd.setId(null); em.persist(mealToAdd); return MealConverter.toTransferObject(mealToAdd); } @PUT @Consumes("application/json") @Produces("application/json") @Override public TOMeal updateMeal(TOMeal meal) throws ValidationException, ObjectNotFoundException { validateItem(meal); // find meal and apply update Meal mealToUpdate = MealConverter.toDomainObject(meal); ensureExistence(mealToUpdate, em); em.merge(mealToUpdate); em.flush(); return MealConverter.toTransferObject(mealToUpdate); } @DELETE @Path("{mealId}") @Override public void deleteMeal(@PathParam("mealId") Long mealId) throws ValidationException, ObjectNotFoundException, DeletionException { if (mealId == null) { throw new IllegalArgumentException("Parameters must not be null"); } // find Meal and dailyMealPlan - Meal mealToDelete = ensureExistence(MealConverter.toDomainObject(toMeal), em); + Meal mealToDelete = ensureExistence(Meal.class, mealId, em); DailyMealPlan dailyMealPlan = mealToDelete.getDailyMealPlan(); // remove Meal form DailyMelaPlan if (dailyMealPlan != null) { dailyMealPlan.getMeals().remove(mealToDelete); } try { logger.info("Meal deletion with ID : " + mealToDelete.getId()); if (dailyMealPlan != null) { em.persist(dailyMealPlan); } em.remove(mealToDelete); em.flush(); } catch (PersistenceException e) { throw new DeletionException(String.format("Failed to delete Meal with id %s", mealToDelete.getId()), e); } } @GET @Produces("application/json") @Path("/{mealId}") @Override public TOMeal getMeal(@PathParam("mealId") Long mealId) throws ObjectNotFoundException { if (mealId == null) { throw new IllegalArgumentException("Parameters must not be null"); } Meal result = ensureExistence(Meal.class, mealId, em); return MealConverter.toTransferObject(result); } }
true
true
public void deleteMeal(@PathParam("mealId") Long mealId) throws ValidationException, ObjectNotFoundException, DeletionException { if (mealId == null) { throw new IllegalArgumentException("Parameters must not be null"); } // find Meal and dailyMealPlan Meal mealToDelete = ensureExistence(MealConverter.toDomainObject(toMeal), em); DailyMealPlan dailyMealPlan = mealToDelete.getDailyMealPlan(); // remove Meal form DailyMelaPlan if (dailyMealPlan != null) { dailyMealPlan.getMeals().remove(mealToDelete); } try { logger.info("Meal deletion with ID : " + mealToDelete.getId()); if (dailyMealPlan != null) { em.persist(dailyMealPlan); } em.remove(mealToDelete); em.flush(); } catch (PersistenceException e) { throw new DeletionException(String.format("Failed to delete Meal with id %s", mealToDelete.getId()), e); } }
public void deleteMeal(@PathParam("mealId") Long mealId) throws ValidationException, ObjectNotFoundException, DeletionException { if (mealId == null) { throw new IllegalArgumentException("Parameters must not be null"); } // find Meal and dailyMealPlan Meal mealToDelete = ensureExistence(Meal.class, mealId, em); DailyMealPlan dailyMealPlan = mealToDelete.getDailyMealPlan(); // remove Meal form DailyMelaPlan if (dailyMealPlan != null) { dailyMealPlan.getMeals().remove(mealToDelete); } try { logger.info("Meal deletion with ID : " + mealToDelete.getId()); if (dailyMealPlan != null) { em.persist(dailyMealPlan); } em.remove(mealToDelete); em.flush(); } catch (PersistenceException e) { throw new DeletionException(String.format("Failed to delete Meal with id %s", mealToDelete.getId()), e); } }
diff --git a/spock-core/src/main/java/org/spockframework/runtime/UnrolledFeatureNameGenerator.java b/spock-core/src/main/java/org/spockframework/runtime/UnrolledFeatureNameGenerator.java index 0f989bd2..48f79ba6 100644 --- a/spock-core/src/main/java/org/spockframework/runtime/UnrolledFeatureNameGenerator.java +++ b/spock-core/src/main/java/org/spockframework/runtime/UnrolledFeatureNameGenerator.java @@ -1,88 +1,92 @@ /* * Copyright 2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.spockframework.runtime; import java.util.HashMap; import java.util.Map; import groovy.lang.Closure; import groovy.lang.GroovyObjectSupport; import groovy.lang.MissingPropertyException; import org.spockframework.runtime.extension.ExtensionException; import org.spockframework.runtime.model.FeatureInfo; import org.spockframework.util.NullSafe; /** * @author Peter Niederwieser */ public class UnrolledFeatureNameGenerator { private final FeatureInfo feature; private final Class<? extends Closure> nameGeneratorClass; private final Map<String, Integer> parameterNameToPosition = new HashMap<String, Integer>(); private int iterationCount = -1; public UnrolledFeatureNameGenerator(FeatureInfo feature, Class<? extends Closure> nameGeneratorClass) { this.feature = feature; this.nameGeneratorClass = nameGeneratorClass; int pos = 0; for (String name : feature.getParameterNames()) parameterNameToPosition.put(name, pos++); } public String nameFor(final Object[] args) { iterationCount++; if (nameGeneratorClass == Closure.class) return String.format("%s[%d]", feature.getName(), iterationCount); Closure nameGenerator; try { - nameGenerator = nameGeneratorClass.getConstructor(Object.class, Object.class).newInstance(null, null); + try { + nameGenerator = nameGeneratorClass.getConstructor(Object.class, Object.class).newInstance(null, null); + } catch (NoSuchMethodException e) { // workaround for GROOVY-5040 + nameGenerator = nameGeneratorClass.getConstructor(Object.class, Object.class, groovy.lang.Reference.class).newInstance(null, null, null); + } } catch (Exception e) { throw new ExtensionException("Failed to instantiate @Unroll naming pattern", e); } Object delegate = new GroovyObjectSupport() { @Override public Object getProperty(String property) { if (property.equals("featureName")) return feature.getName(); if (property.equals("iterationCount")) return String.valueOf(iterationCount); Integer pos = parameterNameToPosition.get(property); if (pos == null) throw new MissingPropertyException( String.format("Cannot resolve data variable '%s'", property)); return args[pos]; } }; nameGenerator.setResolveStrategy(Closure.DELEGATE_ONLY); nameGenerator.setDelegate(delegate); String name; try { name = NullSafe.toString(nameGenerator.call()); } catch (Exception e) { throw new ExtensionException("Failed to evaluate @Unroll naming pattern", e); } return name; } }
true
true
public String nameFor(final Object[] args) { iterationCount++; if (nameGeneratorClass == Closure.class) return String.format("%s[%d]", feature.getName(), iterationCount); Closure nameGenerator; try { nameGenerator = nameGeneratorClass.getConstructor(Object.class, Object.class).newInstance(null, null); } catch (Exception e) { throw new ExtensionException("Failed to instantiate @Unroll naming pattern", e); } Object delegate = new GroovyObjectSupport() { @Override public Object getProperty(String property) { if (property.equals("featureName")) return feature.getName(); if (property.equals("iterationCount")) return String.valueOf(iterationCount); Integer pos = parameterNameToPosition.get(property); if (pos == null) throw new MissingPropertyException( String.format("Cannot resolve data variable '%s'", property)); return args[pos]; } }; nameGenerator.setResolveStrategy(Closure.DELEGATE_ONLY); nameGenerator.setDelegate(delegate); String name; try { name = NullSafe.toString(nameGenerator.call()); } catch (Exception e) { throw new ExtensionException("Failed to evaluate @Unroll naming pattern", e); } return name; }
public String nameFor(final Object[] args) { iterationCount++; if (nameGeneratorClass == Closure.class) return String.format("%s[%d]", feature.getName(), iterationCount); Closure nameGenerator; try { try { nameGenerator = nameGeneratorClass.getConstructor(Object.class, Object.class).newInstance(null, null); } catch (NoSuchMethodException e) { // workaround for GROOVY-5040 nameGenerator = nameGeneratorClass.getConstructor(Object.class, Object.class, groovy.lang.Reference.class).newInstance(null, null, null); } } catch (Exception e) { throw new ExtensionException("Failed to instantiate @Unroll naming pattern", e); } Object delegate = new GroovyObjectSupport() { @Override public Object getProperty(String property) { if (property.equals("featureName")) return feature.getName(); if (property.equals("iterationCount")) return String.valueOf(iterationCount); Integer pos = parameterNameToPosition.get(property); if (pos == null) throw new MissingPropertyException( String.format("Cannot resolve data variable '%s'", property)); return args[pos]; } }; nameGenerator.setResolveStrategy(Closure.DELEGATE_ONLY); nameGenerator.setDelegate(delegate); String name; try { name = NullSafe.toString(nameGenerator.call()); } catch (Exception e) { throw new ExtensionException("Failed to evaluate @Unroll naming pattern", e); } return name; }
diff --git a/Project_Groep2-master/ProjectGroep2/src/java/beans/datumBean.java b/Project_Groep2-master/ProjectGroep2/src/java/beans/datumBean.java index 2932d0f..4a5b333 100644 --- a/Project_Groep2-master/ProjectGroep2/src/java/beans/datumBean.java +++ b/Project_Groep2-master/ProjectGroep2/src/java/beans/datumBean.java @@ -1,86 +1,85 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package beans; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; /** * * @author Robbie Vercammen */ @ManagedBean(name="datum") @RequestScoped public class datumBean { private String strBegin, strEind; private Date dtBegin, dtEind; private Calendar calBegin, calEind; public datumBean() { } public Calendar getCalBegin() { return calBegin; } public void setCalBegin(Calendar calBegin) { this.calBegin = calBegin; } public Calendar getCalEind() { return calEind; } public void setCalEind(Calendar calEind) { this.calEind = calEind; } public String getStrBegin() { return strBegin; } public void setStrBegin(String strBegin) { this.strBegin = strBegin; } public String getStrEind() { return strEind; } public void setStrEind(String strEind) { this.strEind = strEind; } public long getDuur() throws IllegalArgumentException, ParseException { try { createCalendars(strBegin, strEind); long lDagenBegin = calBegin.getTimeInMillis(); long lDagenEinde = calEind.getTimeInMillis(); long lDiff = lDagenEinde - lDagenBegin; long lDuur = lDiff / (24 * 60 * 60 * 1000); - System.out.println("lDagenBegin: " + lDagenBegin + " lDagenEinde: " + lDagenEinde + "\nlDiff: " + lDiff + " lDuur: " + lDuur); return lDuur; } catch (IllegalArgumentException ia) { throw ia; } catch (ParseException pe) { throw pe; } } public void createCalendars(String strBegin, String strEind) throws ParseException { DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd"); Date tempDatum = formatter.parse(strBegin); calBegin = Calendar.getInstance(); calBegin.setTime(tempDatum); tempDatum = formatter.parse(strEind); calEind = Calendar.getInstance(); calEind.setTime(tempDatum); } }
true
true
public long getDuur() throws IllegalArgumentException, ParseException { try { createCalendars(strBegin, strEind); long lDagenBegin = calBegin.getTimeInMillis(); long lDagenEinde = calEind.getTimeInMillis(); long lDiff = lDagenEinde - lDagenBegin; long lDuur = lDiff / (24 * 60 * 60 * 1000); System.out.println("lDagenBegin: " + lDagenBegin + " lDagenEinde: " + lDagenEinde + "\nlDiff: " + lDiff + " lDuur: " + lDuur); return lDuur; } catch (IllegalArgumentException ia) { throw ia; } catch (ParseException pe) { throw pe; } }
public long getDuur() throws IllegalArgumentException, ParseException { try { createCalendars(strBegin, strEind); long lDagenBegin = calBegin.getTimeInMillis(); long lDagenEinde = calEind.getTimeInMillis(); long lDiff = lDagenEinde - lDagenBegin; long lDuur = lDiff / (24 * 60 * 60 * 1000); return lDuur; } catch (IllegalArgumentException ia) { throw ia; } catch (ParseException pe) { throw pe; } }
diff --git a/src/in/yuvi/wpsignpost/PostActivity.java b/src/in/yuvi/wpsignpost/PostActivity.java index cc09b4a..11142e8 100644 --- a/src/in/yuvi/wpsignpost/PostActivity.java +++ b/src/in/yuvi/wpsignpost/PostActivity.java @@ -1,196 +1,196 @@ package in.yuvi.wpsignpost; import java.text.SimpleDateFormat; import java.util.concurrent.ExecutionException; import java.util.regex.Pattern; import in.yuvi.wpsignpost.api.Issue; import in.yuvi.wpsignpost.api.Post; import in.yuvi.wpsignpost.api.SignpostAPI; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.webkit.*; import android.widget.Button; import android.support.v4.app.NavUtils; import com.actionbarsherlock.*; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.actionbarsherlock.widget.*; import com.actionbarsherlock.app.*; import android.support.v4.widget.*; import android.support.v4.view.*; public class PostActivity extends SherlockActivity { private WebView webview; private ShareActionProvider shareProvider; private SignpostApp app; private String currentPermalink; private class PostWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } } private class FetchPostTask extends AsyncTask<String, Object, Post> { @Override protected Post doInBackground(String... params) { String permalink = params[0]; Post p = null; try { p = app.cache.getPost(permalink); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } return p; } @Override protected void onPreExecute() { super.onPreExecute(); View loadingView = findViewById(R.id.postLoadingAnimation); loadingView.setVisibility(View.VISIBLE); webview.setVisibility(View.GONE); View errorView = findViewById(R.id.postError); errorView.setVisibility(View.GONE); } @Override protected void onPostExecute(Post result) { super.onPostExecute(result); if(result != null) { displayPost(result); } else { showError(); } } } private void showError() { webview.setVisibility(View.GONE); View loadingView = findViewById(R.id.postLoadingAnimation); loadingView.setVisibility(View.GONE); View errorView = findViewById(R.id.postError); errorView.setVisibility(View.VISIBLE); Button retryButton = (Button)findViewById(R.id.postRetryButton); retryButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { FetchPostTask t = new FetchPostTask(); t.execute(currentPermalink); } }); } private void displayPost(Post p) { setupShareFunction(p); String prefix = ""; String postfix = ""; prefix += getString(R.string.post_css); - prefix += String.format(getString(R.string.post_title_html), p.title); + prefix += String.format(getString(R.string.post_title_html), "//" + p.permalink, p.title); if(p.author_name != null && p.author_name.length() != 0) { prefix += String.format(getString(R.string.post_author_html), p.author_link, p.author_name); } String article_title = p.permalink.replace("en.wikipedia.org/wiki/", ""); postfix += String.format(getString(R.string.post_footer_html), "/w/index.php?title=" + article_title + "&action=history"); String content = prefix + p.content + postfix; webview.loadDataWithBaseURL("http://en.wikipedia.org", content, "text/html", "utf-8", null); View loadingView = findViewById(R.id.postLoadingAnimation); loadingView.setVisibility(View.GONE); webview.setVisibility(View.VISIBLE); } private void setupShareFunction(Post post) { if(shareProvider == null) { // Recycled view! The sharing intents have already been setup // But is sortof mostly a hack. I need to figure out why menu is null return; } Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, "https://" + post.permalink); shareIntent.putExtra(Intent.EXTRA_TITLE, post.title); shareProvider = (ShareActionProvider) menu.findItem( R.id.menu_share).getActionProvider(); shareProvider.setShareIntent(shareIntent); } private Menu menu; @Override public boolean onCreateOptionsMenu(Menu menu) { getSupportMenuInflater().inflate(R.menu.activity_post, menu); this.menu = menu; shareProvider = (ShareActionProvider) menu.findItem( R.id.menu_share).getActionProvider(); return true; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = ((SignpostApp)getApplicationContext()); setContentView(R.layout.activity_post); webview = (WebView)findViewById(R.id.postWebview); webview.setWebViewClient(new PostWebViewClient()); if(Build.VERSION.SDK_INT >= 11) { // No sane way to give people touchZoom without the retarded -/+ controls on pre-honeycomb Android webview.getSettings().setBuiltInZoomControls(true); webview.getSettings().setDisplayZoomControls(false); } getSupportActionBar().setDisplayHomeAsUpEnabled(true); Intent intent = getIntent(); String permalink = (String) intent.getExtras().get(Intent.EXTRA_TEXT); showPostForPermalink(permalink); currentPermalink = permalink; } private void showPostForPermalink(String permalink) { FetchPostTask task = new FetchPostTask(); task.execute(permalink); this.setTitle(Post.parseCategory(permalink)); this.getActionBar().setSubtitle(SimpleDateFormat.getDateInstance(SimpleDateFormat.MEDIUM).format(Post.parsePublishedDate(permalink))); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // Because we might be in an error page, and current post might be null, so not using cache String issuePermalink = Issue.makePermalink(Post.parsePublishedDate(currentPermalink)); Intent intent = new Intent(this, PostsActivity.class); intent.putExtra(Intent.EXTRA_TEXT, issuePermalink); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } }
true
true
private void displayPost(Post p) { setupShareFunction(p); String prefix = ""; String postfix = ""; prefix += getString(R.string.post_css); prefix += String.format(getString(R.string.post_title_html), p.title); if(p.author_name != null && p.author_name.length() != 0) { prefix += String.format(getString(R.string.post_author_html), p.author_link, p.author_name); } String article_title = p.permalink.replace("en.wikipedia.org/wiki/", ""); postfix += String.format(getString(R.string.post_footer_html), "/w/index.php?title=" + article_title + "&action=history"); String content = prefix + p.content + postfix; webview.loadDataWithBaseURL("http://en.wikipedia.org", content, "text/html", "utf-8", null); View loadingView = findViewById(R.id.postLoadingAnimation); loadingView.setVisibility(View.GONE); webview.setVisibility(View.VISIBLE); }
private void displayPost(Post p) { setupShareFunction(p); String prefix = ""; String postfix = ""; prefix += getString(R.string.post_css); prefix += String.format(getString(R.string.post_title_html), "//" + p.permalink, p.title); if(p.author_name != null && p.author_name.length() != 0) { prefix += String.format(getString(R.string.post_author_html), p.author_link, p.author_name); } String article_title = p.permalink.replace("en.wikipedia.org/wiki/", ""); postfix += String.format(getString(R.string.post_footer_html), "/w/index.php?title=" + article_title + "&action=history"); String content = prefix + p.content + postfix; webview.loadDataWithBaseURL("http://en.wikipedia.org", content, "text/html", "utf-8", null); View loadingView = findViewById(R.id.postLoadingAnimation); loadingView.setVisibility(View.GONE); webview.setVisibility(View.VISIBLE); }
diff --git a/src/net/fornwall/eclipsecoder/archive/ArchiveListView.java b/src/net/fornwall/eclipsecoder/archive/ArchiveListView.java index 4ee6517..e17ec9f 100644 --- a/src/net/fornwall/eclipsecoder/archive/ArchiveListView.java +++ b/src/net/fornwall/eclipsecoder/archive/ArchiveListView.java @@ -1,326 +1,325 @@ package net.fornwall.eclipsecoder.archive; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.List; import net.fornwall.eclipsecoder.languages.LanguageSupportFactory; import net.fornwall.eclipsecoder.preferences.EclipseCoderPlugin; import net.fornwall.eclipsecoder.util.Utilities; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.browser.IWorkbenchBrowserSupport; import org.eclipse.ui.part.ViewPart; import org.xml.sax.SAXException; /** * A view which allows the user to browse and select problems for download and * project generation from the TopCoder problem archive. */ public class ArchiveListView extends ViewPart { static ArchiveListView instance; public static class ListReference { List<ProblemStats> problemStats; } private Job updateListJob = new Job(Messages.updatingProblemList) { { setUser(true); } @Override protected IStatus run(IProgressMonitor monitor) { if (!EclipseCoderPlugin.isTcAccountSpecified()) { EclipseCoderPlugin.demandTcAccountSpecified(); return Status.OK_STATUS; } monitor.beginTask(Messages.updatingProblemList, 100); final ListReference listReference = new ListReference(); IStatus status = ProblemScraper.downloadProblemStats(monitor, listReference); if (!status.isOK()) return status; if (monitor.isCanceled()) return Status.CANCEL_STATUS; monitor.subTask(Messages.updatingTable); PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { @SuppressWarnings("synthetic-access")//$NON-NLS-1$ public void run() { viewer.setInput(listReference.problemStats); for (int i = 0; i < problemListTable.getColumnCount(); i++) { problemListTable.getColumn(i).pack(); } setContentDescription(""); //$NON-NLS-1$ } }); return status; } }; Table problemListTable; TableViewer viewer; @Override public void createPartControl(final Composite parent) { ArchiveListView.instance = this; fillLocalPullDown(getViewSite().getActionBars().getMenuManager()); createTable(parent); } void createTable(Composite parent) { problemListTable = new Table(parent, SWT.FULL_SELECTION); problemListTable.setHeaderVisible(true); problemListTable.setLinesVisible(true); viewer = new TableViewer(problemListTable); viewer.setLabelProvider(new ProblemLabelProvider()); viewer.setContentProvider(new ArrayContentProvider()); Menu rightClickMenu = new Menu(viewer.getTable()); MenuItem viewSubmissionsItem = new MenuItem(rightClickMenu, SWT.PUSH); viewSubmissionsItem.setText(Messages.viewSubmissionList); viewSubmissionsItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent selectionEvent) { ProblemStats stats = (ProblemStats) ((IStructuredSelection) viewer.getSelection()).getFirstElement(); if (stats == null) { return; } Job job = new SubmissionListFetcherJob(stats); job.setUser(true); job.schedule(); } }); MenuItem viewEditorialItem = new MenuItem(rightClickMenu, SWT.PUSH); viewEditorialItem.setText(Messages.viewMatchEditorial); viewEditorialItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final ProblemStats stats = (ProblemStats) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); try { // TODO: Cache a bit? - URLConnection c = new URL("http://www.topcoder.com/tc?module=Static&d1=match_editorials&d2=archive") //$NON-NLS-1$ + URLConnection c = new URL("http://apps.topcoder.com/wiki/display/tc/Algorithm+Problem+Set+Analysis") //$NON-NLS-1$ .openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(c.getInputStream())); try { String line; while ((line = reader.readLine()) != null) { if (line.contains(stats.getContestName())) { - String href = Utilities.getMatch(line, "<a href=\"(.*?)\"", 1); //$NON-NLS-1$ + String href = Utilities.getMatch(line, "<A href=\"(.*?)\"", 1); //$NON-NLS-1$ href = href.replaceAll("&amp;", "&"); // jump to the right place directly - older // problem statements are not formatted this // way, though it cannot hurt href += "#" + stats.getProblemId(); //$NON-NLS-1$ PlatformUI.getWorkbench().getBrowserSupport().createBrowser( IWorkbenchBrowserSupport.AS_VIEW, ArchiveListView.class.getCanonicalName(), "", "").openURL( //$NON-NLS-1$ //$NON-NLS-2$ - new URL("http://www.topcoder.com" //$NON-NLS-1$ - + href)); + new URL(href)); return; } } } finally { reader.close(); } Utilities.showMessageDialog(Messages.noMatchEditorialFound, Messages.noMatchEditorialFoundDescription); } catch (Exception e1) { Utilities.showException(e1); } } }); viewer.getTable().setMenu(rightClickMenu); for (String columnTitle : ProblemStats.COLUMN_NAMES) { TableColumn column = new TableColumn(problemListTable, SWT.LEFT); column.setText(columnTitle); } viewer.setSorter(new ProblemComparator(0, false)); problemListTable.setSortColumn(problemListTable.getColumn(0)); problemListTable.setSortDirection(SWT.DOWN); for (int i = 0; i < problemListTable.getColumnCount(); i++) { final int index = i; problemListTable.getColumn(i).addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ProblemComparator previousSorter = (ProblemComparator) viewer.getSorter(); boolean reversed = false; if (previousSorter.column == index) { reversed = !previousSorter.reversed; } problemListTable.setSortColumn(problemListTable.getColumn(index)); problemListTable.setSortDirection(reversed ? SWT.UP : SWT.DOWN); viewer.setSorter(new ProblemComparator(index, reversed)); } }); problemListTable.getColumn(i).pack(); } problemListTable.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent mouseEvent) { ProblemStats stats = (ProblemStats) ((IStructuredSelection) viewer.getSelection()).getFirstElement(); if (stats == null) { return; } if (!EclipseCoderPlugin.isTcAccountSpecified()) { EclipseCoderPlugin.demandTcAccountSpecified(); return; } Job job; if ((new File(new File(System.getProperty("user.home")), ".enablefetchmarker")).exists()) { job = new ProblemFetcherJob(stats); } else { job = new SubmissionListFetcherJob(stats); } job.setUser(true); job.schedule(); } }); List<ProblemStats> problemList = ProblemScraper.loadProblemStats(); if (problemList == null) { setContentDescription(Messages.needToDownloadProblemArchive); } else { setContentDescription(""); //$NON-NLS-1$ viewer.setInput(problemList); for (int i = 0; i < problemListTable.getColumnCount(); i++) { problemListTable.getColumn(i).pack(); } } } private void fillLocalPullDown(IMenuManager menuManager) { ImageDescriptor updateListImage = PlatformUI.getWorkbench().getSharedImages().getImageDescriptor( ISharedImages.IMG_TOOL_COPY); IAction theAction = new DisabledWhileRunningJobAction(Messages.updateListActionName, updateListImage, updateListJob); menuManager.add(theAction); String preferedLanguage = EclipseCoderPlugin.getDefault().getPreferenceStore().getString( EclipseCoderPlugin.PREFERENCE_LANGUAGE); final String LANG_GROUP = "lang_group"; //$NON-NLS-1$ MenuManager langMenuManager = new MenuManager(Messages.useLanguageActionName, null); menuManager.add(new Separator()); menuManager.add(langMenuManager); langMenuManager.add(new GroupMarker(LANG_GROUP)); for (String lang : LanguageSupportFactory.supportedLanguages()) { Action langAction = new Action(lang, IAction.AS_RADIO_BUTTON) { @Override public void run() { if (isChecked()) { EclipseCoderPlugin.getDefault().getPreferenceStore().setValue( EclipseCoderPlugin.PREFERENCE_LANGUAGE, getText()); } } }; langMenuManager.appendToGroup(LANG_GROUP, langAction); if (lang.equals(preferedLanguage)) { langAction.setChecked(true); } } } @Override public void setFocus() { // if (downloadButton != null) { // downloadButton.setFocus(); // } else if (problemListTable != null) { problemListTable.setFocus(); // } } } @SuppressWarnings("serial")//$NON-NLS-1$ class CanceledException extends SAXException { // just a tag class } class ProblemComparator extends ViewerSorter { public int column; public boolean reversed; public ProblemComparator(int column, boolean reversed) { this.column = column; this.reversed = reversed; } @Override public int compare(Viewer viewer, Object e1, Object e2) { ProblemStats s1 = (ProblemStats) e1; ProblemStats s2 = (ProblemStats) e2; int ret = s1.compareTo(s2, column); return (reversed ? -1 : 1) * ret; } } class ProblemLabelProvider extends LabelProvider implements ITableLabelProvider { public Image getColumnImage(Object element, int columnIndex) { return null; } public String getColumnText(Object element, int columnIndex) { ProblemStats stats = (ProblemStats) element; return stats.getFieldString(columnIndex); } }
false
true
void createTable(Composite parent) { problemListTable = new Table(parent, SWT.FULL_SELECTION); problemListTable.setHeaderVisible(true); problemListTable.setLinesVisible(true); viewer = new TableViewer(problemListTable); viewer.setLabelProvider(new ProblemLabelProvider()); viewer.setContentProvider(new ArrayContentProvider()); Menu rightClickMenu = new Menu(viewer.getTable()); MenuItem viewSubmissionsItem = new MenuItem(rightClickMenu, SWT.PUSH); viewSubmissionsItem.setText(Messages.viewSubmissionList); viewSubmissionsItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent selectionEvent) { ProblemStats stats = (ProblemStats) ((IStructuredSelection) viewer.getSelection()).getFirstElement(); if (stats == null) { return; } Job job = new SubmissionListFetcherJob(stats); job.setUser(true); job.schedule(); } }); MenuItem viewEditorialItem = new MenuItem(rightClickMenu, SWT.PUSH); viewEditorialItem.setText(Messages.viewMatchEditorial); viewEditorialItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final ProblemStats stats = (ProblemStats) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); try { // TODO: Cache a bit? URLConnection c = new URL("http://www.topcoder.com/tc?module=Static&d1=match_editorials&d2=archive") //$NON-NLS-1$ .openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(c.getInputStream())); try { String line; while ((line = reader.readLine()) != null) { if (line.contains(stats.getContestName())) { String href = Utilities.getMatch(line, "<a href=\"(.*?)\"", 1); //$NON-NLS-1$ href = href.replaceAll("&amp;", "&"); // jump to the right place directly - older // problem statements are not formatted this // way, though it cannot hurt href += "#" + stats.getProblemId(); //$NON-NLS-1$ PlatformUI.getWorkbench().getBrowserSupport().createBrowser( IWorkbenchBrowserSupport.AS_VIEW, ArchiveListView.class.getCanonicalName(), "", "").openURL( //$NON-NLS-1$ //$NON-NLS-2$ new URL("http://www.topcoder.com" //$NON-NLS-1$ + href)); return; } } } finally { reader.close(); } Utilities.showMessageDialog(Messages.noMatchEditorialFound, Messages.noMatchEditorialFoundDescription); } catch (Exception e1) { Utilities.showException(e1); } } }); viewer.getTable().setMenu(rightClickMenu); for (String columnTitle : ProblemStats.COLUMN_NAMES) { TableColumn column = new TableColumn(problemListTable, SWT.LEFT); column.setText(columnTitle); } viewer.setSorter(new ProblemComparator(0, false)); problemListTable.setSortColumn(problemListTable.getColumn(0)); problemListTable.setSortDirection(SWT.DOWN); for (int i = 0; i < problemListTable.getColumnCount(); i++) { final int index = i; problemListTable.getColumn(i).addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ProblemComparator previousSorter = (ProblemComparator) viewer.getSorter(); boolean reversed = false; if (previousSorter.column == index) { reversed = !previousSorter.reversed; } problemListTable.setSortColumn(problemListTable.getColumn(index)); problemListTable.setSortDirection(reversed ? SWT.UP : SWT.DOWN); viewer.setSorter(new ProblemComparator(index, reversed)); } }); problemListTable.getColumn(i).pack(); } problemListTable.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent mouseEvent) { ProblemStats stats = (ProblemStats) ((IStructuredSelection) viewer.getSelection()).getFirstElement(); if (stats == null) { return; } if (!EclipseCoderPlugin.isTcAccountSpecified()) { EclipseCoderPlugin.demandTcAccountSpecified(); return; } Job job; if ((new File(new File(System.getProperty("user.home")), ".enablefetchmarker")).exists()) { job = new ProblemFetcherJob(stats); } else { job = new SubmissionListFetcherJob(stats); } job.setUser(true); job.schedule(); } }); List<ProblemStats> problemList = ProblemScraper.loadProblemStats(); if (problemList == null) { setContentDescription(Messages.needToDownloadProblemArchive); } else { setContentDescription(""); //$NON-NLS-1$ viewer.setInput(problemList); for (int i = 0; i < problemListTable.getColumnCount(); i++) { problemListTable.getColumn(i).pack(); } } }
void createTable(Composite parent) { problemListTable = new Table(parent, SWT.FULL_SELECTION); problemListTable.setHeaderVisible(true); problemListTable.setLinesVisible(true); viewer = new TableViewer(problemListTable); viewer.setLabelProvider(new ProblemLabelProvider()); viewer.setContentProvider(new ArrayContentProvider()); Menu rightClickMenu = new Menu(viewer.getTable()); MenuItem viewSubmissionsItem = new MenuItem(rightClickMenu, SWT.PUSH); viewSubmissionsItem.setText(Messages.viewSubmissionList); viewSubmissionsItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent selectionEvent) { ProblemStats stats = (ProblemStats) ((IStructuredSelection) viewer.getSelection()).getFirstElement(); if (stats == null) { return; } Job job = new SubmissionListFetcherJob(stats); job.setUser(true); job.schedule(); } }); MenuItem viewEditorialItem = new MenuItem(rightClickMenu, SWT.PUSH); viewEditorialItem.setText(Messages.viewMatchEditorial); viewEditorialItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { final ProblemStats stats = (ProblemStats) ((IStructuredSelection) viewer.getSelection()) .getFirstElement(); try { // TODO: Cache a bit? URLConnection c = new URL("http://apps.topcoder.com/wiki/display/tc/Algorithm+Problem+Set+Analysis") //$NON-NLS-1$ .openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(c.getInputStream())); try { String line; while ((line = reader.readLine()) != null) { if (line.contains(stats.getContestName())) { String href = Utilities.getMatch(line, "<A href=\"(.*?)\"", 1); //$NON-NLS-1$ href = href.replaceAll("&amp;", "&"); // jump to the right place directly - older // problem statements are not formatted this // way, though it cannot hurt href += "#" + stats.getProblemId(); //$NON-NLS-1$ PlatformUI.getWorkbench().getBrowserSupport().createBrowser( IWorkbenchBrowserSupport.AS_VIEW, ArchiveListView.class.getCanonicalName(), "", "").openURL( //$NON-NLS-1$ //$NON-NLS-2$ new URL(href)); return; } } } finally { reader.close(); } Utilities.showMessageDialog(Messages.noMatchEditorialFound, Messages.noMatchEditorialFoundDescription); } catch (Exception e1) { Utilities.showException(e1); } } }); viewer.getTable().setMenu(rightClickMenu); for (String columnTitle : ProblemStats.COLUMN_NAMES) { TableColumn column = new TableColumn(problemListTable, SWT.LEFT); column.setText(columnTitle); } viewer.setSorter(new ProblemComparator(0, false)); problemListTable.setSortColumn(problemListTable.getColumn(0)); problemListTable.setSortDirection(SWT.DOWN); for (int i = 0; i < problemListTable.getColumnCount(); i++) { final int index = i; problemListTable.getColumn(i).addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ProblemComparator previousSorter = (ProblemComparator) viewer.getSorter(); boolean reversed = false; if (previousSorter.column == index) { reversed = !previousSorter.reversed; } problemListTable.setSortColumn(problemListTable.getColumn(index)); problemListTable.setSortDirection(reversed ? SWT.UP : SWT.DOWN); viewer.setSorter(new ProblemComparator(index, reversed)); } }); problemListTable.getColumn(i).pack(); } problemListTable.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent mouseEvent) { ProblemStats stats = (ProblemStats) ((IStructuredSelection) viewer.getSelection()).getFirstElement(); if (stats == null) { return; } if (!EclipseCoderPlugin.isTcAccountSpecified()) { EclipseCoderPlugin.demandTcAccountSpecified(); return; } Job job; if ((new File(new File(System.getProperty("user.home")), ".enablefetchmarker")).exists()) { job = new ProblemFetcherJob(stats); } else { job = new SubmissionListFetcherJob(stats); } job.setUser(true); job.schedule(); } }); List<ProblemStats> problemList = ProblemScraper.loadProblemStats(); if (problemList == null) { setContentDescription(Messages.needToDownloadProblemArchive); } else { setContentDescription(""); //$NON-NLS-1$ viewer.setInput(problemList); for (int i = 0; i < problemListTable.getColumnCount(); i++) { problemListTable.getColumn(i).pack(); } } }
diff --git a/src/com/connectsy/events/EventRenderer.java b/src/com/connectsy/events/EventRenderer.java index dfaf51f..94b9dad 100644 --- a/src/com/connectsy/events/EventRenderer.java +++ b/src/com/connectsy/events/EventRenderer.java @@ -1,108 +1,107 @@ package com.connectsy.events; import android.content.Context; import android.content.Intent; import android.text.Html; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import com.connectsy.LocManager; import com.connectsy.R; import com.connectsy.data.AvatarFetcher; import com.connectsy.data.DataManager.DataUpdateListener; import com.connectsy.events.EventManager.Event; import com.connectsy.utils.DateUtils; import com.connectsy.utils.Utils; public class EventRenderer implements DataUpdateListener { @SuppressWarnings("unused") private static final String TAG = "EventRenderer"; private EventManager evMan; Context context; View view; String rev; boolean truncate; Event event; public EventRenderer(Context context, View view, String rev, boolean truncate){ evMan = new EventManager(context, this, null, null); this.context = context; this.view = view; this.rev = rev; this.truncate = truncate; event = evMan.getEvent(rev); if (event == null) evMan.refreshEvent(rev, 0); else render(); } private void render(){ final OnClickListener userClick = new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW); i.setType("vnd.android.cursor.item/vnd.connectsy.user"); i.putExtra("com.connectsy.user.username", event.creator); context.startActivity(i); } }; view.findViewById(R.id.event_loading).setVisibility(View.GONE); - view.findViewById(R.id.event_details).setVisibility(View.VISIBLE); ImageView avatar = (ImageView) view.findViewById(R.id.event_avatar); avatar.setOnClickListener(userClick); new AvatarFetcher(context, event.creator, avatar).fetch(); TextView username = (TextView) view.findViewById(R.id.event_username); username.setText(event.creator); username.setOnClickListener(userClick); if (event.category != null && !event.category.equals("")) { view.findViewById(R.id.event_pipe).setVisibility(View.VISIBLE); TextView category = (TextView) view .findViewById(R.id.event_category); category.setVisibility(View.VISIBLE); category.setText(event.category); category.setOnClickListener(new TextView.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW); i.setType("vnd.android.cursor.dir/vnd.connectsy.event"); i.putExtra("filter", EventManager.Filter.CATEGORY); i.putExtra("category", event.category); context.startActivity(i); } }); } TextView where = (TextView) view.findViewById(R.id.event_where); where.setText(Html.fromHtml("<b>where:</b> " + Utils.maybeTruncate(event.where, 25, truncate))); TextView what = (TextView) view.findViewById(R.id.event_what); what.setText(Html.fromHtml("<b>what:</b> " + Utils.maybeTruncate(event.description, 25, truncate))); TextView when = (TextView) view.findViewById(R.id.event_when); when.setText(Html.fromHtml("<b>when:</b> " + DateUtils.formatTimestamp(event.when))); TextView distance = (TextView) view.findViewById(R.id.event_distance); String distanceText = new LocManager(context).distanceFrom( event.posted_from[0], event.posted_from[1]); if (distanceText != null) distance.setText(distanceText); else distance.setVisibility(View.VISIBLE); TextView created = (TextView) view.findViewById(R.id.event_created); created.setText("created " + DateUtils.formatTimestamp(event.created)); } public void onDataUpdate(int code, String response) { event = evMan.getEvent(rev); render(); } public void onRemoteError(int httpStatus, int code) {} }
true
true
private void render(){ final OnClickListener userClick = new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW); i.setType("vnd.android.cursor.item/vnd.connectsy.user"); i.putExtra("com.connectsy.user.username", event.creator); context.startActivity(i); } }; view.findViewById(R.id.event_loading).setVisibility(View.GONE); view.findViewById(R.id.event_details).setVisibility(View.VISIBLE); ImageView avatar = (ImageView) view.findViewById(R.id.event_avatar); avatar.setOnClickListener(userClick); new AvatarFetcher(context, event.creator, avatar).fetch(); TextView username = (TextView) view.findViewById(R.id.event_username); username.setText(event.creator); username.setOnClickListener(userClick); if (event.category != null && !event.category.equals("")) { view.findViewById(R.id.event_pipe).setVisibility(View.VISIBLE); TextView category = (TextView) view .findViewById(R.id.event_category); category.setVisibility(View.VISIBLE); category.setText(event.category); category.setOnClickListener(new TextView.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW); i.setType("vnd.android.cursor.dir/vnd.connectsy.event"); i.putExtra("filter", EventManager.Filter.CATEGORY); i.putExtra("category", event.category); context.startActivity(i); } }); } TextView where = (TextView) view.findViewById(R.id.event_where); where.setText(Html.fromHtml("<b>where:</b> " + Utils.maybeTruncate(event.where, 25, truncate))); TextView what = (TextView) view.findViewById(R.id.event_what); what.setText(Html.fromHtml("<b>what:</b> " + Utils.maybeTruncate(event.description, 25, truncate))); TextView when = (TextView) view.findViewById(R.id.event_when); when.setText(Html.fromHtml("<b>when:</b> " + DateUtils.formatTimestamp(event.when))); TextView distance = (TextView) view.findViewById(R.id.event_distance); String distanceText = new LocManager(context).distanceFrom( event.posted_from[0], event.posted_from[1]); if (distanceText != null) distance.setText(distanceText); else distance.setVisibility(View.VISIBLE); TextView created = (TextView) view.findViewById(R.id.event_created); created.setText("created " + DateUtils.formatTimestamp(event.created)); }
private void render(){ final OnClickListener userClick = new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW); i.setType("vnd.android.cursor.item/vnd.connectsy.user"); i.putExtra("com.connectsy.user.username", event.creator); context.startActivity(i); } }; view.findViewById(R.id.event_loading).setVisibility(View.GONE); ImageView avatar = (ImageView) view.findViewById(R.id.event_avatar); avatar.setOnClickListener(userClick); new AvatarFetcher(context, event.creator, avatar).fetch(); TextView username = (TextView) view.findViewById(R.id.event_username); username.setText(event.creator); username.setOnClickListener(userClick); if (event.category != null && !event.category.equals("")) { view.findViewById(R.id.event_pipe).setVisibility(View.VISIBLE); TextView category = (TextView) view .findViewById(R.id.event_category); category.setVisibility(View.VISIBLE); category.setText(event.category); category.setOnClickListener(new TextView.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Intent.ACTION_VIEW); i.setType("vnd.android.cursor.dir/vnd.connectsy.event"); i.putExtra("filter", EventManager.Filter.CATEGORY); i.putExtra("category", event.category); context.startActivity(i); } }); } TextView where = (TextView) view.findViewById(R.id.event_where); where.setText(Html.fromHtml("<b>where:</b> " + Utils.maybeTruncate(event.where, 25, truncate))); TextView what = (TextView) view.findViewById(R.id.event_what); what.setText(Html.fromHtml("<b>what:</b> " + Utils.maybeTruncate(event.description, 25, truncate))); TextView when = (TextView) view.findViewById(R.id.event_when); when.setText(Html.fromHtml("<b>when:</b> " + DateUtils.formatTimestamp(event.when))); TextView distance = (TextView) view.findViewById(R.id.event_distance); String distanceText = new LocManager(context).distanceFrom( event.posted_from[0], event.posted_from[1]); if (distanceText != null) distance.setText(distanceText); else distance.setVisibility(View.VISIBLE); TextView created = (TextView) view.findViewById(R.id.event_created); created.setText("created " + DateUtils.formatTimestamp(event.created)); }
diff --git a/src/net/rptools/maptool/client/ui/zone/ZoneRenderer.java b/src/net/rptools/maptool/client/ui/zone/ZoneRenderer.java index f72b57e3..786295db 100644 --- a/src/net/rptools/maptool/client/ui/zone/ZoneRenderer.java +++ b/src/net/rptools/maptool/client/ui/zone/ZoneRenderer.java @@ -1,2720 +1,2715 @@ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.rptools.maptool.client.ui.zone; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Dimension; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Paint; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.Transparency; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.QuadCurve2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import javax.swing.JComponent; import javax.swing.SwingUtilities; import javax.swing.Timer; import net.rptools.lib.MD5Key; import net.rptools.lib.image.ImageUtil; import net.rptools.lib.swing.ImageBorder; import net.rptools.lib.swing.ImageLabel; import net.rptools.lib.swing.SwingUtil; import net.rptools.maptool.client.AppActions; import net.rptools.maptool.client.AppPreferences; import net.rptools.maptool.client.AppState; import net.rptools.maptool.client.AppStyle; import net.rptools.maptool.client.AppUtil; import net.rptools.maptool.client.MapTool; import net.rptools.maptool.client.MapToolUtil; import net.rptools.maptool.client.ScreenPoint; import net.rptools.maptool.client.TransferableHelper; import net.rptools.maptool.client.TransferableToken; import net.rptools.maptool.client.ui.Scale; import net.rptools.maptool.client.ui.token.AbstractTokenOverlay; import net.rptools.maptool.client.ui.token.BarTokenOverlay; import net.rptools.maptool.client.ui.token.NewTokenDialog; import net.rptools.maptool.client.ui.token.TokenTemplate; import net.rptools.maptool.client.walker.ZoneWalker; import net.rptools.maptool.model.Asset; import net.rptools.maptool.model.AssetManager; import net.rptools.maptool.model.CellPoint; import net.rptools.maptool.model.GUID; import net.rptools.maptool.model.Grid; import net.rptools.maptool.model.GridCapabilities; import net.rptools.maptool.model.Label; import net.rptools.maptool.model.ModelChangeEvent; import net.rptools.maptool.model.ModelChangeListener; import net.rptools.maptool.model.Path; import net.rptools.maptool.model.Player; import net.rptools.maptool.model.Token; import net.rptools.maptool.model.TokenFootprint; import net.rptools.maptool.model.Zone; import net.rptools.maptool.model.ZonePoint; import net.rptools.maptool.model.drawing.DrawableTexturePaint; import net.rptools.maptool.model.drawing.DrawnElement; import net.rptools.maptool.util.CodeTimer; import net.rptools.maptool.util.GraphicsUtil; import net.rptools.maptool.util.ImageManager; import net.rptools.maptool.util.StringUtil; import net.rptools.maptool.util.TokenUtil; /** */ public class ZoneRenderer extends JComponent implements DropTargetListener, Comparable { private static final long serialVersionUID = 3832897780066104884L; public static final int MIN_GRID_SIZE = 10; protected Zone zone; private ZoneView zoneView; private Scale zoneScale; private DrawableRenderer backgroundDrawableRenderer = new PartitionedDrawableRenderer(); private DrawableRenderer objectDrawableRenderer = new BackBufferDrawableRenderer(); private DrawableRenderer tokenDrawableRenderer = new BackBufferDrawableRenderer(); private DrawableRenderer gmDrawableRenderer = new BackBufferDrawableRenderer(); private List<ZoneOverlay> overlayList = new ArrayList<ZoneOverlay>(); private Map<Zone.Layer , List<TokenLocation>> tokenLocationMap = new HashMap<Zone.Layer, List<TokenLocation>>(); private Set<GUID> selectedTokenSet = new HashSet<GUID>(); private List<Set<GUID>> selectedTokenSetHistory = new ArrayList<Set<GUID>>(); private List<LabelLocation> labelLocationList = new LinkedList<LabelLocation>(); private Set<Area> coveredTokenSet = new HashSet<Area>(); private Map<GUID, SelectionSet> selectionSetMap = new HashMap<GUID, SelectionSet>(); private Map<Token, TokenLocation> tokenLocationCache = new HashMap<Token, TokenLocation>(); private List<TokenLocation> markerLocationList = new ArrayList<TokenLocation>(); private GeneralPath facingArrow; private List<Token> showPathList = new ArrayList<Token>(); // Optimizations private Map<Token, BufferedImage> replacementImageMap = new HashMap<Token, BufferedImage>(); private Token tokenUnderMouse; private ScreenPoint pointUnderMouse; private Zone.Layer activeLayer; private Timer repaintTimer; private String loadingProgress; private boolean isLoaded; private BufferedImage fogBuffer; private boolean flushFog = true; private BufferedImage miniImage; private BufferedImage backbuffer; private boolean drawBackground = true; private int lastX; private int lastY; private BufferedImage cellShape; private double lastScale; private Area visibleScreenArea; // I don't like this, at all, but it'll work for now, basically keep track of when the fog cache // needs to be flushed in the case of switching views private PlayerView lastView; public ZoneRenderer(Zone zone) { if (zone == null) { throw new IllegalArgumentException("Zone cannot be null"); } this.zone = zone; zone.addModelChangeListener(new ZoneModelChangeListener()); setFocusable(true); setZoneScale(new Scale()); zoneView = new ZoneView(zone); // DnD new DropTarget(this, this); // Focus addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e) { requestFocusInWindow(); } @Override public void mouseExited(MouseEvent e) { pointUnderMouse = null; } @Override public void mouseEntered(MouseEvent e) { } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { pointUnderMouse = new ScreenPoint(e.getX(), e.getY()); } }); // fps.start(); } public void setRepaintTimer(Timer timer) { repaintTimer = timer; } public void showPath(Token token, boolean show) { if (show) { showPathList.add(token); } else { showPathList.remove(token); } } public ZonePoint getCenterPoint() { return new ScreenPoint(getSize().width/2, getSize().height/2).convertToZone(this); } public boolean isPathShowing(Token token) { return showPathList.contains(token); } public void clearShowPaths() { showPathList.clear(); repaint(); } public Scale getZoneScale() { return zoneScale; } public void setZoneScale(Scale scale) { zoneScale = scale; scale.addPropertyChangeListener (new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (Scale.PROPERTY_SCALE.equals(evt.getPropertyName())) { tokenLocationCache.clear(); flushFog = true; } if (Scale.PROPERTY_OFFSET.equals(evt.getPropertyName())) { // flushFog = true; } visibleScreenArea = null; repaint(); } }); } /** * I _hate_ this method. But couldn't think of a better way to tell the drawable renderer that a new image had arrived * TODO: FIX THIS ! Perhaps add a new app listener for when new images show up, add the drawable renderer as a listener */ public void flushDrawableRenderer() { backgroundDrawableRenderer.flush (); objectDrawableRenderer.flush(); tokenDrawableRenderer.flush(); gmDrawableRenderer.flush(); } public ScreenPoint getPointUnderMouse() { return pointUnderMouse; } public void setMouseOver(Token token) { if (tokenUnderMouse == token) { return; } tokenUnderMouse = token; repaint(); } @Override public boolean isOpaque() { return false; } public void addMoveSelectionSet (String playerId, GUID keyToken, Set<GUID> tokenList, boolean clearLocalSelected) { // I'm not supposed to be moving a token when someone else is already moving it if (clearLocalSelected) { for (GUID guid : tokenList) { selectedTokenSet.remove (guid); } } selectionSetMap.put (keyToken, new SelectionSet(playerId, keyToken, tokenList)); repaint(); } public boolean hasMoveSelectionSetMoved(GUID keyToken, ZonePoint point) { SelectionSet set = selectionSetMap.get (keyToken); if (set == null) { return false; } Token token = zone.getToken(keyToken); int x = point.x - token.getX(); int y = point.y - token.getY (); return set.offsetX != x || set.offsetY != y; } public void updateMoveSelectionSet (GUID keyToken, ZonePoint offset) { SelectionSet set = selectionSetMap.get(keyToken); if (set == null) { return; } Token token = zone.getToken(keyToken); // int tokenWidth = (int)(TokenSize.getWidth(token, zone.getGrid().getSize()) * getScale()); // int tokenHeight = (int)(TokenSize.getHeight(token, zone.getGrid().getSize()) * getScale()); // // // figure out screen bounds // ScreenPoint tsp = ScreenPoint.fromZonePoint(this, token.getX(), token.getY()); // ScreenPoint dsp = ScreenPoint.fromZonePoint(this, offset.x, offset.y); // ScreenPoint osp = ScreenPoint.fromZonePoint(this, token.getX() + set.offsetX, token.getY() + set.offsetY ); // // int strWidth = SwingUtilities.computeStringWidth(fontMetrics, set.getPlayerId()); // // int x = Math.min(tsp.x, dsp.x) - strWidth/2-4/*playername*/; // int y = Math.min (tsp.y, dsp.y); // int width = Math.abs(tsp.x - dsp.x)+ tokenWidth + strWidth+8/*playername*/; // int height = Math.abs(tsp.y - dsp.y)+ tokenHeight + 45/*labels*/; // Rectangle newBounds = new Rectangle(x, y, width, height); // // x = Math.min(tsp.x, osp.x) - strWidth/2-4/*playername*/; // y = Math.min(tsp.y, osp.y); // width = Math.abs(tsp.x - osp.x)+ tokenWidth + strWidth+8/*playername*/; // height = Math.abs(tsp.y - osp.y)+ tokenHeight + 45/*labels*/; // Rectangle oldBounds = new Rectangle(x, y, width, height); // // newBounds = newBounds.union(oldBounds); // set.setOffset (offset.x - token.getX(), offset.y - token.getY()); //repaint(newBounds.x, newBounds.y, newBounds.width, newBounds.height); repaint(); } public void toggleMoveSelectionSetWaypoint(GUID keyToken, ZonePoint location) { SelectionSet set = selectionSetMap.get(keyToken); if (set == null) { return; } set.toggleWaypoint(location); repaint(); } public void removeMoveSelectionSet (GUID keyToken) { SelectionSet set = selectionSetMap.remove(keyToken); if (set == null) { return; } repaint(); } public void commitMoveSelectionSet (GUID keyTokenId) { // TODO: Quick hack to handle updating server state SelectionSet set = selectionSetMap.get(keyTokenId); removeMoveSelectionSet(keyTokenId); MapTool.serverCommand().stopTokenMove(getZone().getId(), keyTokenId); Token keyToken = zone.getToken(keyTokenId); CellPoint originPoint = zone.getGrid().convert(new ZonePoint(keyToken.getX (), keyToken.getY())); Path path = set.getWalker() != null ? set.getWalker().getPath() : set.gridlessPath != null ? set.gridlessPath : null; for (GUID tokenGUID : set.getTokens()) { Token token = zone.getToken (tokenGUID); CellPoint tokenCell = zone.getGrid().convert(new ZonePoint(token.getX(), token.getY())); int cellOffX = originPoint.x - tokenCell.x; int cellOffY = originPoint.y - tokenCell.y; token.applyMove(set.getOffsetX(), set.getOffsetY(), path != null ? path.derive(cellOffX, cellOffY) : null); // No longer need this version replacementImageMap.remove(token); flush(token); MapTool.serverCommand().putToken(zone.getId(), token); zone.putToken(token); } MapTool.getFrame().updateTokenTree(); } public boolean isTokenMoving(Token token) { for (SelectionSet set : selectionSetMap.values()) { if (set.contains(token)) { return true; } } return false; } protected void setViewOffset(int x, int y) { zoneScale.setOffset(x, y); } public void centerOn(ZonePoint point) { int x = point.x; int y = point.y; x = getSize().width/2 - (int)(x*getScale())-1; y = getSize().height/2 - (int)(y*getScale())-1; setViewOffset(x, y); repaint(); } public void centerOn(CellPoint point) { centerOn(zone.getGrid().convert(point)); } public void flush(Token token) { tokenLocationCache.remove(token); // This should be smarter, but whatever visibleScreenArea = null; flushFog = true; } public ZoneView getZoneView() { return zoneView; } /** * Clear internal caches and backbuffers */ public void flush() { if (zone.getBackgroundPaint() instanceof DrawableTexturePaint) { ImageManager.flushImage(((DrawableTexturePaint)zone.getBackgroundPaint()).getAssetId()); } ImageManager.flushImage(zone.getMapAssetId()); flushDrawableRenderer(); replacementImageMap.clear(); fogBuffer = null; isLoaded = false; } public void flushFog() { flushFog = true; repaint(); } public Zone getZone() { return zone; } public void addOverlay(ZoneOverlay overlay) { overlayList.add(overlay); } public void removeOverlay(ZoneOverlay overlay) { overlayList.remove(overlay); } public void moveViewBy(int dx, int dy) { setViewOffset(getViewOffsetX() + dx, getViewOffsetY() + dy); } public void zoomReset() { zoneScale.reset(); MapTool.getFrame().getZoomStatusBar().update(); } public void zoomIn(int x, int y) { zoneScale.zoomIn(x, y); MapTool.getFrame().getZoomStatusBar().update(); } public void zoomOut(int x, int y) { zoneScale.zoomOut(x, y); MapTool.getFrame().getZoomStatusBar().update(); } public void setView(int x, int y, double scale) { setViewOffset(x, y); zoneScale.setScale(scale); MapTool.getFrame().getZoomStatusBar().update(); } public BufferedImage getMiniImage(int size) { // if (miniImage == null && getTileImage() != ImageManager.UNKNOWN_IMAGE) { // miniImage = new BufferedImage(size, size, Transparency.OPAQUE); // Graphics2D g = miniImage.createGraphics(); // g.setPaint(new TexturePaint(getTileImage(), new Rectangle(0, 0, miniImage.getWidth(), miniImage.getHeight()))); // g.fillRect(0, 0, size, size); // g.dispose(); // } return miniImage; } public void paintComponent(Graphics g) { if (repaintTimer != null) { repaintTimer.restart(); } Graphics2D g2d = (Graphics2D) g; Player.Role role = MapTool.getPlayer().getRole(); if (role == Player.Role.GM && AppState.isShowAsPlayer()) { role = Player.Role.PLAYER; } renderZone(g2d, new PlayerView(role)); if (!zone.isVisible()) { GraphicsUtil.drawBoxedString(g2d, "Map not visible to players", getSize().width/2, 20); } if (AppState.isShowAsPlayer()) { GraphicsUtil.drawBoxedString(g2d, "Player View", getSize().width/2, 20); } } CodeTimer timer; public void renderZone(Graphics2D g2d, PlayerView view) { timer = new CodeTimer("zonerenderer"); timer.start("setup"); g2d.setFont(AppStyle.labelFont); Object oldAA = SwingUtil.useAntiAliasing(g2d); // Are we still waiting to show the zone ? if (isLoading()) { Dimension size = getSize(); g2d.setColor(Color.black); g2d.fillRect(0, 0, size.width , size.height); GraphicsUtil.drawBoxedString(g2d, loadingProgress, size.width/2, size.height/2); return; } if (MapTool.getCampaign ().isBeingSerialized()) { Dimension size = getSize(); g2d.setColor(Color.black); g2d.fillRect(0, 0, size.width, size.height); GraphicsUtil.drawBoxedString (g2d, " Please Wait ", size.width/2, size.height/2); return; } if (zone == null) { return; } // Clear internal state tokenLocationMap.clear(); coveredTokenSet.clear(); markerLocationList.clear(); timer.stop("setup"); // Calculations timer.start("calcs"); if (zoneView.isUsingVision() && zoneView.getVisibleArea(view) != null && visibleScreenArea == null) { AffineTransform af = new AffineTransform(); af.translate(zoneScale.getOffsetX(), zoneScale.getOffsetY()); af.scale(getScale(), getScale()); visibleScreenArea = new Area(zoneView.getVisibleArea(view).createTransformedArea(af)); } timer.stop("calcs"); // Rendering pipeline timer.start("board"); renderBoard(g2d, view); timer.stop("board"); timer.start("drawableOverlay"); renderDrawableOverlay(g2d, backgroundDrawableRenderer, view, zone.getBackgroundDrawnElements()); timer.stop("drawableOverlay"); timer.start("tokensBackground"); renderTokens(g2d, zone.getBackgroundStamps(), view); timer.stop("tokensBackground"); timer.start("drawableOverlay2"); renderDrawableOverlay(g2d, objectDrawableRenderer, view, zone.getObjectDrawnElements()); timer.stop("drawableOverlay2"); timer.start("lights"); renderLights(g2d, view); timer.stop("lights"); timer.start("templates"); renderTokenTemplates(g2d, view); timer.stop("templates"); timer.start("grid"); renderGrid(g2d, view); timer.stop("grid"); timer.start("drawableOverlay3"); if (view.isGMView()) { renderTokens(g2d, zone.getGMStamps(), view); renderDrawableOverlay(g2d, gmDrawableRenderer, view, zone.getGMDrawnElements()); } timer.stop("drawableOverlay3"); timer.start("tokensStamp"); renderTokens(g2d, zone.getStampTokens(), view); timer.stop("tokensStamp"); timer.start("drawableOverlay4"); renderDrawableOverlay(g2d, tokenDrawableRenderer, view, zone.getDrawnElements()); timer.stop("drawableOverlay4"); timer.start("visionOverlay"); renderPlayerVisionOverlay(g2d, view); timer.stop("visionOverlay"); timer.start("tokens"); renderTokens(g2d, zone.getTokens(), view); timer.stop("tokens"); timer.start("movement"); renderMoveSelectionSets(g2d, view); timer.stop("movement"); timer.start("labels"); renderLabels(g2d, view); timer.stop("labels"); timer.start("fog"); renderFog(g2d, view); timer.stop("fog"); timer.start("visionOverlayGM"); renderGMVisionOverlay(g2d, view); timer.stop("visionOverlayGM"); timer.start("overlays"); for (int i = 0; i < overlayList.size(); i++) { ZoneOverlay overlay = overlayList.get(i); overlay.paintOverlay(this, g2d); } timer.stop("overlays"); renderCoordinates(g2d, view); // if (lightSourceArea != null) { // g2d.setColor(Color.yellow); // g2d.fill(lightSourceArea.createTransformedArea(AffineTransform.getScaleInstance (getScale(), getScale()))); // } // // g2d.setColor(Color.red); // for (AreaMeta meta : getTopologyAreaData().getAreaList()) { // // Area area = new Area(meta.getArea().getBounds()).createTransformedArea(AffineTransform.getScaleInstance (getScale(), getScale())); // area = area.createTransformedArea(AffineTransform.getTranslateInstance(zoneScale.getOffsetX(), zoneScale.getOffsetY())); // g2d.draw(area); // } SwingUtil.restoreAntiAliasing(g2d, oldAA); // System.out.println(timer); lastView = view; } private void renderLights(Graphics2D g, PlayerView view) { // Setup Graphics2D newG = (Graphics2D)g.create(); Area clip = new Area(g.getClip()); if (visibleScreenArea != null) { clip.intersect(visibleScreenArea); } newG.setClip(clip); SwingUtil.useAntiAliasing(newG); AffineTransform af = g.getTransform(); af.translate(getViewOffsetX(), getViewOffsetY()); af.scale(getScale(), getScale()); newG.setTransform(af); newG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, AppPreferences.getVisionOverlayOpacity()/255.0f)); // Organize Map<Paint, List<Area>> colorMap = new HashMap<Paint, List<Area>>(); for (DrawableLight light : zoneView.getDrawableLights()) { List<Area> areaList = colorMap.get(light.getPaint().getPaint()); if (areaList == null) { areaList = new ArrayList<Area>(); colorMap.put(light.getPaint().getPaint(), areaList); } areaList.add(new Area(light.getArea())); } // Combine same colors to avoid ugly overlap for (List<Area> areaList : colorMap.values()) { while (areaList.size() > 1) { Area a1 = areaList.remove(0); Area a2 = areaList.remove(0); a1.add(a2); areaList.add(a1); } // Cut out the bright light if (areaList.size() > 0) { Area area = areaList.get(0); for (Area brightArea : zoneView.getBrightLights()) { area.subtract(brightArea); } } } // Draw for (Entry<Paint, List<Area>> entry : colorMap.entrySet()) { newG.setPaint(entry.getKey()); for (Area area : entry.getValue()) { newG.fill(area); } } } private void renderPlayerVisionOverlay(Graphics2D g, PlayerView view) { if (!view.isGMView()) { renderVisionOverlay(g, view); } } private void renderGMVisionOverlay(Graphics2D g, PlayerView view) { if (view.isGMView()) { renderVisionOverlay(g, view); } } private void renderVisionOverlay(Graphics2D g, PlayerView view) { Area currentTokenVisionArea = zoneView.getVisibleArea(tokenUnderMouse); if (currentTokenVisionArea == null) { return; } AffineTransform af = new AffineTransform(); af.translate(zoneScale.getOffsetX(), zoneScale.getOffsetY()); af.scale(getScale(), getScale()); Area area = currentTokenVisionArea.createTransformedArea(af); SwingUtil.useAntiAliasing(g); g.setColor(new Color(200, 200, 200)); g.draw(area); boolean useHaloColor = tokenUnderMouse.getHaloColor() != null && AppPreferences.getUseHaloColorOnVisionOverlay(); if (tokenUnderMouse.getVisionOverlayColor() != null || useHaloColor) { Color visionColor = useHaloColor ? tokenUnderMouse.getHaloColor() : tokenUnderMouse.getVisionOverlayColor(); g.setColor(new Color(visionColor.getRed(), visionColor.getGreen(), visionColor.getBlue(), AppPreferences.getVisionOverlayOpacity())); g.fill(area); } } private void renderPlayerVision(Graphics2D g, PlayerView view) { // Object oldAntiAlias = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING ); // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // // // // if (currentTokenVisionArea != null && !view.isGMView()) { // // Draw the outline under the fog // g.setColor(new Color(200, 200, 200)); // g.draw(currentTokenVisionArea); // } // // g.setRenderingHint(RenderingHints.KEY_ANTIALIASING , oldAntiAlias); } /** * Paint all of the token templates for selected tokens. * * @param g Paint on this graphic object. */ private void renderTokenTemplates(Graphics2D g, PlayerView view) { double scale = zoneScale.getScale(); int scaledGridSize = (int) getScaledGridSize(); // Find tokens with template state // TODO: I really don't like this, it should be optimized AffineTransform old = g.getTransform(); AffineTransform t = new AffineTransform(); g.setTransform(t); for (Token token : zone.getAllTokens()) { for (String state : token.getStatePropertyNames()) { Object value = token.getState(state); if (value instanceof TokenTemplate) { // Only show if selected if (!AppState.isShowLightRadius()) { continue; } // Calculate the token bounds Rectangle size = token.getBounds(zone); int width = (int) (size.width * scale) - 1; int height = (int) (size.height * scale) - 1; ScreenPoint tokenScreenLocation = ScreenPoint.fromZonePointRnd(this, token.getX(), token.getY()); int x = (int)(tokenScreenLocation.x + 1); int y = (int)(tokenScreenLocation.y); if (width < scaledGridSize) { x += (scaledGridSize - width) / 2; } if (height < scaledGridSize) { y += (scaledGridSize - height) / 2; } Rectangle bounds = new Rectangle(x, y, width, height); // Set up the graphics, paint the template, restore the graphics t.setTransform(old); t.translate(bounds.x, bounds.y); t.scale(getScale(), getScale()); g.setTransform(t); ((TokenTemplate)value).paintTemplate(g, token, bounds, this); } } } g.setTransform(old); } private void renderLabels(Graphics2D g, PlayerView view) { labelLocationList.clear(); for (Label label : zone.getLabels()) { ZonePoint zp = new ZonePoint(label.getX(), label.getY()); if (!zone.isPointVisible(zp, view.getRole())) { continue; } ScreenPoint sp = ScreenPoint.fromZonePointRnd(this, zp.x, zp.y); Rectangle bounds = null; if (label.isShowBackground()) { bounds = GraphicsUtil.drawBoxedString(g, label.getLabel(), (int)sp.x, (int)sp.y, SwingUtilities.CENTER, GraphicsUtil.GREY_LABEL, label.getForegroundColor()); } else { FontMetrics fm = g.getFontMetrics(); int strWidth = SwingUtilities.computeStringWidth(fm, label.getLabel()); int x = (int)(sp.x - strWidth/2); int y = (int)(sp.y - fm.getAscent()); g.setColor(label.getForegroundColor()); g.drawString(label.getLabel(), x, y + fm.getAscent()); bounds = new Rectangle(x, y, strWidth, fm.getHeight()); } labelLocationList.add(new LabelLocation(bounds, label)); } } Integer fogX = null; Integer fogY = null; private void renderFog(Graphics2D g, PlayerView view) { if (!zone.hasFog()) { return; } if (lastView == null || view.isGMView() != lastView.isGMView()) { flushFog = true; } Dimension size = getSize(); // Optimization for panning Area fogClip = null; if (!flushFog && fogX != null && fogY != null && (fogX != getViewOffsetX() || fogY != getViewOffsetY())) { // This optimization does not seem to keep the alpha channel correctly, and sometimes leaves // lines on some graphics boards, we'll leave it out for now // if (Math.abs(fogX - getViewOffsetX()) < size.width && Math.abs(fogY - getViewOffsetY()) < size.height) { // int deltaX = getViewOffsetX() - fogX; // int deltaY = getViewOffsetY() - fogY; // // Graphics2D buffG = fogBuffer.createGraphics(); // // buffG.setComposite(AlphaComposite.Src); // buffG.copyArea(0, 0, size.width, size.height, deltaX, deltaY); // // buffG.dispose(); // // fogClip = new Area(); // if (deltaX < 0) { // fogClip.add(new Area(new Rectangle(size.width+deltaX, 0, -deltaX, size.height))); // } else if (deltaX > 0){ // fogClip.add(new Area(new Rectangle(0, 0, deltaX, size.height))); // } // // if (deltaY < 0) { // fogClip.add(new Area(new Rectangle(0, size.height + deltaY, size.width, -deltaY))); // } else if (deltaY > 0) { // fogClip.add(new Area(new Rectangle(0, 0, size.width, deltaY))); // } // // } flushFog = true; } if (flushFog || fogBuffer == null || fogBuffer.getWidth() != size.width || fogBuffer.getHeight() != size.height) { fogX = getViewOffsetX(); fogY = getViewOffsetY(); boolean newImage = false; if (fogBuffer == null || fogBuffer.getWidth() != size.width || fogBuffer.getHeight() != size.height) { newImage = true; fogBuffer = new BufferedImage(size.width, size.height, view.isGMView() ? Transparency.TRANSLUCENT : Transparency.BITMASK); } Graphics2D buffG = fogBuffer.createGraphics(); buffG.setClip(fogClip != null ? fogClip : new Rectangle(0, 0, size.width, size.height)); SwingUtil.useAntiAliasing(buffG); if (!newImage){ Composite oldComposite = buffG.getComposite(); buffG.setComposite(AlphaComposite.Clear); buffG.fillRect(0, 0, size.width, size.height); buffG.setComposite(oldComposite); } // Fill buffG.setPaint(zone.getFogPaint().getPaint(getViewOffsetX(), getViewOffsetY(), getScale())); buffG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, view.isGMView() ? .6f : 1f)); buffG.fillRect(0, 0, size.width, size.height); // Cut out the exposed area AffineTransform af = new AffineTransform(); af.translate(getViewOffsetX(), getViewOffsetY()); af.scale(getScale(), getScale()); buffG.setTransform(af); buffG.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR)); buffG.fill(zone.getExposedArea()); // Soft fog if (zoneView.isUsingVision()) { buffG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC)); Area visibleArea = zoneView.getVisibleArea(view); if (visibleArea != null) { buffG.setColor(new Color(0, 0, 0, 100)); if (zone.hasFog ()) { // Fill in the exposed area buffG.fill(zone.getExposedArea()); buffG.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR)); Shape oldClip = buffG.getClip(); buffG.setClip(zone.getExposedArea()); buffG.fill(visibleArea); buffG.setClip(oldClip); } else { buffG.setColor(new Color(255, 255, 255, 40)); buffG.fill(visibleArea); } } else { if (zone.hasFog()) { buffG.setColor(new Color(0, 0, 0, 80)); buffG.fill(zone.getExposedArea()); } } } // Outline if (false && AppPreferences.getUseSoftFogEdges()) { GraphicsUtil.renderSoftClipping(buffG, zone.getExposedArea(), (int)(zone.getGrid().getSize() * getScale()*.25), view.isGMView() ? .6 : 1); } else { buffG.setTransform(new AffineTransform()); buffG.setComposite(AlphaComposite.Src); buffG.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); buffG.setStroke(new BasicStroke(1)); buffG.setColor(Color.black); buffG.draw(zone.getExposedArea().createTransformedArea(af)); } buffG.dispose(); flushFog = false; } g.drawImage(fogBuffer, 0, 0, this); } public Area getVisibleArea(Token token) { return zoneView.getVisibleArea(token); } public boolean isLoading() { if (isLoaded) { // We're done, until the cache is cleared return false; } // Get a list of all the assets in the zone Set<MD5Key> assetSet = zone.getAllAssetIds(); assetSet.remove(null); // remove bad data // Make sure they are loaded int downloadCount = 0; int cacheCount = 0; boolean loaded = true; for (MD5Key id : assetSet) { // Have we gotten the actual data yet ? Asset asset = AssetManager.getAsset(id); if (asset == null) { loaded = false; continue; } downloadCount ++; // Have we loaded the image into memory yet ? Image image = ImageManager.getImage(asset, new ImageObserver[]{}); if (image == null || image == ImageManager.UNKNOWN_IMAGE ) { loaded = false; continue; } cacheCount ++; } loadingProgress = String.format(" Loading Map '%s' - %d/%d Loaded %d/%d Cached", zone.getName(), downloadCount, assetSet.size(), cacheCount, assetSet.size()); isLoaded = loaded; if (isLoaded) { // Notify the token tree that it should update MapTool.getFrame().updateTokenTree(); } return !isLoaded; } protected void renderDrawableOverlay(Graphics g, DrawableRenderer renderer, PlayerView view, List<DrawnElement> drawnElements) { Rectangle viewport = new Rectangle(zoneScale.getOffsetX (), zoneScale.getOffsetY(), getSize().width, getSize().height); List<DrawnElement> list = new ArrayList<DrawnElement>(); list.addAll(drawnElements); renderer.renderDrawables (g, list, viewport, getScale()); } protected void renderBoard(Graphics2D g, PlayerView view) { Dimension size = getSize(); if (backbuffer == null || backbuffer.getWidth() != size.width || backbuffer.getHeight() != size.height) { backbuffer = new BufferedImage(size.width, size.height, Transparency.OPAQUE); drawBackground = true; } Scale scale = getZoneScale(); if (scale.getOffsetX() != lastX || scale.getOffsetY() != lastY || scale.getScale() != lastScale) { drawBackground = true; } if (drawBackground) { Graphics2D bbg = backbuffer.createGraphics(); // Background texture Paint paint = zone.getBackgroundPaint().getPaint(getViewOffsetX(), getViewOffsetY(), getScale()); bbg.setPaint(paint); bbg.fillRect(0, 0, size.width, size.height); // Map if (zone.getMapAssetId() != null) { BufferedImage mapImage = ImageManager.getImage(AssetManager.getAsset(zone.getMapAssetId()), this); bbg.drawImage(mapImage, getViewOffsetX(), getViewOffsetY(), (int)(mapImage.getWidth()*getScale()), (int)(mapImage.getHeight()*getScale()), null); } bbg.dispose(); drawBackground = false; } lastX = scale.getOffsetX(); lastY = scale.getOffsetY(); lastScale = scale.getScale(); g.drawImage(backbuffer, 0, 0, this); } protected void renderGrid(Graphics2D g, PlayerView view) { int gridSize = (int) ( zone.getGrid().getSize() * getScale()); if (!AppState.isShowGrid() || gridSize < MIN_GRID_SIZE) { return; } zone.getGrid().draw(this, g, g.getClipBounds()); } protected void renderCoordinates(Graphics2D g, PlayerView view) { if (AppState.isShowCoordinates()) { zone.getGrid().drawCoordinatesOverlay(g, this); } } protected void renderMoveSelectionSets(Graphics2D g, PlayerView view) { Grid grid = zone.getGrid(); double scale = zoneScale.getScale(); Set<SelectionSet> selections = new HashSet<SelectionSet>(); selections.addAll(selectionSetMap.values()); for (SelectionSet set : selections) { Token keyToken = zone.getToken(set.getKeyToken()); ZoneWalker walker = set.getWalker(); // Hide the hidden layer if (keyToken.getLayer() == Zone.Layer.GM && !view.isGMView()) { continue; } for (GUID tokenGUID : set.getTokens()) { Token token = zone.getToken(tokenGUID); boolean isOwner = token.isOwner(MapTool.getPlayer().getName()); // Perhaps deleted ? if (token == null) { continue; } // Don't bother if it's not visible if (!token.isVisible() && !view.isGMView()) { continue; } Asset asset = AssetManager.getAsset(token.getImageAssetId()); if (asset == null) { continue; } // OPTIMIZE: combine this with the code in renderTokens() Rectangle footprintBounds = token.getBounds(zone); ScreenPoint newScreenPoint = ScreenPoint.fromZonePoint(this, footprintBounds.x + set.getOffsetX(), footprintBounds.y + set.getOffsetY()); BufferedImage image = ImageManager.getImage(AssetManager.getAsset(token.getImageAssetId())); int scaledWidth = (int)(footprintBounds.width * scale); int scaledHeight = (int)(footprintBounds.height * scale); // Tokens are centered on the image center point int x = (int)(newScreenPoint.x); int y = (int)(newScreenPoint.y); // Vision visibility Rectangle clip = g.getClipBounds(); if (!view.isGMView() && !isOwner && zoneView.isUsingVision() && visibleScreenArea != null) { // Only show the part of the path that is visible Area clipArea = new Area(clip); clipArea.intersect(visibleScreenArea); g.setClip(clipArea); } // Show path only on the key token if (token == keyToken) { if (!token.isStamp()) { if (!token.isObjectStamp() && zone.getGrid().getCapabilities().isPathingSupported() && token.isSnapToGrid()) { renderPath(g, walker.getPath(), token.getFootprint(zone.getGrid())); } else { // Line Color highlight = new Color(255, 255, 255, 80); Stroke highlightStroke = new BasicStroke(9); Stroke oldStroke = g.getStroke(); Object oldAA = SwingUtil.useAntiAliasing(g); ScreenPoint lastPoint = ScreenPoint.fromZonePointRnd(this, token.getX()+footprintBounds.width/2, token.getY()+footprintBounds.height/2); for (ZonePoint zp : set.gridlessPath.getCellPath()) { ScreenPoint nextPoint = ScreenPoint.fromZonePoint(this, zp.x, zp.y); g.setColor(highlight); g.setStroke(highlightStroke); g.drawLine((int)lastPoint.x, (int)lastPoint.y , (int)nextPoint.x, (int)nextPoint.y); g.setStroke(oldStroke); g.setColor(Color.blue); g.drawLine((int)lastPoint.x, (int)lastPoint.y , (int)nextPoint.x, (int)nextPoint.y); lastPoint = nextPoint; } g.setColor(highlight); g.setStroke(highlightStroke); g.drawLine((int)lastPoint.x, (int)lastPoint.y, x + scaledWidth/2, y + scaledHeight/2); g.setStroke(oldStroke); g.setColor(Color.blue); g.drawLine((int)lastPoint.x, (int)lastPoint.y, x + scaledWidth/2, y + scaledHeight/2); SwingUtil.restoreAntiAliasing(g, oldAA); // Waypoints for (ZonePoint p : set.gridlessPath.getCellPath()) { p = new ZonePoint(p.x, p.y); highlightCell(g, p, AppStyle.cellWaypointImage, .333f); } } } } // handle flipping BufferedImage workImage = image; if (token.isFlippedX() || token.isFlippedY()) { workImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getTransparency()); int workW = image.getWidth() * (token.isFlippedX() ? -1 : 1); int workH = image.getHeight() * (token.isFlippedY() ? -1 : 1); int workX = token.isFlippedX() ? image.getWidth() : 0; int workY = token.isFlippedY() ? image.getHeight() : 0; Graphics2D wig = workImage.createGraphics(); wig.drawImage(image, workX, workY, workW, workH, null); wig.dispose(); } // Draw token Dimension imgSize = new Dimension(workImage.getWidth(), workImage.getHeight()); SwingUtil.constrainTo(imgSize, footprintBounds.width, footprintBounds.height); int offsetx = 0; int offsety = 0; if (token.isSnapToScale()) { offsetx = (int)(imgSize.width < footprintBounds.width ? (footprintBounds.width - imgSize.width)/2 * getScale() : 0); offsety = (int)(imgSize.height < footprintBounds.height ? (footprintBounds.height - imgSize.height)/2 * getScale() : 0); } int tx = x + offsetx; int ty = y + offsety; AffineTransform at = new AffineTransform(); at.translate(tx, ty); if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) { at.rotate(Math.toRadians (-token.getFacing() - 90), scaledWidth/2 - token.getAnchor().x*scale - offsetx, scaledHeight/2 - token.getAnchor().y*scale - offsety); // facing defaults to down, or -90 degrees } if (token.isSnapToScale()) { at.scale((double) imgSize.width / workImage.getWidth(), (double) imgSize.height / workImage.getHeight()); at.scale(getScale(), getScale()); } else { at.scale((double) scaledWidth / workImage.getWidth(), (double) scaledHeight / workImage.getHeight()); } g.drawImage(workImage, at, this); // Other details if (token == keyToken) { // if the token is visible on the screen it will be in the location cache if (tokenLocationCache.containsKey(token)) { y += 10 + scaledHeight; x += scaledWidth/2; if (!token.isStamp()) { if (AppState.getShowMovementMeasurements ()) { String distance = ""; if (zone.getGrid().getCapabilities().isPathingSupported() && token.isSnapToGrid()) { if (walker.getDistance() >= 1) { distance = Integer.toString(walker.getDistance()); } } else { double c = 0; ZonePoint lastPoint = new ZonePoint(token.getX()+footprintBounds.width/2, token.getY()+footprintBounds.height/2); for (ZonePoint zp : set.gridlessPath.getCellPath()) { int a = lastPoint.x - zp.x; int b = lastPoint.y - zp.y; c += Math.hypot(a, b); lastPoint = zp; } ZonePoint finalPoint = new ZonePoint((set.offsetX + token.getX())+footprintBounds.width/2, (set.offsetY + token.getY())+footprintBounds.height/2); int a = lastPoint.x - finalPoint.x; int b = lastPoint.y - finalPoint.y; c += Math.hypot(a, b); c /= zone.getGrid().getSize(); // Number of "cells" c *= zone.getUnitsPerCell(); // "actual" distance traveled distance = String.format("%.1f", c); } if (distance.length() > 0) { GraphicsUtil.drawBoxedString(g, distance, x, y); y += 20; } } } if (set.getPlayerId() != null && set.getPlayerId().length() >= 1) { GraphicsUtil.drawBoxedString (g, set.getPlayerId(), x, y); } } } g.setClip(clip); } } } public void renderPath(Graphics2D g, Path path, TokenFootprint footprint) { Object oldRendering = g.getRenderingHint(RenderingHints.KEY_ANTIALIASING); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); CellPoint previousPoint = null; Point previousHalfPoint = null; Grid grid = zone.getGrid(); double scale = getScale(); Rectangle footprintBounds = footprint.getBounds(grid); List<CellPoint> cellPath = path.getCellPath(); Set<CellPoint> pathSet = new HashSet<CellPoint>(); List<ZonePoint> waypointList = new LinkedList<ZonePoint>(); for (CellPoint p : cellPath) { pathSet.addAll(footprint.getOccupiedCells(p)); if (path.isWaypoint(p) && previousPoint != null) { ZonePoint zp = grid.convert(p); zp.x += footprintBounds.width/2; zp.y += footprintBounds.height/2; waypointList.add(zp); } previousPoint = p; } // Don't show the final path point as a waypoint, it's redundant, and ugly if (waypointList.size() > 0) { waypointList.remove(waypointList.size()-1); } Dimension cellOffset = zone.getGrid().getCellOffset(); for (CellPoint p : pathSet) { ZonePoint zp = grid.convert(p); zp.x += grid.getCellWidth()/2 + cellOffset.width; zp.y += grid.getCellHeight()/2 + cellOffset.height; highlightCell(g, zp, grid.getCellHighlight(), 1.0f); } for (ZonePoint p : waypointList) { ZonePoint zp = new ZonePoint(p.x + cellOffset.width, p.y + cellOffset.height); highlightCell(g, zp, AppStyle.cellWaypointImage, .333f); } // Line path if (grid.getCapabilities().isPathLineSupported() ) { ZonePoint lineOffset = new ZonePoint(footprintBounds.x + footprintBounds.width/2 - grid.getOffsetX(), footprintBounds.y + footprintBounds.height/2 - grid.getOffsetY()); int xOffset = (int)(lineOffset.x * scale); int yOffset = (int)(lineOffset.y * scale); g.setColor(Color.blue); previousPoint = null; for (CellPoint p : cellPath) { if (previousPoint != null) { ZonePoint ozp = grid.convert(previousPoint); int ox = ozp.x; int oy = ozp.y; ZonePoint dzp = grid.convert(p); int dx = dzp.x; int dy = dzp.y; ScreenPoint origin = ScreenPoint.fromZonePoint(this, ox, oy); ScreenPoint destination = ScreenPoint.fromZonePoint(this, dx, dy); int halfx = (int)(( origin.x + destination.x)/2); int halfy = (int)((origin.y + destination.y)/2); Point halfPoint = new Point(halfx, halfy); if (previousHalfPoint != null) { int x1 = previousHalfPoint.x+xOffset; int y1 = previousHalfPoint.y+yOffset; int x2 = (int)origin.x+xOffset; int y2 = (int)origin.y+yOffset; int xh = halfPoint.x+xOffset; int yh = halfPoint.y+yOffset; QuadCurve2D curve = new QuadCurve2D.Float(x1, y1, x2, y2, xh, yh); g.draw(curve); } previousHalfPoint = halfPoint; } previousPoint = p; } } g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldRendering); } public void highlightCell(Graphics2D g, ZonePoint point, BufferedImage image, float size) { Grid grid = zone.getGrid(); double cwidth = grid.getCellWidth() * getScale(); double cheight = grid.getCellHeight() * getScale(); double iwidth = cwidth * size; double iheight = cheight * size; ScreenPoint sp = ScreenPoint.fromZonePoint(this, point); g.drawImage (image, (int)(sp.x - iwidth/2), (int)(sp.y - iheight/2), (int)iwidth, (int)iheight, this); } /** * Get a list of tokens currently visible on the screen. The list is ordered by location starting * in the top left and going to the bottom right * @return */ public List<Token> getTokensOnScreen() { List<Token> list = new ArrayList<Token>(); // Always assume tokens, for now List<TokenLocation> tokenLocationListCopy = new ArrayList<TokenLocation>(); tokenLocationListCopy.addAll(getTokenLocations(Zone.Layer.TOKEN)); for (TokenLocation location : tokenLocationListCopy) { list.add(location.token); } // Sort by location on screen, top left to bottom right Collections.sort(list, new Comparator<Token>(){ public int compare(Token o1, Token o2) { if (o1.getY() < o2.getY()) { return -1; } if (o1.getY() > o2.getY()) { return 1; } if (o1.getX() < o2.getX()) { return -1; } if (o1.getX() > o2.getX()) { return 1; } return 0; } }); return list; } public Zone.Layer getActiveLayer() { return activeLayer != null ? activeLayer : Zone.Layer.TOKEN; } public void setActiveLayer(Zone.Layer layer) { activeLayer = layer; selectedTokenSet.clear(); repaint(); } /** * Get the token locations for the given layer, creates an empty list * if there are not locations for the given layer */ private List<TokenLocation> getTokenLocations(Zone.Layer layer) { List<TokenLocation> list = tokenLocationMap.get(layer); if (list != null) { return list; } list = new LinkedList<TokenLocation>(); tokenLocationMap.put(layer, list); return list; } // TODO: I don't like this hardwiring protected Shape getCircleFacingArrow(int angle, int size) { int base = (int)(size * .75); int width = (int)(size * .35); facingArrow = new GeneralPath(); facingArrow.moveTo(base, -width); facingArrow.lineTo(size, 0); facingArrow.lineTo(base, width); facingArrow.lineTo(base, -width); return ((GeneralPath)facingArrow.createTransformedShape( AffineTransform.getRotateInstance(-Math.toRadians(angle)))).createTransformedShape(AffineTransform.getScaleInstance(getScale(), getScale())); } // TODO: I don't like this hardwiring protected Shape getSquareFacingArrow(int angle, int size) { int base = (int)(size * .75); int width = (int)(size * .35); facingArrow = new GeneralPath(); facingArrow.moveTo(0, 0); facingArrow.lineTo(-(size - base), -width); facingArrow.lineTo(-(size - base), width); facingArrow.lineTo(0, 0); return ((GeneralPath)facingArrow.createTransformedShape(AffineTransform.getRotateInstance(-Math.toRadians(angle)))).createTransformedShape( AffineTransform.getScaleInstance(getScale(), getScale())); } protected void renderTokens(Graphics2D g, List<Token> tokenList, PlayerView view) { Graphics2D clippedG = g; timer.start("createClip"); if (!view.isGMView() && visibleScreenArea != null && tokenList.size() > 0 && tokenList.get(0).isToken()) { clippedG = (Graphics2D)g.create(); Area visibleArea = new Area(g.getClipBounds()); visibleArea.intersect(visibleScreenArea); clippedG.setClip(new GeneralPath(visibleArea)); } timer.stop("createClip"); Rectangle viewport = new Rectangle(0, 0, getSize().width, getSize().height); Rectangle clipBounds = g.getClipBounds(); double scale = zoneScale.getScale(); for (Token token : tokenList) { if (token.isStamp() && isTokenMoving(token)) { continue; } TokenLocation location = tokenLocationCache.get(token); if (location != null && !location.maybeOnscreen(viewport)) { continue; } // Don't bother if it's not visible // NOTE: Not going to use zone.isTokenVisible as it is very slow. In fact, it's faster // to just draw the tokens and let them be clipped if (!token.isVisible() && !view.isGMView()) { continue; } Rectangle footprintBounds = token.getBounds(zone); BufferedImage image = null; Asset asset = AssetManager.getAsset(token.getImageAssetId ()); if (asset == null) { // In the mean time, show a placeholder image = ImageManager.UNKNOWN_IMAGE; } else { image = ImageManager.getImage(AssetManager.getAsset(token.getImageAssetId()), this); } double scaledWidth = (footprintBounds.width*scale); double scaledHeight = (footprintBounds.height*scale); // if (!token.isStamp()) { // // Fit inside the grid // scaledWidth --; // scaledHeight --; // } ScreenPoint tokenScreenLocation = ScreenPoint.fromZonePoint (this, footprintBounds.x, footprintBounds.y); // Tokens are centered on the image center point double x = tokenScreenLocation.x; double y = tokenScreenLocation.y; Rectangle2D origBounds = new Rectangle2D.Double(x, y, scaledWidth, scaledHeight); Area tokenBounds = new Area(origBounds); if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) { tokenBounds.transform(AffineTransform.getRotateInstance(Math.toRadians(-token.getFacing() - 90), scaledWidth/2 + x - (token.getAnchor().x*scale), scaledHeight/2 + y - (token.getAnchor().y*scale))); // facing defaults to down, or -90 degrees } location = new TokenLocation(tokenBounds, origBounds, token, x, y, footprintBounds.width, footprintBounds.height, scaledWidth, scaledHeight); tokenLocationCache.put(token, location); // General visibility if (!view.isGMView() && !token.isVisible()) { continue; } // Vision visibility if (!view.isGMView() && token.isToken() && zoneView.isUsingVision()) { if (!visibleScreenArea.getBounds().intersects(location.boundsCache)) { continue; } } // Markers if (token.isMarker() && canSeeMarker(token)) { markerLocationList.add(location); } if (!location.bounds.intersects(clipBounds)) { // Not on the screen, don't have to worry about it continue; } // Stacking check if (!token.isStamp()) { for (TokenLocation currLocation : getTokenLocations(Zone.Layer.TOKEN)) { Area r1 = currLocation.bounds; // Are we covering anyone ? if (location.boundsCache.contains(currLocation.boundsCache) && GraphicsUtil.contains(location.bounds, r1)) { // Are we covering someone that is covering someone ? Area oldRect = null; for (Area r2 : coveredTokenSet) { if (location.bounds.getBounds().contains(r2.getBounds ())) { oldRect = r2; break; } } if (oldRect != null) { coveredTokenSet.remove(oldRect); } coveredTokenSet.add(location.bounds); } } } // Keep track of the location on the screen // Note the order where the top most token is at the end of the list List<TokenLocation> locationList = null; if (!token.isStamp()) { locationList = getTokenLocations(Zone.Layer.TOKEN); } else { if (token.isObjectStamp()) { locationList = getTokenLocations(Zone.Layer.OBJECT); } if (token.isBackgroundStamp()) { locationList = getTokenLocations(Zone.Layer.BACKGROUND); } if (token.isGMStamp()) { locationList = getTokenLocations(Zone.Layer.GM); } } if (locationList != null) { locationList.add(location); } // Only draw if we're visible // NOTE: this takes place AFTER resizing the image, that's so that the user // sufferes a pause only once while scaling, and not as new tokens are // scrolled onto the screen if (!location.bounds.intersects(clipBounds)) { continue; } // Moving ? if (isTokenMoving(token)) { BufferedImage replacementImage = replacementImageMap.get(token); if (replacementImage == null) { replacementImage = ImageUtil.rgbToGrayscale(image); replacementImageMap.put(token, replacementImage); } image = replacementImage; } // Previous path if (showPathList.contains(token) && token.getLastPath() != null) { renderPath(g, token.getLastPath(), token.getFootprint(zone.getGrid())); } // Halo (TOPDOWN, CIRCLE) if (token.hasHalo() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.getShape() == Token.TokenShape.CIRCLE)) { Stroke oldStroke = clippedG.getStroke(); clippedG.setStroke( new BasicStroke(AppPreferences.getHaloLineWidth())); clippedG.setColor(token.getHaloColor()); clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight)); clippedG.setStroke(oldStroke); } // handle flipping BufferedImage workImage = image; if (token.isFlippedX() || token.isFlippedY()) { workImage = new BufferedImage( image.getWidth(), image.getHeight(), image.getTransparency()); int workW = image.getWidth() * (token.isFlippedX() ? -1 : 1); int workH = image.getHeight() * (token.isFlippedY () ? -1 : 1); int workX = token.isFlippedX() ? image.getWidth() : 0; int workY = token.isFlippedY() ? image.getHeight() : 0; Graphics2D wig = workImage.createGraphics (); wig.drawImage(image, workX, workY, workW, workH, null); wig.dispose(); } // Position Dimension imgSize = new Dimension(workImage.getWidth(), workImage.getHeight()); SwingUtil.constrainTo(imgSize, footprintBounds.width, footprintBounds.height); int offsetx = 0; int offsety = 0; if (token.isSnapToScale()) { offsetx = (int)(imgSize.width < footprintBounds.width ? (footprintBounds.width - imgSize.width)/2 * getScale() : 0); offsety = (int)(imgSize.height < footprintBounds.height ? (footprintBounds.height - imgSize.height)/2 * getScale() : 0); } double tx = location.x + offsetx; double ty = location.y + offsety; AffineTransform at = new AffineTransform(); at.translate(tx, ty); // Rotated if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) { at.rotate(Math.toRadians(-token.getFacing() - 90), location.scaledWidth/2 - (token.getAnchor().x*scale) - offsetx, location.scaledHeight/2 - (token.getAnchor().y*scale) - offsety); // facing defaults to down, or -90 degrees } // Draw the token if (token.isSnapToScale()) { at.scale(((double) imgSize.width) / workImage.getWidth(), ((double) imgSize.height) / workImage.getHeight()); at.scale(getScale(), getScale()); } else { at.scale(((double) scaledWidth) / workImage.getWidth(), ((double) scaledHeight) / workImage.getHeight()); } clippedG.drawImage(workImage, at, this); // Halo (SQUARE) if (token.hasHalo() && token.getShape() == Token.TokenShape.SQUARE) { Stroke oldStroke = g.getStroke(); clippedG.setStroke(new BasicStroke(AppPreferences.getHaloLineWidth())); clippedG.setColor (token.getHaloColor()); clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight)); clippedG.setStroke(oldStroke); } // Facing ? // TODO: Optimize this by doing it once per token per facing if (token.hasFacing()) { Token.TokenShape tokenType = token.getShape(); switch(tokenType) { case CIRCLE: Shape arrow = getCircleFacingArrow(token.getFacing(), footprintBounds.width/2); double cx = location.x + location.scaledWidth/2; double cy = location.y + location.scaledHeight/2; clippedG.translate(cx, cy); clippedG.setColor(Color.yellow); clippedG.fill(arrow); clippedG.setColor(Color.darkGray); clippedG.draw(arrow); clippedG.translate(-cx, -cy); break; case SQUARE: int facing = token.getFacing(); while (facing < 0) {facing += 360;} // TODO: this should really be done in Token.setFacing() but I didn't want to take the chance of breaking something, so change this when it's safe to break stuff facing %= 360; arrow = getSquareFacingArrow(facing, footprintBounds.width/2); cx = location.x + location.scaledWidth/2; cy = location.y + location.scaledHeight/2; // Find the edge of the image // TODO: Man, this is horrible, there's gotta be a better way to do this double xp = location.scaledWidth/2; double yp = location.scaledHeight/2; if (facing >= 45 && facing <= 135 || facing >= 225 && facing <= 315) { xp = (int)(yp / Math.tan(Math.toRadians(facing))); if (facing > 180 ) { xp = -xp; yp = -yp; } } else { yp = (int)(xp * Math.tan(Math.toRadians(facing))); if (facing > 90 && facing < 270) { xp = -xp; yp = -yp; } } cx += xp; cy -= yp; clippedG.translate (cx, cy); clippedG.setColor(Color.yellow); clippedG.fill(arrow); clippedG.setColor(Color.darkGray); clippedG.draw(arrow); clippedG.translate(-cx, -cy); break; } } // Set up the graphics so that the overlay can just be painted. - AffineTransform transform = new AffineTransform(); - transform.translate(location.x+g.getTransform().getTranslateX(), location.y+g.getTransform().getTranslateY()); - Graphics2D locg = (Graphics2D)clippedG.create(); - locg.setTransform(transform); + Graphics2D locg = (Graphics2D)clippedG.create((int)location.x, (int)location.y, (int)Math.ceil(location.scaledWidth), (int)Math.ceil(location.scaledHeight)); Rectangle bounds = new Rectangle(0, 0, (int)Math.ceil(location.scaledWidth), (int)Math.ceil(location.scaledHeight)); - Rectangle overlayClip = locg.getClipBounds().intersection(bounds); - locg.setClip(overlayClip); // Check each of the set values for (String state : MapTool.getCampaign().getTokenStatesMap().keySet()) { Object stateValue = token.getState(state); AbstractTokenOverlay overlay = MapTool.getCampaign().getTokenStatesMap().get(state); if (stateValue instanceof AbstractTokenOverlay) overlay = (AbstractTokenOverlay)stateValue; if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) continue; overlay.paintOverlay(locg, token, bounds, stateValue); } for (String bar : MapTool.getCampaign().getTokenBarsMap().keySet()) { Object barValue = token.getState(bar); BarTokenOverlay overlay = MapTool.getCampaign().getTokenBarsMap().get(bar); if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) continue; overlay.paintOverlay(locg, token, bounds, barValue); } // endfor locg.dispose(); // DEBUGGING // ScreenPoint tmpsp = ScreenPoint.fromZonePoint(this, new ZonePoint(token.getX(), token.getY())); // g.setColor(Color.red); // g.drawLine(tmpsp.x, 0, tmpsp.x, getSize().height); // g.drawLine(0, tmpsp.y, getSize().width, tmpsp.y); } // Selection and labels for (TokenLocation location : getTokenLocations(getActiveLayer())) { Area bounds = location.bounds; Rectangle2D origBounds = location.origBounds; // TODO: This isn't entirely accurate as it doesn't account for the actual text // to be in the clipping bounds, but I'll fix that later if (!location.bounds.getBounds().intersects(clipBounds)) { continue; } Token token = location.token; boolean isSelected = selectedTokenSet.contains(token.getId()); if (isSelected) { Rectangle footprintBounds = token.getBounds(zone); ScreenPoint sp = ScreenPoint.fromZonePoint(this, footprintBounds.x, footprintBounds.y); double width = footprintBounds.width * getScale(); double height = footprintBounds.height * getScale(); ImageBorder selectedBorder = token.isStamp() ? AppStyle.selectedStampBorder : AppStyle.selectedBorder; // Border if (token.hasFacing() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.isStamp ())) { AffineTransform oldTransform = g.getTransform(); // Rotated g.translate(sp.x, sp.y); g.rotate(Math.toRadians(-token.getFacing() - 90), width/2 - (token.getAnchor().x*scale), height/2 - (token.getAnchor().y*scale)); // facing defaults to down, or -90 degrees selectedBorder.paintAround(g, 0, 0, (int)width, (int)height); g.setTransform(oldTransform); } else { selectedBorder.paintAround(g, (int)sp.x, (int)sp.y, (int)width, (int)height); } } // Name if (AppState.isShowTokenNames() || isSelected || token == tokenUnderMouse) { String name = token.getName(); if (view.isGMView () && token.getGMName() != null && token.getGMName().length() > 0) { name += " (" + token.getGMName() + ")"; } ImageLabel background = token.isVisible() ? token.getType() == Token.Type.NPC ? GraphicsUtil.BLUE_LABEL : GraphicsUtil.GREY_LABEL : GraphicsUtil.DARK_GREY_LABEL; Color foreground = token.isVisible() ? token.getType() == Token.Type.NPC ? Color.white : Color.black : Color.white; int offset = 10 + (isSelected ? 3 : 0); GraphicsUtil.drawBoxedString(g, name, bounds.getBounds().x + bounds.getBounds ().width/2, bounds.getBounds().y + bounds.getBounds().height + offset, SwingUtilities.CENTER, background, foreground); if (token.getLabel() != null && token.getLabel().trim().length() > 0) { offset += 16 + (isSelected ? 3 : 0); GraphicsUtil.drawBoxedString(g, token.getLabel(), bounds.getBounds().x + bounds.getBounds ().width/2, bounds.getBounds().y + bounds.getBounds().height + offset, SwingUtilities.CENTER, background, foreground); } } } // Stacks for (Area rect : coveredTokenSet) { BufferedImage stackImage = AppStyle.stackImage ; clippedG.drawImage(stackImage, rect.getBounds().x + rect.getBounds().width - stackImage.getWidth() + 2, rect.getBounds().y - 2, null); } // // Markers // for (TokenLocation location : getMarkerLocations() ) { // BufferedImage stackImage = AppStyle.markerImage; // g.drawImage(stackImage, location.bounds.getBounds().x, location.bounds.getBounds().y, null); // } if (clippedG != g) { clippedG.dispose(); } } private boolean canSeeMarker(Token token) { return MapTool.getPlayer().isGM() || !StringUtil.isEmpty(token.getNotes()); } public Set<GUID> getSelectedTokenSet() { return selectedTokenSet; } /** * A convienence method to get selected tokens ordered by name * @return List<Token> */ public List<Token> getSelectedTokensList() { List<Token> tokenList = new ArrayList<Token>(); for (GUID g : selectedTokenSet) { if (zone.getToken(g) != null) { tokenList.add(zone.getToken(g)); } } Collections.sort(tokenList, Token.NAME_COMPARATOR); return tokenList; } public boolean isTokenSelectable(GUID tokenGUID) { if (tokenGUID == null) { return false; } Token token = zone.getToken(tokenGUID); if (token == null) { return false; } if (!AppUtil.playerOwns(token)) { return false; } // FOR NOW: if you own the token, you can select it // if (!AppUtil.playerOwns(token) && !zone.isTokenVisible(token)) { // return false; // } // return true; } public void deselectToken(GUID tokenGUID) { addToSelectionHistory(selectedTokenSet); selectedTokenSet.remove(tokenGUID); MapTool.getFrame().resetTokenPanels(); repaint(); } public boolean selectToken(GUID tokenGUID) { if (!isTokenSelectable(tokenGUID)) { return false; } addToSelectionHistory(selectedTokenSet); selectedTokenSet.add(tokenGUID); repaint(); MapTool.getFrame().resetTokenPanels(); return true; } /** * Screen space rectangle */ public void selectTokens(Rectangle rect) { for (TokenLocation location : getTokenLocations(getActiveLayer())) { if (rect.intersects (location.bounds.getBounds())) { selectToken(location.token.getId()); } } } public void clearSelectedTokens() { addToSelectionHistory(selectedTokenSet); clearShowPaths(); selectedTokenSet.clear(); MapTool.getFrame().resetTokenPanels(); repaint(); } public void undoSelectToken() { // System.out.println("num history items: " + selectedTokenSetHistory.size()); /* for (Set<GUID> set : selectedTokenSetHistory) { System.out.println("history item"); for (GUID guid : set) { System.out.println(zone.getToken(guid).getName()); } }*/ if (selectedTokenSetHistory.size() > 0) { selectedTokenSet = selectedTokenSetHistory.remove(0); // user may have deleted some of the tokens that are contained in the selection history. // find them and filter them otherwise the selectionSet will have orphaned GUIDs and // they will cause NPE Set<GUID> invalidTokenSet = new HashSet<GUID>(); for (GUID guid : selectedTokenSet) { if (zone.getToken(guid) == null) { invalidTokenSet.add(guid); } } selectedTokenSet.removeAll(invalidTokenSet); // if there is no token left in the set, undo again if (selectedTokenSet.size() == 0) { undoSelectToken(); } } //TODO: if selection history is empty, notify the selection panel to disable the undo button. MapTool.getFrame().resetTokenPanels(); repaint(); } private void addToSelectionHistory(Set<GUID> selectionSet) { // don't add empty selections to history if (selectionSet.size() == 0) { return; } Set<GUID> history = new HashSet<GUID>(selectionSet); selectedTokenSetHistory.add(0, history); // limit the history to a certain size if (selectedTokenSetHistory.size() > 20) { selectedTokenSetHistory.subList(20, selectedTokenSetHistory.size() - 1).clear(); } } public void cycleSelectedToken(int direction) { List<Token> visibleTokens = getTokensOnScreen(); Set<GUID> selectedTokenSet = getSelectedTokenSet(); Integer newSelection = null; if (visibleTokens.size() == 0) { return; } if (selectedTokenSet.size() == 0) { newSelection = 0; } else { // Find the first selected token on the screen for (int i = 0; i < visibleTokens.size(); i++) { Token token = visibleTokens.get(i); if (!isTokenSelectable(token.getId())) { continue; } if (getSelectedTokenSet().contains(token.getId())) { newSelection = i; break; } } // Pick the next newSelection += direction; } if (newSelection < 0) { newSelection = visibleTokens.size() - 1; } if (newSelection >= visibleTokens.size()) { newSelection = 0; } // Make the selection clearSelectedTokens(); selectToken(visibleTokens.get(newSelection).getId()); } public Area getTokenBounds(Token token) { TokenLocation location = tokenLocationCache.get(token); return location != null ? location.bounds : null; } public Area getMarkerBounds(Token token) { for (TokenLocation location : markerLocationList) { if (location.token == token) { return location.bounds; } } return null; } public Rectangle getLabelBounds(Label label) { for (LabelLocation location : labelLocationList) { if (location.label == label) { return location.bounds; } } return null; } /** * Returns the token at screen location x, y (not cell location). To get * the token at a cell location, use getGameMap() and use that. * * @param x * @param y * @return */ public Token getTokenAt (int x, int y) { List<TokenLocation> locationList = new ArrayList<TokenLocation>(); locationList.addAll(getTokenLocations(getActiveLayer())); Collections.reverse(locationList); for (TokenLocation location : locationList) { if (location.bounds.contains(x, y)) { return location.token; } } return null; } public Token getMarkerAt (int x, int y) { List<TokenLocation> locationList = new ArrayList<TokenLocation>(); locationList.addAll(markerLocationList); Collections.reverse(locationList); for (TokenLocation location : locationList) { if (location.bounds.contains(x, y)) { return location.token; } } return null; } public List<Token> getTokenStackAt (int x, int y) { List<Area> stackList = new ArrayList<Area>(); stackList.addAll(coveredTokenSet); for (Area bounds : stackList) { if (bounds.contains(x, y)) { List<Token> tokenList = new ArrayList<Token>(); for (TokenLocation location : getTokenLocations(getActiveLayer())) { if (location.bounds.getBounds().intersects(bounds.getBounds())) { tokenList.add(location.token); } } return tokenList; } } return null; } /** * Returns the label at screen location x, y (not cell location). To get * the token at a cell location, use getGameMap() and use that. * * @param x * @param y * @return */ public Label getLabelAt (int x, int y) { List<LabelLocation> labelList = new ArrayList<LabelLocation>(); labelList.addAll(labelLocationList); Collections.reverse(labelList); for (LabelLocation location : labelList) { if (location.bounds.contains(x, y)) { return location.label; } } return null; } public int getViewOffsetX() { return zoneScale.getOffsetX(); } public int getViewOffsetY() { return zoneScale.getOffsetY(); } public void adjustGridSize(int delta) { zone.getGrid().setSize(Math.max(0, zone.getGrid().getSize() + delta)); repaint(); } public void moveGridBy(int dx, int dy) { int gridOffsetX = zone.getGrid().getOffsetX(); int gridOffsetY = zone.getGrid().getOffsetY(); gridOffsetX += dx; gridOffsetY += dy; if (gridOffsetY > 0) { gridOffsetY = gridOffsetY - (int)zone.getGrid().getCellHeight(); } if (gridOffsetX > 0) { gridOffsetX = gridOffsetX - (int)zone.getGrid().getCellWidth(); } zone.getGrid().setOffset(gridOffsetX, gridOffsetY); repaint(); } /** * Since the map can be scaled, this is a convenience method to find out * what cell is at this location. * * @param screenPoint Find the cell for this point. * @return The cell coordinates of the passed screen point. */ public CellPoint getCellAt(ScreenPoint screenPoint) { ZonePoint zp = screenPoint.convertToZone(this); return zone.getGrid().convert(zp); } public void setScale(double scale) { zoneScale.setScale(scale); } public double getScale() { return zoneScale.getScale(); } public double getScaledGridSize() { // Optimize: only need to calc this when grid size or scale changes return getScale() * zone.getGrid().getSize(); } /** * This makes sure that any image updates get refreshed. This could be a little smarter. */ @Override public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) { repaint(); return super.imageUpdate(img, infoflags, x, y, w, h); } /** * Represents a movement set */ private class SelectionSet { private HashSet<GUID> selectionSet = new HashSet<GUID>(); private GUID keyToken; private String playerId; private ZoneWalker walker; private Token token; private Path<ZonePoint> gridlessPath; // Pixel distance from keyToken's origin private int offsetX; private int offsetY; public SelectionSet(String playerId, GUID tokenGUID, Set<GUID> selectionList) { selectionSet.addAll(selectionList); keyToken = tokenGUID; this.playerId = playerId; token = zone.getToken(tokenGUID); if (token.isSnapToGrid() && zone.getGrid().getCapabilities().isSnapToGridSupported()) { if (ZoneRenderer.this.zone.getGrid().getCapabilities().isPathingSupported()) { CellPoint tokenPoint = zone.getGrid().convert(new ZonePoint(token.getX(), token.getY())); walker = ZoneRenderer.this.zone.getGrid().createZoneWalker(); walker.setWaypoints(tokenPoint, tokenPoint); } } else { gridlessPath = new Path<ZonePoint>(); } } public ZoneWalker getWalker() { return walker; } public GUID getKeyToken() { return keyToken; } public Set<GUID> getTokens() { return selectionSet; } public boolean contains(Token token) { return selectionSet.contains(token.getId()); } public void setOffset(int x, int y) { offsetX = x; offsetY = y; if (ZoneRenderer.this.zone.getGrid().getCapabilities().isPathingSupported() && token.isSnapToGrid()) { CellPoint point = zone.getGrid().convert(new ZonePoint( token.getX()+x, token.getY()+y)); walker.replaceLastWaypoint(point); } } /** * Add the waypoint if it is a new waypoint. If it is * an old waypoint remove it. * * @param location The point where the waypoint is toggled. */ public void toggleWaypoint(ZonePoint location) { // CellPoint cp = renderer.getZone().getGrid().convert(new ZonePoint(dragStartX, dragStartY)); if (token.isSnapToGrid()) { walker.toggleWaypoint(getZone().getGrid().convert(location)); } else { gridlessPath.addWayPoint(location); gridlessPath.addPathCell(location); } } public int getOffsetX() { return offsetX; } public int getOffsetY() { return offsetY; } public String getPlayerId() { return playerId; } } private class TokenLocation { public Area bounds; public Rectangle2D origBounds; public Token token; public Rectangle boundsCache; public int height; public int width; public double scaledHeight; public double scaledWidth; public double x; public double y; public int offsetX; public int offsetY; public TokenLocation(Area bounds, Rectangle2D origBounds, Token token, double x, double y, int width, int height, double scaledWidth, double scaledHeight) { this.bounds = bounds; this.token = token; this.origBounds = origBounds; this.width = width; this.height = height; this.scaledWidth = scaledWidth; this.scaledHeight = scaledHeight; this.x = x; this.y = y; offsetX = getViewOffsetX(); offsetY = getViewOffsetY(); boundsCache = bounds.getBounds(); } public boolean maybeOnscreen(Rectangle viewport) { int deltaX = getViewOffsetX() - offsetX; int deltaY = getViewOffsetY() - offsetY; boundsCache.x += deltaX; boundsCache.y += deltaY; offsetX = getViewOffsetX(); offsetY = getViewOffsetY(); if (!boundsCache.intersects(viewport)) { return false; } return true; } } private static class LabelLocation { public Rectangle bounds; public Label label; public LabelLocation(Rectangle bounds, Label label) { this.bounds = bounds; this.label = label; } } //// // DROP TARGET LISTENER /* (non-Javadoc) * @see java.awt.dnd.DropTargetListener#dragEnter(java.awt.dnd.DropTargetDragEvent) */ public void dragEnter(DropTargetDragEvent dtde) {} /* (non-Javadoc) * @see java.awt.dnd.DropTargetListener#dragExit(java.awt.dnd.DropTargetEvent) */ public void dragExit(DropTargetEvent dte) {} /* (non-Javadoc) * @see java.awt.dnd.DropTargetListener#dragOver (java.awt.dnd.DropTargetDragEvent) */ public void dragOver(DropTargetDragEvent dtde) { } private void addTokens(List<Token> tokens, ZonePoint zp, boolean configureToken) { GridCapabilities gridCaps = zone.getGrid().getCapabilities(); boolean isGM = MapTool.getPlayer().isGM(); ScreenPoint sp = ScreenPoint.fromZonePoint(this, zp); Point dropPoint = new Point((int)sp.x, (int)sp.y); SwingUtilities.convertPointToScreen(dropPoint, this); for (Token token : tokens) { // Get the snap to grid value for the current prefs and abilities token.setSnapToGrid(gridCaps.isSnapToGridSupported() && AppPreferences.getTokensStartSnapToGrid()); if (gridCaps.isSnapToGridSupported() && token.isSnapToGrid()) { zp = zone.getGrid().convert(zone.getGrid().convert(zp)); } token.setX(zp.x); token.setY(zp.y); // Set the image properties if (configureToken) { BufferedImage image = ImageManager.getImageAndWait(AssetManager.getAsset(token.getImageAssetId())); token.setShape(TokenUtil.guessTokenType((BufferedImage)image)); token.setWidth(image.getWidth(null)); token.setHeight(image.getHeight(null)); token.setFootprint(zone.getGrid(), zone.getGrid().getDefaultFootprint()); } // Always set the layer token.setLayer(getActiveLayer()); // He who drops, owns, if there are not players already set if (!token.hasOwners() && !isGM) { token.addOwner(MapTool.getPlayer().getName()); } // Token type Rectangle size = token.getBounds(zone); switch (getActiveLayer()) { case TOKEN: { // Players can't drop invisible tokens token.setVisible(!isGM || AppPreferences.getNewTokensVisible()); if (AppPreferences.getTokensStartFreesize()) { token.setSnapToScale(false); } break; } case BACKGROUND: { token.setShape (Token.TokenShape.TOP_DOWN); token.setSnapToScale(!AppPreferences.getBackgroundsStartFreesize()); token.setSnapToGrid(AppPreferences.getBackgroundsStartSnapToGrid()); token.setVisible(AppPreferences.getNewBackgroundsVisible()); // Center on drop point if (!token.isSnapToScale() && !token.isSnapToGrid()) { token.setX(token.getX() - size.width/2); token.setY(token.getY() - size.height/2); } break; } case OBJECT: { token.setShape(Token.TokenShape.TOP_DOWN); token.setSnapToScale(!AppPreferences.getObjectsStartFreesize()); token.setSnapToGrid(AppPreferences.getObjectsStartSnapToGrid()); token.setVisible(AppPreferences.getNewObjectsVisible()); // Center on drop point if (!token.isSnapToScale() && !token.isSnapToGrid()) { token.setX(token.getX() - size.width/2); token.setY(token.getY() - size.height/2); } break; } } // Check the name (after Token layer is set as name relies on layer) token.setName(MapToolUtil.nextTokenId(zone, token)); // Token type if (isGM) { token.setType(Token.Type.NPC); if (getActiveLayer() == Zone.Layer.TOKEN) { if (AppPreferences.getShowDialogOnNewToken()) { NewTokenDialog dialog = new NewTokenDialog(token, dropPoint.x, dropPoint.y); dialog.showDialog(); if (!dialog.isSuccess()) { continue; } } } } else { // Player dropped, player token token.setType(Token.Type.PC); } // Save the token and tell everybody about it zone.putToken(token); MapTool.serverCommand().putToken(zone.getId(), token); } // For convenience, select them clearSelectedTokens(); for (Token token : tokens) { selectToken(token.getId()); } // Copy them to the clipboard so that we can quickly copy them onto the map AppActions.copyTokens(tokens); requestFocusInWindow(); repaint(); } /* * (non-Javadoc) * * @see java.awt.dnd.DropTargetListener#drop (java.awt.dnd.DropTargetDropEvent) */ public void drop(DropTargetDropEvent dtde) { final ZonePoint zp = new ScreenPoint((int) dtde.getLocation().getX(), (int) dtde.getLocation().getY()).convertToZone(this); Transferable t = dtde.getTransferable(); if (!(TransferableHelper.isSupportedAssetFlavor(t) || TransferableHelper.isSupportedTokenFlavor(t)) || (dtde.getDropAction () & DnDConstants.ACTION_COPY_OR_MOVE) == 0) { dtde.rejectDrop(); // Not a supported flavor or not a copy/move return; } dtde.acceptDrop(dtde.getDropAction()); List<Token> tokens = null; List assets = TransferableHelper.getAsset(dtde); if (assets != null) { tokens = new ArrayList<Token>(assets.size()); for (Object working : assets) { if (working instanceof Asset) { Asset asset = (Asset)working; tokens.add(new Token(asset.getName(), asset.getId())); } else if (working instanceof Token) { tokens.add(new Token((Token)working)); } } addTokens(tokens, zp, true); } else { if (t.isDataFlavorSupported(TransferableToken.dataFlavor)) { try { // Make a copy so that it gets a new unique GUID tokens = Collections.singletonList(new Token((Token)t.getTransferData(TransferableToken.dataFlavor))); addTokens(tokens, zp, false); } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } else { tokens = TransferableHelper.getTokens(dtde.getTransferable ()); addTokens(tokens, zp, true); } } dtde.dropComplete(tokens != null); } /* (non-Javadoc) * @see java.awt.dnd.DropTargetListener#dropActionChanged (java.awt.dnd.DropTargetDragEvent) */ public void dropActionChanged(DropTargetDragEvent dtde) { // TODO Auto-generated method stub } //// // ZONE MODEL CHANGE LISTENER private class ZoneModelChangeListener implements ModelChangeListener { public void modelChanged(ModelChangeEvent event) { Object evt = event.getEvent(); if (evt == Zone.Event.TOPOLOGY_CHANGED) { flushFog = true; visibleScreenArea = null; } if (evt == Zone.Event.TOKEN_CHANGED || evt == Zone.Event.TOKEN_REMOVED) { flush((Token)event.getArg()); } if (evt == Zone.Event.FOG_CHANGED) { flushFog = true; } MapTool.getFrame().updateTokenTree(); repaint(); } } //// // COMPARABLE public int compareTo(Object o) { if (!(o instanceof ZoneRenderer)) { return 0; } return zone.getCreationTime() < ((ZoneRenderer)o).zone.getCreationTime() ? -1 : 1; } }
false
true
protected void renderTokens(Graphics2D g, List<Token> tokenList, PlayerView view) { Graphics2D clippedG = g; timer.start("createClip"); if (!view.isGMView() && visibleScreenArea != null && tokenList.size() > 0 && tokenList.get(0).isToken()) { clippedG = (Graphics2D)g.create(); Area visibleArea = new Area(g.getClipBounds()); visibleArea.intersect(visibleScreenArea); clippedG.setClip(new GeneralPath(visibleArea)); } timer.stop("createClip"); Rectangle viewport = new Rectangle(0, 0, getSize().width, getSize().height); Rectangle clipBounds = g.getClipBounds(); double scale = zoneScale.getScale(); for (Token token : tokenList) { if (token.isStamp() && isTokenMoving(token)) { continue; } TokenLocation location = tokenLocationCache.get(token); if (location != null && !location.maybeOnscreen(viewport)) { continue; } // Don't bother if it's not visible // NOTE: Not going to use zone.isTokenVisible as it is very slow. In fact, it's faster // to just draw the tokens and let them be clipped if (!token.isVisible() && !view.isGMView()) { continue; } Rectangle footprintBounds = token.getBounds(zone); BufferedImage image = null; Asset asset = AssetManager.getAsset(token.getImageAssetId ()); if (asset == null) { // In the mean time, show a placeholder image = ImageManager.UNKNOWN_IMAGE; } else { image = ImageManager.getImage(AssetManager.getAsset(token.getImageAssetId()), this); } double scaledWidth = (footprintBounds.width*scale); double scaledHeight = (footprintBounds.height*scale); // if (!token.isStamp()) { // // Fit inside the grid // scaledWidth --; // scaledHeight --; // } ScreenPoint tokenScreenLocation = ScreenPoint.fromZonePoint (this, footprintBounds.x, footprintBounds.y); // Tokens are centered on the image center point double x = tokenScreenLocation.x; double y = tokenScreenLocation.y; Rectangle2D origBounds = new Rectangle2D.Double(x, y, scaledWidth, scaledHeight); Area tokenBounds = new Area(origBounds); if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) { tokenBounds.transform(AffineTransform.getRotateInstance(Math.toRadians(-token.getFacing() - 90), scaledWidth/2 + x - (token.getAnchor().x*scale), scaledHeight/2 + y - (token.getAnchor().y*scale))); // facing defaults to down, or -90 degrees } location = new TokenLocation(tokenBounds, origBounds, token, x, y, footprintBounds.width, footprintBounds.height, scaledWidth, scaledHeight); tokenLocationCache.put(token, location); // General visibility if (!view.isGMView() && !token.isVisible()) { continue; } // Vision visibility if (!view.isGMView() && token.isToken() && zoneView.isUsingVision()) { if (!visibleScreenArea.getBounds().intersects(location.boundsCache)) { continue; } } // Markers if (token.isMarker() && canSeeMarker(token)) { markerLocationList.add(location); } if (!location.bounds.intersects(clipBounds)) { // Not on the screen, don't have to worry about it continue; } // Stacking check if (!token.isStamp()) { for (TokenLocation currLocation : getTokenLocations(Zone.Layer.TOKEN)) { Area r1 = currLocation.bounds; // Are we covering anyone ? if (location.boundsCache.contains(currLocation.boundsCache) && GraphicsUtil.contains(location.bounds, r1)) { // Are we covering someone that is covering someone ? Area oldRect = null; for (Area r2 : coveredTokenSet) { if (location.bounds.getBounds().contains(r2.getBounds ())) { oldRect = r2; break; } } if (oldRect != null) { coveredTokenSet.remove(oldRect); } coveredTokenSet.add(location.bounds); } } } // Keep track of the location on the screen // Note the order where the top most token is at the end of the list List<TokenLocation> locationList = null; if (!token.isStamp()) { locationList = getTokenLocations(Zone.Layer.TOKEN); } else { if (token.isObjectStamp()) { locationList = getTokenLocations(Zone.Layer.OBJECT); } if (token.isBackgroundStamp()) { locationList = getTokenLocations(Zone.Layer.BACKGROUND); } if (token.isGMStamp()) { locationList = getTokenLocations(Zone.Layer.GM); } } if (locationList != null) { locationList.add(location); } // Only draw if we're visible // NOTE: this takes place AFTER resizing the image, that's so that the user // sufferes a pause only once while scaling, and not as new tokens are // scrolled onto the screen if (!location.bounds.intersects(clipBounds)) { continue; } // Moving ? if (isTokenMoving(token)) { BufferedImage replacementImage = replacementImageMap.get(token); if (replacementImage == null) { replacementImage = ImageUtil.rgbToGrayscale(image); replacementImageMap.put(token, replacementImage); } image = replacementImage; } // Previous path if (showPathList.contains(token) && token.getLastPath() != null) { renderPath(g, token.getLastPath(), token.getFootprint(zone.getGrid())); } // Halo (TOPDOWN, CIRCLE) if (token.hasHalo() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.getShape() == Token.TokenShape.CIRCLE)) { Stroke oldStroke = clippedG.getStroke(); clippedG.setStroke( new BasicStroke(AppPreferences.getHaloLineWidth())); clippedG.setColor(token.getHaloColor()); clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight)); clippedG.setStroke(oldStroke); } // handle flipping BufferedImage workImage = image; if (token.isFlippedX() || token.isFlippedY()) { workImage = new BufferedImage( image.getWidth(), image.getHeight(), image.getTransparency()); int workW = image.getWidth() * (token.isFlippedX() ? -1 : 1); int workH = image.getHeight() * (token.isFlippedY () ? -1 : 1); int workX = token.isFlippedX() ? image.getWidth() : 0; int workY = token.isFlippedY() ? image.getHeight() : 0; Graphics2D wig = workImage.createGraphics (); wig.drawImage(image, workX, workY, workW, workH, null); wig.dispose(); } // Position Dimension imgSize = new Dimension(workImage.getWidth(), workImage.getHeight()); SwingUtil.constrainTo(imgSize, footprintBounds.width, footprintBounds.height); int offsetx = 0; int offsety = 0; if (token.isSnapToScale()) { offsetx = (int)(imgSize.width < footprintBounds.width ? (footprintBounds.width - imgSize.width)/2 * getScale() : 0); offsety = (int)(imgSize.height < footprintBounds.height ? (footprintBounds.height - imgSize.height)/2 * getScale() : 0); } double tx = location.x + offsetx; double ty = location.y + offsety; AffineTransform at = new AffineTransform(); at.translate(tx, ty); // Rotated if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) { at.rotate(Math.toRadians(-token.getFacing() - 90), location.scaledWidth/2 - (token.getAnchor().x*scale) - offsetx, location.scaledHeight/2 - (token.getAnchor().y*scale) - offsety); // facing defaults to down, or -90 degrees } // Draw the token if (token.isSnapToScale()) { at.scale(((double) imgSize.width) / workImage.getWidth(), ((double) imgSize.height) / workImage.getHeight()); at.scale(getScale(), getScale()); } else { at.scale(((double) scaledWidth) / workImage.getWidth(), ((double) scaledHeight) / workImage.getHeight()); } clippedG.drawImage(workImage, at, this); // Halo (SQUARE) if (token.hasHalo() && token.getShape() == Token.TokenShape.SQUARE) { Stroke oldStroke = g.getStroke(); clippedG.setStroke(new BasicStroke(AppPreferences.getHaloLineWidth())); clippedG.setColor (token.getHaloColor()); clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight)); clippedG.setStroke(oldStroke); } // Facing ? // TODO: Optimize this by doing it once per token per facing if (token.hasFacing()) { Token.TokenShape tokenType = token.getShape(); switch(tokenType) { case CIRCLE: Shape arrow = getCircleFacingArrow(token.getFacing(), footprintBounds.width/2); double cx = location.x + location.scaledWidth/2; double cy = location.y + location.scaledHeight/2; clippedG.translate(cx, cy); clippedG.setColor(Color.yellow); clippedG.fill(arrow); clippedG.setColor(Color.darkGray); clippedG.draw(arrow); clippedG.translate(-cx, -cy); break; case SQUARE: int facing = token.getFacing(); while (facing < 0) {facing += 360;} // TODO: this should really be done in Token.setFacing() but I didn't want to take the chance of breaking something, so change this when it's safe to break stuff facing %= 360; arrow = getSquareFacingArrow(facing, footprintBounds.width/2); cx = location.x + location.scaledWidth/2; cy = location.y + location.scaledHeight/2; // Find the edge of the image // TODO: Man, this is horrible, there's gotta be a better way to do this double xp = location.scaledWidth/2; double yp = location.scaledHeight/2; if (facing >= 45 && facing <= 135 || facing >= 225 && facing <= 315) { xp = (int)(yp / Math.tan(Math.toRadians(facing))); if (facing > 180 ) { xp = -xp; yp = -yp; } } else { yp = (int)(xp * Math.tan(Math.toRadians(facing))); if (facing > 90 && facing < 270) { xp = -xp; yp = -yp; } } cx += xp; cy -= yp; clippedG.translate (cx, cy); clippedG.setColor(Color.yellow); clippedG.fill(arrow); clippedG.setColor(Color.darkGray); clippedG.draw(arrow); clippedG.translate(-cx, -cy); break; } } // Set up the graphics so that the overlay can just be painted. AffineTransform transform = new AffineTransform(); transform.translate(location.x+g.getTransform().getTranslateX(), location.y+g.getTransform().getTranslateY()); Graphics2D locg = (Graphics2D)clippedG.create(); locg.setTransform(transform); Rectangle bounds = new Rectangle(0, 0, (int)Math.ceil(location.scaledWidth), (int)Math.ceil(location.scaledHeight)); Rectangle overlayClip = locg.getClipBounds().intersection(bounds); locg.setClip(overlayClip); // Check each of the set values for (String state : MapTool.getCampaign().getTokenStatesMap().keySet()) { Object stateValue = token.getState(state); AbstractTokenOverlay overlay = MapTool.getCampaign().getTokenStatesMap().get(state); if (stateValue instanceof AbstractTokenOverlay) overlay = (AbstractTokenOverlay)stateValue; if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) continue; overlay.paintOverlay(locg, token, bounds, stateValue); } for (String bar : MapTool.getCampaign().getTokenBarsMap().keySet()) { Object barValue = token.getState(bar); BarTokenOverlay overlay = MapTool.getCampaign().getTokenBarsMap().get(bar); if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) continue; overlay.paintOverlay(locg, token, bounds, barValue); } // endfor locg.dispose(); // DEBUGGING // ScreenPoint tmpsp = ScreenPoint.fromZonePoint(this, new ZonePoint(token.getX(), token.getY())); // g.setColor(Color.red); // g.drawLine(tmpsp.x, 0, tmpsp.x, getSize().height); // g.drawLine(0, tmpsp.y, getSize().width, tmpsp.y); } // Selection and labels for (TokenLocation location : getTokenLocations(getActiveLayer())) { Area bounds = location.bounds; Rectangle2D origBounds = location.origBounds; // TODO: This isn't entirely accurate as it doesn't account for the actual text // to be in the clipping bounds, but I'll fix that later if (!location.bounds.getBounds().intersects(clipBounds)) { continue; } Token token = location.token; boolean isSelected = selectedTokenSet.contains(token.getId()); if (isSelected) { Rectangle footprintBounds = token.getBounds(zone); ScreenPoint sp = ScreenPoint.fromZonePoint(this, footprintBounds.x, footprintBounds.y); double width = footprintBounds.width * getScale(); double height = footprintBounds.height * getScale(); ImageBorder selectedBorder = token.isStamp() ? AppStyle.selectedStampBorder : AppStyle.selectedBorder; // Border if (token.hasFacing() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.isStamp ())) { AffineTransform oldTransform = g.getTransform(); // Rotated g.translate(sp.x, sp.y); g.rotate(Math.toRadians(-token.getFacing() - 90), width/2 - (token.getAnchor().x*scale), height/2 - (token.getAnchor().y*scale)); // facing defaults to down, or -90 degrees selectedBorder.paintAround(g, 0, 0, (int)width, (int)height); g.setTransform(oldTransform); } else { selectedBorder.paintAround(g, (int)sp.x, (int)sp.y, (int)width, (int)height); } } // Name if (AppState.isShowTokenNames() || isSelected || token == tokenUnderMouse) { String name = token.getName(); if (view.isGMView () && token.getGMName() != null && token.getGMName().length() > 0) { name += " (" + token.getGMName() + ")"; } ImageLabel background = token.isVisible() ? token.getType() == Token.Type.NPC ? GraphicsUtil.BLUE_LABEL : GraphicsUtil.GREY_LABEL : GraphicsUtil.DARK_GREY_LABEL; Color foreground = token.isVisible() ? token.getType() == Token.Type.NPC ? Color.white : Color.black : Color.white; int offset = 10 + (isSelected ? 3 : 0); GraphicsUtil.drawBoxedString(g, name, bounds.getBounds().x + bounds.getBounds ().width/2, bounds.getBounds().y + bounds.getBounds().height + offset, SwingUtilities.CENTER, background, foreground); if (token.getLabel() != null && token.getLabel().trim().length() > 0) { offset += 16 + (isSelected ? 3 : 0); GraphicsUtil.drawBoxedString(g, token.getLabel(), bounds.getBounds().x + bounds.getBounds ().width/2, bounds.getBounds().y + bounds.getBounds().height + offset, SwingUtilities.CENTER, background, foreground); } } } // Stacks for (Area rect : coveredTokenSet) { BufferedImage stackImage = AppStyle.stackImage ; clippedG.drawImage(stackImage, rect.getBounds().x + rect.getBounds().width - stackImage.getWidth() + 2, rect.getBounds().y - 2, null); } // // Markers // for (TokenLocation location : getMarkerLocations() ) { // BufferedImage stackImage = AppStyle.markerImage; // g.drawImage(stackImage, location.bounds.getBounds().x, location.bounds.getBounds().y, null); // } if (clippedG != g) { clippedG.dispose(); } }
protected void renderTokens(Graphics2D g, List<Token> tokenList, PlayerView view) { Graphics2D clippedG = g; timer.start("createClip"); if (!view.isGMView() && visibleScreenArea != null && tokenList.size() > 0 && tokenList.get(0).isToken()) { clippedG = (Graphics2D)g.create(); Area visibleArea = new Area(g.getClipBounds()); visibleArea.intersect(visibleScreenArea); clippedG.setClip(new GeneralPath(visibleArea)); } timer.stop("createClip"); Rectangle viewport = new Rectangle(0, 0, getSize().width, getSize().height); Rectangle clipBounds = g.getClipBounds(); double scale = zoneScale.getScale(); for (Token token : tokenList) { if (token.isStamp() && isTokenMoving(token)) { continue; } TokenLocation location = tokenLocationCache.get(token); if (location != null && !location.maybeOnscreen(viewport)) { continue; } // Don't bother if it's not visible // NOTE: Not going to use zone.isTokenVisible as it is very slow. In fact, it's faster // to just draw the tokens and let them be clipped if (!token.isVisible() && !view.isGMView()) { continue; } Rectangle footprintBounds = token.getBounds(zone); BufferedImage image = null; Asset asset = AssetManager.getAsset(token.getImageAssetId ()); if (asset == null) { // In the mean time, show a placeholder image = ImageManager.UNKNOWN_IMAGE; } else { image = ImageManager.getImage(AssetManager.getAsset(token.getImageAssetId()), this); } double scaledWidth = (footprintBounds.width*scale); double scaledHeight = (footprintBounds.height*scale); // if (!token.isStamp()) { // // Fit inside the grid // scaledWidth --; // scaledHeight --; // } ScreenPoint tokenScreenLocation = ScreenPoint.fromZonePoint (this, footprintBounds.x, footprintBounds.y); // Tokens are centered on the image center point double x = tokenScreenLocation.x; double y = tokenScreenLocation.y; Rectangle2D origBounds = new Rectangle2D.Double(x, y, scaledWidth, scaledHeight); Area tokenBounds = new Area(origBounds); if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) { tokenBounds.transform(AffineTransform.getRotateInstance(Math.toRadians(-token.getFacing() - 90), scaledWidth/2 + x - (token.getAnchor().x*scale), scaledHeight/2 + y - (token.getAnchor().y*scale))); // facing defaults to down, or -90 degrees } location = new TokenLocation(tokenBounds, origBounds, token, x, y, footprintBounds.width, footprintBounds.height, scaledWidth, scaledHeight); tokenLocationCache.put(token, location); // General visibility if (!view.isGMView() && !token.isVisible()) { continue; } // Vision visibility if (!view.isGMView() && token.isToken() && zoneView.isUsingVision()) { if (!visibleScreenArea.getBounds().intersects(location.boundsCache)) { continue; } } // Markers if (token.isMarker() && canSeeMarker(token)) { markerLocationList.add(location); } if (!location.bounds.intersects(clipBounds)) { // Not on the screen, don't have to worry about it continue; } // Stacking check if (!token.isStamp()) { for (TokenLocation currLocation : getTokenLocations(Zone.Layer.TOKEN)) { Area r1 = currLocation.bounds; // Are we covering anyone ? if (location.boundsCache.contains(currLocation.boundsCache) && GraphicsUtil.contains(location.bounds, r1)) { // Are we covering someone that is covering someone ? Area oldRect = null; for (Area r2 : coveredTokenSet) { if (location.bounds.getBounds().contains(r2.getBounds ())) { oldRect = r2; break; } } if (oldRect != null) { coveredTokenSet.remove(oldRect); } coveredTokenSet.add(location.bounds); } } } // Keep track of the location on the screen // Note the order where the top most token is at the end of the list List<TokenLocation> locationList = null; if (!token.isStamp()) { locationList = getTokenLocations(Zone.Layer.TOKEN); } else { if (token.isObjectStamp()) { locationList = getTokenLocations(Zone.Layer.OBJECT); } if (token.isBackgroundStamp()) { locationList = getTokenLocations(Zone.Layer.BACKGROUND); } if (token.isGMStamp()) { locationList = getTokenLocations(Zone.Layer.GM); } } if (locationList != null) { locationList.add(location); } // Only draw if we're visible // NOTE: this takes place AFTER resizing the image, that's so that the user // sufferes a pause only once while scaling, and not as new tokens are // scrolled onto the screen if (!location.bounds.intersects(clipBounds)) { continue; } // Moving ? if (isTokenMoving(token)) { BufferedImage replacementImage = replacementImageMap.get(token); if (replacementImage == null) { replacementImage = ImageUtil.rgbToGrayscale(image); replacementImageMap.put(token, replacementImage); } image = replacementImage; } // Previous path if (showPathList.contains(token) && token.getLastPath() != null) { renderPath(g, token.getLastPath(), token.getFootprint(zone.getGrid())); } // Halo (TOPDOWN, CIRCLE) if (token.hasHalo() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.getShape() == Token.TokenShape.CIRCLE)) { Stroke oldStroke = clippedG.getStroke(); clippedG.setStroke( new BasicStroke(AppPreferences.getHaloLineWidth())); clippedG.setColor(token.getHaloColor()); clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight)); clippedG.setStroke(oldStroke); } // handle flipping BufferedImage workImage = image; if (token.isFlippedX() || token.isFlippedY()) { workImage = new BufferedImage( image.getWidth(), image.getHeight(), image.getTransparency()); int workW = image.getWidth() * (token.isFlippedX() ? -1 : 1); int workH = image.getHeight() * (token.isFlippedY () ? -1 : 1); int workX = token.isFlippedX() ? image.getWidth() : 0; int workY = token.isFlippedY() ? image.getHeight() : 0; Graphics2D wig = workImage.createGraphics (); wig.drawImage(image, workX, workY, workW, workH, null); wig.dispose(); } // Position Dimension imgSize = new Dimension(workImage.getWidth(), workImage.getHeight()); SwingUtil.constrainTo(imgSize, footprintBounds.width, footprintBounds.height); int offsetx = 0; int offsety = 0; if (token.isSnapToScale()) { offsetx = (int)(imgSize.width < footprintBounds.width ? (footprintBounds.width - imgSize.width)/2 * getScale() : 0); offsety = (int)(imgSize.height < footprintBounds.height ? (footprintBounds.height - imgSize.height)/2 * getScale() : 0); } double tx = location.x + offsetx; double ty = location.y + offsety; AffineTransform at = new AffineTransform(); at.translate(tx, ty); // Rotated if (token.hasFacing() && token.getShape() == Token.TokenShape.TOP_DOWN) { at.rotate(Math.toRadians(-token.getFacing() - 90), location.scaledWidth/2 - (token.getAnchor().x*scale) - offsetx, location.scaledHeight/2 - (token.getAnchor().y*scale) - offsety); // facing defaults to down, or -90 degrees } // Draw the token if (token.isSnapToScale()) { at.scale(((double) imgSize.width) / workImage.getWidth(), ((double) imgSize.height) / workImage.getHeight()); at.scale(getScale(), getScale()); } else { at.scale(((double) scaledWidth) / workImage.getWidth(), ((double) scaledHeight) / workImage.getHeight()); } clippedG.drawImage(workImage, at, this); // Halo (SQUARE) if (token.hasHalo() && token.getShape() == Token.TokenShape.SQUARE) { Stroke oldStroke = g.getStroke(); clippedG.setStroke(new BasicStroke(AppPreferences.getHaloLineWidth())); clippedG.setColor (token.getHaloColor()); clippedG.draw(new Rectangle2D.Double(location.x, location.y, location.scaledWidth, location.scaledHeight)); clippedG.setStroke(oldStroke); } // Facing ? // TODO: Optimize this by doing it once per token per facing if (token.hasFacing()) { Token.TokenShape tokenType = token.getShape(); switch(tokenType) { case CIRCLE: Shape arrow = getCircleFacingArrow(token.getFacing(), footprintBounds.width/2); double cx = location.x + location.scaledWidth/2; double cy = location.y + location.scaledHeight/2; clippedG.translate(cx, cy); clippedG.setColor(Color.yellow); clippedG.fill(arrow); clippedG.setColor(Color.darkGray); clippedG.draw(arrow); clippedG.translate(-cx, -cy); break; case SQUARE: int facing = token.getFacing(); while (facing < 0) {facing += 360;} // TODO: this should really be done in Token.setFacing() but I didn't want to take the chance of breaking something, so change this when it's safe to break stuff facing %= 360; arrow = getSquareFacingArrow(facing, footprintBounds.width/2); cx = location.x + location.scaledWidth/2; cy = location.y + location.scaledHeight/2; // Find the edge of the image // TODO: Man, this is horrible, there's gotta be a better way to do this double xp = location.scaledWidth/2; double yp = location.scaledHeight/2; if (facing >= 45 && facing <= 135 || facing >= 225 && facing <= 315) { xp = (int)(yp / Math.tan(Math.toRadians(facing))); if (facing > 180 ) { xp = -xp; yp = -yp; } } else { yp = (int)(xp * Math.tan(Math.toRadians(facing))); if (facing > 90 && facing < 270) { xp = -xp; yp = -yp; } } cx += xp; cy -= yp; clippedG.translate (cx, cy); clippedG.setColor(Color.yellow); clippedG.fill(arrow); clippedG.setColor(Color.darkGray); clippedG.draw(arrow); clippedG.translate(-cx, -cy); break; } } // Set up the graphics so that the overlay can just be painted. Graphics2D locg = (Graphics2D)clippedG.create((int)location.x, (int)location.y, (int)Math.ceil(location.scaledWidth), (int)Math.ceil(location.scaledHeight)); Rectangle bounds = new Rectangle(0, 0, (int)Math.ceil(location.scaledWidth), (int)Math.ceil(location.scaledHeight)); // Check each of the set values for (String state : MapTool.getCampaign().getTokenStatesMap().keySet()) { Object stateValue = token.getState(state); AbstractTokenOverlay overlay = MapTool.getCampaign().getTokenStatesMap().get(state); if (stateValue instanceof AbstractTokenOverlay) overlay = (AbstractTokenOverlay)stateValue; if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) continue; overlay.paintOverlay(locg, token, bounds, stateValue); } for (String bar : MapTool.getCampaign().getTokenBarsMap().keySet()) { Object barValue = token.getState(bar); BarTokenOverlay overlay = MapTool.getCampaign().getTokenBarsMap().get(bar); if (overlay == null || overlay.isMouseover() && token != tokenUnderMouse || !overlay.showPlayer(token, MapTool.getPlayer())) continue; overlay.paintOverlay(locg, token, bounds, barValue); } // endfor locg.dispose(); // DEBUGGING // ScreenPoint tmpsp = ScreenPoint.fromZonePoint(this, new ZonePoint(token.getX(), token.getY())); // g.setColor(Color.red); // g.drawLine(tmpsp.x, 0, tmpsp.x, getSize().height); // g.drawLine(0, tmpsp.y, getSize().width, tmpsp.y); } // Selection and labels for (TokenLocation location : getTokenLocations(getActiveLayer())) { Area bounds = location.bounds; Rectangle2D origBounds = location.origBounds; // TODO: This isn't entirely accurate as it doesn't account for the actual text // to be in the clipping bounds, but I'll fix that later if (!location.bounds.getBounds().intersects(clipBounds)) { continue; } Token token = location.token; boolean isSelected = selectedTokenSet.contains(token.getId()); if (isSelected) { Rectangle footprintBounds = token.getBounds(zone); ScreenPoint sp = ScreenPoint.fromZonePoint(this, footprintBounds.x, footprintBounds.y); double width = footprintBounds.width * getScale(); double height = footprintBounds.height * getScale(); ImageBorder selectedBorder = token.isStamp() ? AppStyle.selectedStampBorder : AppStyle.selectedBorder; // Border if (token.hasFacing() && (token.getShape() == Token.TokenShape.TOP_DOWN || token.isStamp ())) { AffineTransform oldTransform = g.getTransform(); // Rotated g.translate(sp.x, sp.y); g.rotate(Math.toRadians(-token.getFacing() - 90), width/2 - (token.getAnchor().x*scale), height/2 - (token.getAnchor().y*scale)); // facing defaults to down, or -90 degrees selectedBorder.paintAround(g, 0, 0, (int)width, (int)height); g.setTransform(oldTransform); } else { selectedBorder.paintAround(g, (int)sp.x, (int)sp.y, (int)width, (int)height); } } // Name if (AppState.isShowTokenNames() || isSelected || token == tokenUnderMouse) { String name = token.getName(); if (view.isGMView () && token.getGMName() != null && token.getGMName().length() > 0) { name += " (" + token.getGMName() + ")"; } ImageLabel background = token.isVisible() ? token.getType() == Token.Type.NPC ? GraphicsUtil.BLUE_LABEL : GraphicsUtil.GREY_LABEL : GraphicsUtil.DARK_GREY_LABEL; Color foreground = token.isVisible() ? token.getType() == Token.Type.NPC ? Color.white : Color.black : Color.white; int offset = 10 + (isSelected ? 3 : 0); GraphicsUtil.drawBoxedString(g, name, bounds.getBounds().x + bounds.getBounds ().width/2, bounds.getBounds().y + bounds.getBounds().height + offset, SwingUtilities.CENTER, background, foreground); if (token.getLabel() != null && token.getLabel().trim().length() > 0) { offset += 16 + (isSelected ? 3 : 0); GraphicsUtil.drawBoxedString(g, token.getLabel(), bounds.getBounds().x + bounds.getBounds ().width/2, bounds.getBounds().y + bounds.getBounds().height + offset, SwingUtilities.CENTER, background, foreground); } } } // Stacks for (Area rect : coveredTokenSet) { BufferedImage stackImage = AppStyle.stackImage ; clippedG.drawImage(stackImage, rect.getBounds().x + rect.getBounds().width - stackImage.getWidth() + 2, rect.getBounds().y - 2, null); } // // Markers // for (TokenLocation location : getMarkerLocations() ) { // BufferedImage stackImage = AppStyle.markerImage; // g.drawImage(stackImage, location.bounds.getBounds().x, location.bounds.getBounds().y, null); // } if (clippedG != g) { clippedG.dispose(); } }
diff --git a/trunk/org/xbill/DNS/Name.java b/trunk/org/xbill/DNS/Name.java index 9dd76ad..4a998d8 100644 --- a/trunk/org/xbill/DNS/Name.java +++ b/trunk/org/xbill/DNS/Name.java @@ -1,736 +1,739 @@ // Copyright (c) 1999 Brian Wellington ([email protected]) package org.xbill.DNS; import java.io.*; import java.text.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A representation of a domain name. * * @author Brian Wellington */ public class Name implements Comparable { private static final int LABEL_NORMAL = 0; private static final int LABEL_COMPRESSION = 0xC0; private static final int LABEL_MASK = 0xC0; private byte [] name; private long offsets; private int hashcode; private static final byte [] emptyLabel = new byte[] {(byte)0}; private static final byte [] wildLabel = new byte[] {(byte)1, (byte)'*'}; /** The root name */ public static final Name root; /** The maximum length of a Name */ private static final int MAXNAME = 255; /** The maximum length of labels a label a Name */ private static final int MAXLABEL = 63; /** The maximum number of labels in a Name */ private static final int MAXLABELS = 128; /** The maximum number of cached offsets */ private static final int MAXOFFSETS = 7; /* Used for printing non-printable characters */ private static final DecimalFormat byteFormat = new DecimalFormat(); /* Used to efficiently convert bytes to lowercase */ private static final byte lowercase[] = new byte[256]; /* Used in wildcard names. */ private static final Name wild; static { byteFormat.setMinimumIntegerDigits(3); for (int i = 0; i < lowercase.length; i++) { if (i < 'A' || i > 'Z') lowercase[i] = (byte)i; else lowercase[i] = (byte)(i - 'A' + 'a'); } root = new Name(); wild = new Name(); root.appendSafe(emptyLabel, 0, 1); wild.appendSafe(wildLabel, 0, 1); } private Name() { } private final void dump(String prefix) { String s; try { s = toString(); } catch (Exception e) { s = "<unprintable>"; } System.out.println(prefix + ": " + s); byte labels = labels(); for (int i = 0; i < labels; i++) System.out.print(offset(i) + " "); System.out.println(""); for (int i = 0; name != null && i < name.length; i++) System.out.print((name[i] & 0xFF) + " "); System.out.println(""); } private final void setoffset(int n, int offset) { if (n >= MAXOFFSETS) return; int shift = 8 * (7 - n); offsets &= (~(0xFFL << shift)); offsets |= ((long)offset << shift); } private final int offset(int n) { if (n < MAXOFFSETS) { int shift = 8 * (7 - n); return ((int)(offsets >>> shift) & 0xFF); } else { int pos = offset(MAXOFFSETS - 1); for (int i = MAXOFFSETS - 1; i < n; i++) pos += (name[pos] + 1); return (pos); } } private final void setlabels(byte labels) { offsets &= ~(0xFF); offsets |= labels; } private final byte getlabels() { return (byte)(offsets & 0xFF); } private static final void copy(Name src, Name dst) { dst.name = src.name; dst.offsets = src.offsets; } private final void append(byte [] array, int start, int n) throws NameTooLongException { int length = (name == null ? 0 : (name.length - offset(0))); int alength = 0; for (int i = 0, pos = start; i < n; i++) { int len = array[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); len++; pos += len; alength += len; } int newlength = length + alength; if (newlength > MAXNAME) throw new NameTooLongException(); byte labels = getlabels(); int newlabels = labels + n; if (newlabels > MAXLABELS) throw new IllegalStateException("too many labels"); byte [] newname = new byte[newlength]; if (length != 0) System.arraycopy(name, offset(0), newname, 0, length); System.arraycopy(array, start, newname, length, alength); name = newname; for (int i = 0, pos = length; i < n; i++) { setoffset(labels + i, pos); pos += (newname[pos] + 1); } setlabels((byte) newlabels); } private final void appendFromString(byte [] array, int start, int n) throws TextParseException { try { append(array, start, n); } catch (NameTooLongException e) { throw new TextParseException("Name too long"); } } private final void appendSafe(byte [] array, int start, int n) { try { append(array, start, n); } catch (NameTooLongException e) { } } /** * Create a new name from a string and an origin * @param s The string to be converted * @param origin If the name is not absolute, the origin to be appended * @deprecated As of dnsjava 1.3.0, replaced by <code>Name.fromString</code>. */ public Name(String s, Name origin) { Name n; try { n = Name.fromString(s, origin); } catch (TextParseException e) { StringBuffer sb = new StringBuffer(s); if (origin != null) sb.append("." + origin); sb.append(": "+ e.getMessage()); System.err.println(sb.toString()); return; } if (!n.isAbsolute() && !Options.check("pqdn") && n.getlabels() > 1 && n.getlabels() < MAXLABELS - 1) { /* * This isn't exactly right, but it's close. * Partially qualified names are evil. */ n.appendSafe(emptyLabel, 0, 1); } copy(n, this); } /** * Create a new name from a string * @param s The string to be converted * @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>. */ public Name(String s) { this (s, null); } /** * Create a new name from a string and an origin. This does not automatically * make the name absolute; it will be absolute if it has a trailing dot or an * absolute origin is appended. * @param s The string to be converted * @param origin If the name is not absolute, the origin to be appended. * @throws TextParseException The name is invalid. */ public static Name fromString(String s, Name origin) throws TextParseException { Name name = new Name(); if (s.equals("")) throw new TextParseException("empty name"); else if (s.equals("@")) { if (origin == null) return name; return origin; } else if (s.equals(".")) return (root); int labelstart = -1; int pos = 1; byte [] label = new byte[MAXLABEL + 1]; boolean escaped = false; int digits = 0; int intval = 0; boolean absolute = false; for (int i = 0; i < s.length(); i++) { byte b = (byte) s.charAt(i); if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; - intval *= 10 + (b - '0'); + intval *= 10; intval += (b - '0'); + if (intval > 255) + throw new TextParseException + ("bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); if (pos >= MAXLABEL) throw new TextParseException("label too long"); labelstart = pos; label[pos++] = b; escaped = false; } else if (b == '\\') { escaped = true; digits = 0; intval = 0; } else if (b == '.') { if (labelstart == -1) throw new TextParseException("invalid label"); label[0] = (byte)(pos - 1); name.appendFromString(label, 0, 1); labelstart = -1; pos = 1; } else { if (labelstart == -1) labelstart = i; if (pos >= MAXLABEL) throw new TextParseException("label too long"); label[pos++] = b; } } if (labelstart == -1) { name.appendFromString(emptyLabel, 0, 1); absolute = true; } else { label[0] = (byte)(pos - 1); name.appendFromString(label, 0, 1); } if (origin != null && !absolute) name.appendFromString(origin.name, 0, origin.getlabels()); return (name); } /** * Create a new name from a string. This does not automatically make the name * absolute; it will be absolute if it has a trailing dot. * @param s The string to be converted * @throws TextParseException The name is invalid. */ public static Name fromString(String s) throws TextParseException { return fromString(s, null); } /** * Create a new name from a constant string. This should only be used when the name is known to be good - that is, when it is constant. * @param s The string to be converted * @throws IllegalArgumentException The name is invalid. */ public static Name fromConstantString(String s) { try { return fromString(s, null); } catch (TextParseException e) { throw new IllegalArgumentException("Invalid name '" + s + "'"); } } /** * Create a new name from DNS wire format * @param in A stream containing the input data */ public Name(DataByteInputStream in) throws IOException { int len, pos, savedpos; Name name2; boolean done = false; byte [] label = new byte[MAXLABEL + 1]; while (!done) { len = in.readUnsignedByte(); switch (len & LABEL_MASK) { case LABEL_NORMAL: if (getlabels() >= MAXLABELS) throw new WireParseException("too many labels"); if (len == 0) { append(emptyLabel, 0, 1); done = true; } else { label[0] = (byte)len; in.readArray(label, 1, len); append(label, 0, 1); } break; case LABEL_COMPRESSION: pos = in.readUnsignedByte(); pos += ((len & ~LABEL_MASK) << 8); if (Options.check("verbosecompression")) System.err.println("currently " + in.getPos() + ", pointer to " + pos); savedpos = in.getPos(); if (pos >= savedpos) throw new WireParseException("bad compression"); in.setPos(pos); if (Options.check("verbosecompression")) System.err.println("current name '" + this + "', seeking to " + pos); try { name2 = new Name(in); } finally { in.setPos(savedpos); } append(name2.name, 0, name2.labels()); done = true; break; } } } /** * Create a new name by removing labels from the beginning of an existing Name * @param src An existing Name * @param n The number of labels to remove from the beginning in the copy */ public Name(Name src, int n) { byte slabels = src.labels(); if (n > slabels) throw new IllegalArgumentException("attempted to remove too " + "many labels"); name = src.name; setlabels((byte)(slabels - n)); for (int i = 0; i < MAXOFFSETS && i < slabels - n; i++) setoffset(i, src.offset(i + n)); } /** * Creates a new name by concatenating two existing names. * @param prefix The prefix name. * @param suffix The suffix name. * @return The concatenated name. * @throws NameTooLongException The name is too long. */ public static Name concatenate(Name prefix, Name suffix) throws NameTooLongException { if (prefix.isAbsolute()) return (prefix); Name newname = new Name(); copy(prefix, newname); newname.append(suffix.name, suffix.offset(0), suffix.getlabels()); return newname; } /** * Generates a new Name with the first n labels replaced by a wildcard * @return The wildcard name */ public Name wild(int n) { if (n < 1) throw new IllegalArgumentException("must replace 1 or more " + "labels"); try { Name newname = new Name(); copy(wild, newname); newname.append(name, offset(n), getlabels() - n); return newname; } catch (NameTooLongException e) { throw new IllegalStateException ("Name.wild: concatenate failed"); } } /** * Generates a new Name to be used when following a DNAME. * @param dname The DNAME record to follow. * @return The constructed name. * @throws NameTooLongException The resulting name is too long. */ public Name fromDNAME(DNAMERecord dname) throws NameTooLongException { Name dnameowner = dname.getName(); Name dnametarget = dname.getTarget(); if (!subdomain(dnameowner)) return null; int plabels = labels() - dnameowner.labels(); int plength = length() - dnameowner.length(); int pstart = offset(0); int dlabels = dnametarget.labels(); int dlength = dnametarget.length(); if (plength + dlength > MAXNAME) throw new NameTooLongException(); Name newname = new Name(); newname.setlabels((byte)(plabels + dlabels)); newname.name = new byte[plength + dlength]; System.arraycopy(name, pstart, newname.name, 0, plength); System.arraycopy(dnametarget.name, 0, newname.name, plength, dlength); for (int i = 0, pos = 0; i < MAXOFFSETS && i < plabels + dlabels; i++) { newname.setoffset(i, pos); pos += (newname.name[pos] + 1); } return newname; } /** * Is this name a wildcard? */ public boolean isWild() { if (labels() == 0) return false; return (name[0] == (byte)1 && name[1] == (byte)'*'); } /** * Is this name fully qualified (that is, absolute)? * @deprecated As of dnsjava 1.3.0, replaced by <code>isAbsolute</code>. */ public boolean isQualified() { return (isAbsolute()); } /** * Is this name absolute? */ public boolean isAbsolute() { if (labels() == 0) return false; return (name[name.length - 1] == 0); } /** * The length of the name. */ public short length() { return (short)(name.length - offset(0)); } /** * The number of labels in the name. */ public byte labels() { return getlabels(); } /** * Is the current Name a subdomain of the specified name? */ public boolean subdomain(Name domain) { byte labels = labels(); byte dlabels = domain.labels(); if (dlabels > labels) return false; if (dlabels == labels) return equals(domain); return domain.equals(name, offset(labels - dlabels)); } private String byteString(byte [] array, int pos) { StringBuffer sb = new StringBuffer(); int len = array[pos++]; for (int i = pos; i < pos + len; i++) { short b = (short)(array[i] & 0xFF); if (b <= 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == '(' || b == ')' || b == '.' || b == ';' || b == '\\' || b == '@' || b == '$') { sb.append('\\'); sb.append((char)b); } else sb.append((char)b); } return sb.toString(); } /** * Convert Name to a String */ public String toString() { byte labels = labels(); if (labels == 0) return "@"; else if (labels == 1 && name[offset(0)] == 0) return "."; StringBuffer sb = new StringBuffer(); for (int i = 0, pos = offset(0); i < labels; i++) { int len = name[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); if (len == 0) break; sb.append(byteString(name, pos)); sb.append('.'); pos += (1 + len); } if (!isAbsolute()) sb.deleteCharAt(sb.length() - 1); return sb.toString(); } /** * Convert the nth label in a Name to a String * @param n The label to be converted to a String */ public String getLabelString(int n) { int pos = offset(n); return byteString(name, pos); } /** * Convert Name to DNS wire format * @param out The output stream containing the DNS message. * @param c The compression context, or null of no compression is desired. * @throws IOException An error occurred writing the name. * @throws IllegalArgumentException The name is not absolute. */ public void toWire(DataByteOutputStream out, Compression c) throws IOException { if (!isAbsolute()) throw new IllegalArgumentException("toWire() called on " + "non-absolute name"); byte labels = labels(); for (int i = 0; i < labels - 1; i++) { Name tname; if (i == 0) tname = this; else tname = new Name(this, i); int pos = -1; if (c != null) pos = c.get(tname); if (pos >= 0) { pos |= (LABEL_MASK << 8); out.writeShort(pos); return; } else { if (c != null) c.add(out.getPos(), tname); out.writeString(name, offset(i)); } } out.writeByte(0); } /** * Convert Name to canonical DNS wire format (all lowercase) * @param out The output stream to which the message is written. * @throws IOException An error occurred writing the name. */ public void toWireCanonical(DataByteOutputStream out) throws IOException { byte [] b = toWireCanonical(); out.write(b); } /** * Convert Name to canonical DNS wire format (all lowercase) * @throws IOException An error occurred writing the name. */ public byte [] toWireCanonical() throws IOException { byte labels = labels(); if (labels == 0) return (new byte[0]); byte [] b = new byte[name.length - offset(0)]; for (int i = 0, pos = offset(0); i < labels; i++) { int len = name[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); b[pos] = name[pos++]; for (int j = 0; j < len; j++) b[pos] = lowercase[name[pos++]]; } return b; } private final boolean equals(byte [] b, int bpos) { byte labels = labels(); for (int i = 0, pos = offset(0); i < labels; i++) { if (name[pos] != b[bpos]) return false; int len = name[pos++]; bpos++; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); for (int j = 0; j < len; j++) if (lowercase[name[pos++]] != lowercase[b[bpos++]]) return false; } return true; } /** * Are these two Names equivalent? */ public boolean equals(Object arg) { if (arg == this) return true; if (arg == null || !(arg instanceof Name)) return false; Name d = (Name) arg; if (d.labels() != labels()) return false; return equals(d.name, d.offset(0)); } /** * Computes a hashcode based on the value */ public int hashCode() { if (hashcode != 0) return (hashcode); int code = 0; for (int i = offset(0); i < name.length; i++) code += ((code << 3) + lowercase[name[i]]); hashcode = code; return hashcode; } /** * Compares this Name to another Object. * @param o The Object to be compared. * @return The value 0 if the argument is a name equivalent to this name; * a value less than 0 if the argument is less than this name in the canonical * ordering, and a value greater than 0 if the argument is greater than this * name in the canonical ordering. * @throws ClassCastException if the argument is not a Name. */ public int compareTo(Object o) { Name arg = (Name) o; if (this == arg) return (0); byte labels = labels(); byte alabels = arg.labels(); int compares = labels > alabels ? alabels : labels; for (int i = 1; i <= compares; i++) { int start = offset(labels - i); int astart = arg.offset(alabels - i); int length = name[start]; int alength = arg.name[astart]; for (int j = 0; j < length && j < alength; j++) { int n = lowercase[name[j + start]] - lowercase[arg.name[j + astart]]; if (n != 0) return (n); } if (length != alength) return (length - alength); } return (labels - alabels); } }
false
true
public static Name fromString(String s, Name origin) throws TextParseException { Name name = new Name(); if (s.equals("")) throw new TextParseException("empty name"); else if (s.equals("@")) { if (origin == null) return name; return origin; } else if (s.equals(".")) return (root); int labelstart = -1; int pos = 1; byte [] label = new byte[MAXLABEL + 1]; boolean escaped = false; int digits = 0; int intval = 0; boolean absolute = false; for (int i = 0; i < s.length(); i++) { byte b = (byte) s.charAt(i); if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10 + (b - '0'); intval += (b - '0'); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); if (pos >= MAXLABEL) throw new TextParseException("label too long"); labelstart = pos; label[pos++] = b; escaped = false; } else if (b == '\\') { escaped = true; digits = 0; intval = 0; } else if (b == '.') { if (labelstart == -1) throw new TextParseException("invalid label"); label[0] = (byte)(pos - 1); name.appendFromString(label, 0, 1); labelstart = -1; pos = 1; } else { if (labelstart == -1) labelstart = i; if (pos >= MAXLABEL) throw new TextParseException("label too long"); label[pos++] = b; } } if (labelstart == -1) { name.appendFromString(emptyLabel, 0, 1); absolute = true; } else { label[0] = (byte)(pos - 1); name.appendFromString(label, 0, 1); } if (origin != null && !absolute) name.appendFromString(origin.name, 0, origin.getlabels()); return (name); }
public static Name fromString(String s, Name origin) throws TextParseException { Name name = new Name(); if (s.equals("")) throw new TextParseException("empty name"); else if (s.equals("@")) { if (origin == null) return name; return origin; } else if (s.equals(".")) return (root); int labelstart = -1; int pos = 1; byte [] label = new byte[MAXLABEL + 1]; boolean escaped = false; int digits = 0; int intval = 0; boolean absolute = false; for (int i = 0; i < s.length(); i++) { byte b = (byte) s.charAt(i); if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10; intval += (b - '0'); if (intval > 255) throw new TextParseException ("bad escape"); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); if (pos >= MAXLABEL) throw new TextParseException("label too long"); labelstart = pos; label[pos++] = b; escaped = false; } else if (b == '\\') { escaped = true; digits = 0; intval = 0; } else if (b == '.') { if (labelstart == -1) throw new TextParseException("invalid label"); label[0] = (byte)(pos - 1); name.appendFromString(label, 0, 1); labelstart = -1; pos = 1; } else { if (labelstart == -1) labelstart = i; if (pos >= MAXLABEL) throw new TextParseException("label too long"); label[pos++] = b; } } if (labelstart == -1) { name.appendFromString(emptyLabel, 0, 1); absolute = true; } else { label[0] = (byte)(pos - 1); name.appendFromString(label, 0, 1); } if (origin != null && !absolute) name.appendFromString(origin.name, 0, origin.getlabels()); return (name); }
diff --git a/src/com/itmill/toolkit/demo/util/SampleDatabase.java b/src/com/itmill/toolkit/demo/util/SampleDatabase.java index d18732361..68e357790 100644 --- a/src/com/itmill/toolkit/demo/util/SampleDatabase.java +++ b/src/com/itmill/toolkit/demo/util/SampleDatabase.java @@ -1,167 +1,167 @@ package com.itmill.toolkit.demo.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Creates temporary database named toolkit with sample table named employee and * populates it with data. By default we use HSQLDB. Ensure that you have * hsqldb.jar under WEB-INF/lib directory. Database is will be created into * memory. * * @author IT Mill Ltd. * */ public class SampleDatabase { public static final int ROWCOUNT = 1000; private Connection connection = null; private static final String[] firstnames = new String[] { "Amanda", "Andrew", "Bill", "Frank", "Matt", "Xavier", "John", "Mary", "Joe", "Gloria", "Marcus", "Belinda", "David", "Anthony", "Julian", "Paul", "Carrie", "Susan", "Gregg", "Michael", "William", "Ethan", "Thomas", "Oscar", "Norman", "Roy", "Sarah", "Jeff", "Jane", "Peter", "Marc", "Josie", "Linus" }; private static final String[] lastnames = new String[] { "Torvalds", "Smith", "Jones", "Beck", "Burton", "Bell", "Davis", "Burke", "Bernard", "Hood", "Scott", "Smith", "Carter", "Roller", "Conrad", "Martin", "Fisher", "Martell", "Freeman", "Hackman", "Jones", "Harper", "Russek", "Johnson", "Sheridan", "Hill", "Parker", "Foster", "Moss", "Fielding" }; private static final String[] titles = new String[] { "Project Manager", "Marketing Manager", "Sales Manager", "Sales", "Trainer", "Technical Support", "Account Manager", "Customer Support", "Testing Engineer", "Software Designer", "Programmer", "Consultant" }; private static final String[] units = new String[] { "Tokyo", "Mexico City", "Seoul", "New York", "Sao Paulo", "Bombay", "Delhi", "Shanghai", "Los Angeles", "London", "Shanghai", "Sydney", "Bangalore", "Hong Kong", "Madrid", "Milano", "Beijing", "Paris", "Moscow", "Berlin", "Helsinki" }; /** * Create temporary database. * */ public SampleDatabase() { // connect to SQL database connect(); // initialize SQL database createTables(); // test by executing sample JDBC query testDatabase(); } /** * Creates sample table named employee and populates it with data.Use the * specified database connection. * * @param connection */ public SampleDatabase(Connection connection) { // initialize SQL database createTables(); // test by executing sample JDBC query testDatabase(); } /** * Connect to SQL database. In this sample we use HSQLDB and an toolkit * named database in implicitly created into system memory. * */ private void connect() { // use memory-Only Database String url = "jdbc:hsqldb:mem:toolkit"; try { Class.forName("org.hsqldb.jdbcDriver").newInstance(); connection = DriverManager.getConnection(url, "sa", ""); } catch (Exception e) { throw new RuntimeException(e); } } /** * use for SQL commands CREATE, DROP, INSERT and UPDATE * * @param expression * @throws SQLException */ public void update(String expression) throws SQLException { Statement st = null; st = connection.createStatement(); int i = st.executeUpdate(expression); if (i == -1) { System.out.println("SampleDatabase error : " + expression); } st.close(); } /** * Create test table and few rows. Issue note: using capitalized column * names as HSQLDB returns column names in capitalized form with this demo. * */ private void createTables() { try { String stmt = null; stmt = "CREATE TABLE employee ( ID INTEGER IDENTITY, FIRSTNAME VARCHAR(100), " + "LASTNAME VARCHAR(100), TITLE VARCHAR(100), UNIT VARCHAR(100) )"; update(stmt); for (int j = 0; j < ROWCOUNT; j++) { stmt = "INSERT INTO employee(FIRSTNAME, LASTNAME, TITLE, UNIT) VALUES (" + "'" + firstnames[(int) (Math.random() * (firstnames.length - 1))] + "'," + "'" + lastnames[(int) (Math.random() * (lastnames.length - 1))] + "'," + "'" + titles[(int) (Math.random() * (titles.length - 1))] + "'," + "'" + units[(int) (Math.random() * (units.length - 1))] + "'" + ")"; update(stmt); } } catch (SQLException e) { - if (e.toString().indexOf("Table already exists") != -1) + if (e.toString().indexOf("Table already exists") == -1) throw new RuntimeException(e); } } /** * Test database connection with simple SELECT command. * */ private String testDatabase() { String result = null; try { Statement stmt = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM employee"); rs.next(); result = "rowcount for table test is " + rs.getObject(1).toString(); stmt.close(); } catch (SQLException e) { throw new RuntimeException(e); } return result; } public Connection getConnection() { return connection; } }
true
true
private void createTables() { try { String stmt = null; stmt = "CREATE TABLE employee ( ID INTEGER IDENTITY, FIRSTNAME VARCHAR(100), " + "LASTNAME VARCHAR(100), TITLE VARCHAR(100), UNIT VARCHAR(100) )"; update(stmt); for (int j = 0; j < ROWCOUNT; j++) { stmt = "INSERT INTO employee(FIRSTNAME, LASTNAME, TITLE, UNIT) VALUES (" + "'" + firstnames[(int) (Math.random() * (firstnames.length - 1))] + "'," + "'" + lastnames[(int) (Math.random() * (lastnames.length - 1))] + "'," + "'" + titles[(int) (Math.random() * (titles.length - 1))] + "'," + "'" + units[(int) (Math.random() * (units.length - 1))] + "'" + ")"; update(stmt); } } catch (SQLException e) { if (e.toString().indexOf("Table already exists") != -1) throw new RuntimeException(e); } }
private void createTables() { try { String stmt = null; stmt = "CREATE TABLE employee ( ID INTEGER IDENTITY, FIRSTNAME VARCHAR(100), " + "LASTNAME VARCHAR(100), TITLE VARCHAR(100), UNIT VARCHAR(100) )"; update(stmt); for (int j = 0; j < ROWCOUNT; j++) { stmt = "INSERT INTO employee(FIRSTNAME, LASTNAME, TITLE, UNIT) VALUES (" + "'" + firstnames[(int) (Math.random() * (firstnames.length - 1))] + "'," + "'" + lastnames[(int) (Math.random() * (lastnames.length - 1))] + "'," + "'" + titles[(int) (Math.random() * (titles.length - 1))] + "'," + "'" + units[(int) (Math.random() * (units.length - 1))] + "'" + ")"; update(stmt); } } catch (SQLException e) { if (e.toString().indexOf("Table already exists") == -1) throw new RuntimeException(e); } }
diff --git a/src/com/android/nfc/NfcDispatcher.java b/src/com/android/nfc/NfcDispatcher.java index 2f442e6..1324017 100644 --- a/src/com/android/nfc/NfcDispatcher.java +++ b/src/com/android/nfc/NfcDispatcher.java @@ -1,464 +1,465 @@ /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.nfc; import com.android.nfc.RegisteredComponentCache.ComponentInfo; import android.app.Activity; import android.app.ActivityManagerNative; import android.app.IActivityManager; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.net.Uri; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.Ndef; import android.os.RemoteException; import android.util.Log; import java.io.FileDescriptor; import java.io.PrintWriter; import java.nio.charset.Charsets; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; /** * Dispatch of NFC events to start activities */ public class NfcDispatcher { static final boolean DBG = true; static final String TAG = "NfcDispatcher"; final Context mContext; final IActivityManager mIActivityManager; final RegisteredComponentCache mTechListFilters; final PackageManager mPackageManager; final ContentResolver mContentResolver; // Locked on this PendingIntent mOverrideIntent; IntentFilter[] mOverrideFilters; String[][] mOverrideTechLists; public NfcDispatcher(Context context, P2pLinkManager p2pManager) { mContext = context; mIActivityManager = ActivityManagerNative.getDefault(); mTechListFilters = new RegisteredComponentCache(mContext, NfcAdapter.ACTION_TECH_DISCOVERED, NfcAdapter.ACTION_TECH_DISCOVERED); mPackageManager = context.getPackageManager(); mContentResolver = context.getContentResolver(); } public synchronized void setForegroundDispatch(PendingIntent intent, IntentFilter[] filters, String[][] techLists) { if (DBG) Log.d(TAG, "Set Foreground Dispatch"); mOverrideIntent = intent; mOverrideFilters = filters; mOverrideTechLists = techLists; } /** * Helper for re-used objects and methods during a single tag dispatch. */ static class DispatchInfo { public final Intent intent; final Intent rootIntent; final Uri ndefUri; final String ndefMimeType; final PackageManager packageManager; final Context context; public DispatchInfo(Context context, Tag tag, NdefMessage message) { intent = new Intent(); intent.putExtra(NfcAdapter.EXTRA_TAG, tag); intent.putExtra(NfcAdapter.EXTRA_ID, tag.getId()); if (message != null) { intent.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES, new NdefMessage[] {message}); ndefUri = message.getRecords()[0].toUri(); ndefMimeType = message.getRecords()[0].toMimeType(); } else { ndefUri = null; ndefMimeType = null; } rootIntent = new Intent(context, NfcRootActivity.class); rootIntent.putExtra(NfcRootActivity.EXTRA_LAUNCH_INTENT, intent); rootIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); this.context = context; packageManager = context.getPackageManager(); } public Intent setNdefIntent() { intent.setAction(NfcAdapter.ACTION_NDEF_DISCOVERED); if (ndefUri != null) { intent.setData(ndefUri); return intent; } else if (ndefMimeType != null) { intent.setType(ndefMimeType); return intent; } return null; } public Intent setTechIntent() { intent.setData(null); intent.setType(null); intent.setAction(NfcAdapter.ACTION_TECH_DISCOVERED); return intent; } public Intent setTagIntent() { intent.setData(null); intent.setType(null); intent.setAction(NfcAdapter.ACTION_TAG_DISCOVERED); return intent; } /** * Launch the activity via a (single) NFC root task, so that it * creates a new task stack instead of interfering with any existing * task stack for that activity. * NfcRootActivity acts as the task root, it immediately calls * start activity on the intent it is passed. */ boolean tryStartActivity() { // Ideally we'd have used startActivityForResult() to determine whether the // NfcRootActivity was able to launch the intent, but startActivityForResult() // is not available on Context. Instead, we query the PackageManager beforehand // to determine if there is an Activity to handle this intent, and base the // result of off that. List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0); if (activities.size() > 0) { context.startActivity(rootIntent); return true; } return false; } boolean tryStartActivity(Intent intentToStart) { List<ResolveInfo> activities = packageManager.queryIntentActivities(intentToStart, 0); if (activities.size() > 0) { rootIntent.putExtra(NfcRootActivity.EXTRA_LAUNCH_INTENT, intentToStart); context.startActivity(rootIntent); return true; } return false; } } /** Returns false if no activities were found to dispatch to */ public boolean dispatchTag(Tag tag) { NdefMessage message = null; Ndef ndef = Ndef.get(tag); if (ndef != null) { message = ndef.getCachedNdefMessage(); } if (DBG) Log.d(TAG, "dispatch tag: " + tag.toString() + " message: " + message); PendingIntent overrideIntent; IntentFilter[] overrideFilters; String[][] overrideTechLists; DispatchInfo dispatch = new DispatchInfo(mContext, tag, message); synchronized (this) { overrideFilters = mOverrideFilters; overrideIntent = mOverrideIntent; overrideTechLists = mOverrideTechLists; } resumeAppSwitches(); if (tryOverrides(dispatch, tag, message, overrideIntent, overrideFilters, overrideTechLists)) { return true; } if (tryNdef(dispatch, message)) { return true; } if (tryTech(dispatch, tag)) { return true; } dispatch.setTagIntent(); if (dispatch.tryStartActivity()) { if (DBG) Log.i(TAG, "matched TAG"); return true; } if (DBG) Log.i(TAG, "no match"); return false; } boolean tryOverrides(DispatchInfo dispatch, Tag tag, NdefMessage message, PendingIntent overrideIntent, IntentFilter[] overrideFilters, String[][] overrideTechLists) { if (overrideIntent == null) { return false; } Intent intent; // NDEF if (message != null) { intent = dispatch.setNdefIntent(); - if (isFilterMatch(intent, overrideFilters, overrideTechLists != null)) { + if (intent != null && + isFilterMatch(intent, overrideFilters, overrideTechLists != null)) { try { overrideIntent.send(mContext, Activity.RESULT_OK, intent); if (DBG) Log.i(TAG, "matched NDEF override"); return true; } catch (CanceledException e) { return false; } } } // TECH intent = dispatch.setTechIntent(); if (isTechMatch(tag, overrideTechLists)) { try { overrideIntent.send(mContext, Activity.RESULT_OK, intent); if (DBG) Log.i(TAG, "matched TECH override"); return true; } catch (CanceledException e) { return false; } } // TAG intent = dispatch.setTagIntent(); if (isFilterMatch(intent, overrideFilters, overrideTechLists != null)) { try { overrideIntent.send(mContext, Activity.RESULT_OK, intent); if (DBG) Log.i(TAG, "matched TAG override"); return true; } catch (CanceledException e) { return false; } } return false; } boolean isFilterMatch(Intent intent, IntentFilter[] filters, boolean hasTechFilter) { if (filters != null) { for (IntentFilter filter : filters) { if (filter.match(mContentResolver, intent, false, TAG) >= 0) { return true; } } } else if (!hasTechFilter) { return true; // always match if both filters and techlists are null } return false; } boolean isTechMatch(Tag tag, String[][] techLists) { if (techLists == null) { return false; } String[] tagTechs = tag.getTechList(); Arrays.sort(tagTechs); for (String[] filterTechs : techLists) { if (filterMatch(tagTechs, filterTechs)) { return true; } } return false; } boolean tryNdef(DispatchInfo dispatch, NdefMessage message) { if (message == null) { return false; } dispatch.setNdefIntent(); // Try to start AAR activity with matching filter List<String> aarPackages = extractAarPackages(message); for (String pkg : aarPackages) { dispatch.intent.setPackage(pkg); if (dispatch.tryStartActivity()) { if (DBG) Log.i(TAG, "matched AAR to NDEF"); return true; } } // Try to perform regular launch of the first AAR if (aarPackages.size() > 0) { String firstPackage = aarPackages.get(0); Intent appLaunchIntent = mPackageManager.getLaunchIntentForPackage(firstPackage); if (appLaunchIntent != null && dispatch.tryStartActivity(appLaunchIntent)) { if (DBG) Log.i(TAG, "matched AAR to application launch"); return true; } // Find the package in Market: Intent marketIntent = getAppSearchIntent(firstPackage); if (marketIntent != null && dispatch.tryStartActivity(marketIntent)) { if (DBG) Log.i(TAG, "matched AAR to market launch"); return true; } } // regular launch dispatch.intent.setPackage(null); if (dispatch.tryStartActivity()) { if (DBG) Log.i(TAG, "matched NDEF"); return true; } return false; } static List<String> extractAarPackages(NdefMessage message) { List<String> aarPackages = new LinkedList<String>(); for (NdefRecord record : message.getRecords()) { String pkg = checkForAar(record); if (pkg != null) { aarPackages.add(pkg); } } return aarPackages; } boolean tryTech(DispatchInfo dispatch, Tag tag) { dispatch.setTechIntent(); String[] tagTechs = tag.getTechList(); Arrays.sort(tagTechs); // Standard tech dispatch path ArrayList<ResolveInfo> matches = new ArrayList<ResolveInfo>(); List<ComponentInfo> registered = mTechListFilters.getComponents(); // Check each registered activity to see if it matches for (ComponentInfo info : registered) { // Don't allow wild card matching if (filterMatch(tagTechs, info.techs) && isComponentEnabled(mPackageManager, info.resolveInfo)) { // Add the activity as a match if it's not already in the list if (!matches.contains(info.resolveInfo)) { matches.add(info.resolveInfo); } } } if (matches.size() == 1) { // Single match, launch directly ResolveInfo info = matches.get(0); dispatch.intent.setClassName(info.activityInfo.packageName, info.activityInfo.name); if (dispatch.tryStartActivity()) { if (DBG) Log.i(TAG, "matched single TECH"); return true; } dispatch.intent.setClassName((String)null, null); } else if (matches.size() > 1) { // Multiple matches, show a custom activity chooser dialog Intent intent = new Intent(mContext, TechListChooserActivity.class); intent.putExtra(Intent.EXTRA_INTENT, dispatch.intent); intent.putParcelableArrayListExtra(TechListChooserActivity.EXTRA_RESOLVE_INFOS, matches); if (dispatch.tryStartActivity(intent)) { if (DBG) Log.i(TAG, "matched multiple TECH"); return true; } } return false; } /** * Tells the ActivityManager to resume allowing app switches. * * If the current app called stopAppSwitches() then our startActivity() can * be delayed for several seconds. This happens with the default home * screen. As a system service we can override this behavior with * resumeAppSwitches(). */ void resumeAppSwitches() { try { mIActivityManager.resumeAppSwitches(); } catch (RemoteException e) { } } /** Returns true if the tech list filter matches the techs on the tag */ boolean filterMatch(String[] tagTechs, String[] filterTechs) { if (filterTechs == null || filterTechs.length == 0) return false; for (String tech : filterTechs) { if (Arrays.binarySearch(tagTechs, tech) < 0) { return false; } } return true; } static String checkForAar(NdefRecord record) { if (record.getTnf() == NdefRecord.TNF_EXTERNAL_TYPE && Arrays.equals(record.getType(), NdefRecord.RTD_ANDROID_APP)) { return new String(record.getPayload(), Charsets.US_ASCII); } return null; } /** * Returns an intent that can be used to find an application not currently * installed on the device. */ static Intent getAppSearchIntent(String pkg) { Intent market = new Intent(Intent.ACTION_VIEW); market.setData(Uri.parse("market://details?id=" + pkg)); return market; } static boolean isComponentEnabled(PackageManager pm, ResolveInfo info) { boolean enabled = false; ComponentName compname = new ComponentName( info.activityInfo.packageName, info.activityInfo.name); try { // Note that getActivityInfo() will internally call // isEnabledLP() to determine whether the component // enabled. If it's not, null is returned. if (pm.getActivityInfo(compname,0) != null) { enabled = true; } } catch (PackageManager.NameNotFoundException e) { enabled = false; } if (!enabled) { Log.d(TAG, "Component not enabled: " + compname); } return enabled; } void dump(FileDescriptor fd, PrintWriter pw, String[] args) { synchronized (this) { pw.println("mOverrideIntent=" + mOverrideIntent); pw.println("mOverrideFilters=" + mOverrideFilters); pw.println("mOverrideTechLists=" + mOverrideTechLists); } } }
true
true
boolean tryOverrides(DispatchInfo dispatch, Tag tag, NdefMessage message, PendingIntent overrideIntent, IntentFilter[] overrideFilters, String[][] overrideTechLists) { if (overrideIntent == null) { return false; } Intent intent; // NDEF if (message != null) { intent = dispatch.setNdefIntent(); if (isFilterMatch(intent, overrideFilters, overrideTechLists != null)) { try { overrideIntent.send(mContext, Activity.RESULT_OK, intent); if (DBG) Log.i(TAG, "matched NDEF override"); return true; } catch (CanceledException e) { return false; } } } // TECH intent = dispatch.setTechIntent(); if (isTechMatch(tag, overrideTechLists)) { try { overrideIntent.send(mContext, Activity.RESULT_OK, intent); if (DBG) Log.i(TAG, "matched TECH override"); return true; } catch (CanceledException e) { return false; } } // TAG intent = dispatch.setTagIntent(); if (isFilterMatch(intent, overrideFilters, overrideTechLists != null)) { try { overrideIntent.send(mContext, Activity.RESULT_OK, intent); if (DBG) Log.i(TAG, "matched TAG override"); return true; } catch (CanceledException e) { return false; } } return false; }
boolean tryOverrides(DispatchInfo dispatch, Tag tag, NdefMessage message, PendingIntent overrideIntent, IntentFilter[] overrideFilters, String[][] overrideTechLists) { if (overrideIntent == null) { return false; } Intent intent; // NDEF if (message != null) { intent = dispatch.setNdefIntent(); if (intent != null && isFilterMatch(intent, overrideFilters, overrideTechLists != null)) { try { overrideIntent.send(mContext, Activity.RESULT_OK, intent); if (DBG) Log.i(TAG, "matched NDEF override"); return true; } catch (CanceledException e) { return false; } } } // TECH intent = dispatch.setTechIntent(); if (isTechMatch(tag, overrideTechLists)) { try { overrideIntent.send(mContext, Activity.RESULT_OK, intent); if (DBG) Log.i(TAG, "matched TECH override"); return true; } catch (CanceledException e) { return false; } } // TAG intent = dispatch.setTagIntent(); if (isFilterMatch(intent, overrideFilters, overrideTechLists != null)) { try { overrideIntent.send(mContext, Activity.RESULT_OK, intent); if (DBG) Log.i(TAG, "matched TAG override"); return true; } catch (CanceledException e) { return false; } } return false; }
diff --git a/slickij-web-base/src/main/java/org/tcrun/slickij/webgroup/plans/ScheduleTestplanPanel.java b/slickij-web-base/src/main/java/org/tcrun/slickij/webgroup/plans/ScheduleTestplanPanel.java index df7027c..74e5a92 100644 --- a/slickij-web-base/src/main/java/org/tcrun/slickij/webgroup/plans/ScheduleTestplanPanel.java +++ b/slickij-web-base/src/main/java/org/tcrun/slickij/webgroup/plans/ScheduleTestplanPanel.java @@ -1,112 +1,113 @@ package org.tcrun.slickij.webgroup.plans; import com.google.inject.Inject; import java.util.ArrayList; import java.util.List; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.ChoiceRenderer; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.bson.types.ObjectId; import org.tcrun.slickij.api.TestplanResource; import org.tcrun.slickij.api.data.Build; import org.tcrun.slickij.api.data.ConfigurationOverride; import org.tcrun.slickij.api.data.Project; import org.tcrun.slickij.api.data.Release; import org.tcrun.slickij.api.data.Testplan; import org.tcrun.slickij.api.data.TestplanRunParameters; import org.tcrun.slickij.api.data.Testrun; import org.tcrun.slickij.api.data.dao.ConfigurationDAO; import org.tcrun.slickij.api.data.dao.TestplanDAO; import org.tcrun.slickij.webbase.SlickijSession; import org.tcrun.slickij.webgroup.reports.ReportByTestrunPage; /** * * @author jcorbett */ public class ScheduleTestplanPanel extends Panel { private ObjectId testplanId; private TestplanRunParametersWithCombinedBuildRelease parameters; @Inject private ConfigurationDAO configDAO; @Inject private TestplanResource testplanRestResource; @Inject private TestplanDAO tpDao; public ScheduleTestplanPanel(String id, ObjectId testplan) { super(id); this.testplanId = testplan; SlickijSession session = SlickijSession.get(); add(new FeedbackPanel("feedback")); add(new Label("testplanname", new PropertyModel<Testplan>(new LoadableDetatchableTestplanModel(tpDao, testplan), "name"))); parameters = new TestplanRunParametersWithCombinedBuildRelease(); Project curProject = session.getCurrentProject(); Release defRelease = curProject.findRelease(curProject.getDefaultRelease()); Build defBuild = defRelease.findBuild(defRelease.getDefaultBuild()); BuildReleaseReferenceCombo defaultReleaseAndBuild = new BuildReleaseReferenceCombo(defBuild.createReference(), defRelease.createReference()); parameters.setBuildRelease(defaultReleaseAndBuild); List<BuildReleaseReferenceCombo> builds = new ArrayList<BuildReleaseReferenceCombo>(); for(Release release : curProject.getReleases()) { for(Build build : release.getBuilds()) { builds.add(new BuildReleaseReferenceCombo(build.createReference(), release.createReference())); } } final TextField<String> key = new TextField<String>("overridekey", new Model<String>()); final TextField<String> value = new TextField<String>("overridevalue", new Model<String>()); Form<TestplanRunParameters> scheduleTestplanForm = new Form<TestplanRunParameters>("scheduletestplanform", new Model<TestplanRunParameters>(parameters)) { @Override protected void onSubmit() { if(key.getValue() != null && !key.getValue().equals("")) { ConfigurationOverride keyvaluepair = new ConfigurationOverride(); keyvaluepair.setKey(key.getValue()); keyvaluepair.setValue(value.getValue()); + keyvaluepair.setIsRequirement(false); parameters.setOverrides(new ArrayList<ConfigurationOverride>()); parameters.getOverrides().add(keyvaluepair); } Testrun run = testplanRestResource.runTestPlan(testplanId.toString(), parameters); PageParameters reportParams = new PageParameters(); reportParams.add("testrunid", run.getId()); setResponsePage(ReportByTestrunPage.class, reportParams); } }; DropDownChoice environments = new DropDownChoice("selectenvironment", new PropertyModel(scheduleTestplanForm.getModel(), "config"), new LoadableDetatchableConfigurationReferenceModel(configDAO), new ChoiceRenderer("name", "configId")); environments.setRequired(true); environments.setLabel(new Model("Environment")); DropDownChoice selectBuilds = new DropDownChoice("selectbuild", new PropertyModel(scheduleTestplanForm.getModel(), "buildRelease"), builds, new ChoiceRenderer("name", "id")); selectBuilds.setRequired(true); selectBuilds.setLabel(new Model("Build")); scheduleTestplanForm.add(environments); scheduleTestplanForm.add(selectBuilds); scheduleTestplanForm.add(key); scheduleTestplanForm.add(value); scheduleTestplanForm.add(new Button("submitscheduletestplanform")); add(scheduleTestplanForm); } }
true
true
public ScheduleTestplanPanel(String id, ObjectId testplan) { super(id); this.testplanId = testplan; SlickijSession session = SlickijSession.get(); add(new FeedbackPanel("feedback")); add(new Label("testplanname", new PropertyModel<Testplan>(new LoadableDetatchableTestplanModel(tpDao, testplan), "name"))); parameters = new TestplanRunParametersWithCombinedBuildRelease(); Project curProject = session.getCurrentProject(); Release defRelease = curProject.findRelease(curProject.getDefaultRelease()); Build defBuild = defRelease.findBuild(defRelease.getDefaultBuild()); BuildReleaseReferenceCombo defaultReleaseAndBuild = new BuildReleaseReferenceCombo(defBuild.createReference(), defRelease.createReference()); parameters.setBuildRelease(defaultReleaseAndBuild); List<BuildReleaseReferenceCombo> builds = new ArrayList<BuildReleaseReferenceCombo>(); for(Release release : curProject.getReleases()) { for(Build build : release.getBuilds()) { builds.add(new BuildReleaseReferenceCombo(build.createReference(), release.createReference())); } } final TextField<String> key = new TextField<String>("overridekey", new Model<String>()); final TextField<String> value = new TextField<String>("overridevalue", new Model<String>()); Form<TestplanRunParameters> scheduleTestplanForm = new Form<TestplanRunParameters>("scheduletestplanform", new Model<TestplanRunParameters>(parameters)) { @Override protected void onSubmit() { if(key.getValue() != null && !key.getValue().equals("")) { ConfigurationOverride keyvaluepair = new ConfigurationOverride(); keyvaluepair.setKey(key.getValue()); keyvaluepair.setValue(value.getValue()); parameters.setOverrides(new ArrayList<ConfigurationOverride>()); parameters.getOverrides().add(keyvaluepair); } Testrun run = testplanRestResource.runTestPlan(testplanId.toString(), parameters); PageParameters reportParams = new PageParameters(); reportParams.add("testrunid", run.getId()); setResponsePage(ReportByTestrunPage.class, reportParams); } }; DropDownChoice environments = new DropDownChoice("selectenvironment", new PropertyModel(scheduleTestplanForm.getModel(), "config"), new LoadableDetatchableConfigurationReferenceModel(configDAO), new ChoiceRenderer("name", "configId")); environments.setRequired(true); environments.setLabel(new Model("Environment")); DropDownChoice selectBuilds = new DropDownChoice("selectbuild", new PropertyModel(scheduleTestplanForm.getModel(), "buildRelease"), builds, new ChoiceRenderer("name", "id")); selectBuilds.setRequired(true); selectBuilds.setLabel(new Model("Build")); scheduleTestplanForm.add(environments); scheduleTestplanForm.add(selectBuilds); scheduleTestplanForm.add(key); scheduleTestplanForm.add(value); scheduleTestplanForm.add(new Button("submitscheduletestplanform")); add(scheduleTestplanForm); }
public ScheduleTestplanPanel(String id, ObjectId testplan) { super(id); this.testplanId = testplan; SlickijSession session = SlickijSession.get(); add(new FeedbackPanel("feedback")); add(new Label("testplanname", new PropertyModel<Testplan>(new LoadableDetatchableTestplanModel(tpDao, testplan), "name"))); parameters = new TestplanRunParametersWithCombinedBuildRelease(); Project curProject = session.getCurrentProject(); Release defRelease = curProject.findRelease(curProject.getDefaultRelease()); Build defBuild = defRelease.findBuild(defRelease.getDefaultBuild()); BuildReleaseReferenceCombo defaultReleaseAndBuild = new BuildReleaseReferenceCombo(defBuild.createReference(), defRelease.createReference()); parameters.setBuildRelease(defaultReleaseAndBuild); List<BuildReleaseReferenceCombo> builds = new ArrayList<BuildReleaseReferenceCombo>(); for(Release release : curProject.getReleases()) { for(Build build : release.getBuilds()) { builds.add(new BuildReleaseReferenceCombo(build.createReference(), release.createReference())); } } final TextField<String> key = new TextField<String>("overridekey", new Model<String>()); final TextField<String> value = new TextField<String>("overridevalue", new Model<String>()); Form<TestplanRunParameters> scheduleTestplanForm = new Form<TestplanRunParameters>("scheduletestplanform", new Model<TestplanRunParameters>(parameters)) { @Override protected void onSubmit() { if(key.getValue() != null && !key.getValue().equals("")) { ConfigurationOverride keyvaluepair = new ConfigurationOverride(); keyvaluepair.setKey(key.getValue()); keyvaluepair.setValue(value.getValue()); keyvaluepair.setIsRequirement(false); parameters.setOverrides(new ArrayList<ConfigurationOverride>()); parameters.getOverrides().add(keyvaluepair); } Testrun run = testplanRestResource.runTestPlan(testplanId.toString(), parameters); PageParameters reportParams = new PageParameters(); reportParams.add("testrunid", run.getId()); setResponsePage(ReportByTestrunPage.class, reportParams); } }; DropDownChoice environments = new DropDownChoice("selectenvironment", new PropertyModel(scheduleTestplanForm.getModel(), "config"), new LoadableDetatchableConfigurationReferenceModel(configDAO), new ChoiceRenderer("name", "configId")); environments.setRequired(true); environments.setLabel(new Model("Environment")); DropDownChoice selectBuilds = new DropDownChoice("selectbuild", new PropertyModel(scheduleTestplanForm.getModel(), "buildRelease"), builds, new ChoiceRenderer("name", "id")); selectBuilds.setRequired(true); selectBuilds.setLabel(new Model("Build")); scheduleTestplanForm.add(environments); scheduleTestplanForm.add(selectBuilds); scheduleTestplanForm.add(key); scheduleTestplanForm.add(value); scheduleTestplanForm.add(new Button("submitscheduletestplanform")); add(scheduleTestplanForm); }
diff --git a/patientview-parent/patientview/src/main/java/org/patientview/patientview/logon/PatientEditInputAction.java b/patientview-parent/patientview/src/main/java/org/patientview/patientview/logon/PatientEditInputAction.java index 74fb2b5d..6d805c3d 100644 --- a/patientview-parent/patientview/src/main/java/org/patientview/patientview/logon/PatientEditInputAction.java +++ b/patientview-parent/patientview/src/main/java/org/patientview/patientview/logon/PatientEditInputAction.java @@ -1,54 +1,54 @@ /* * PatientView * * Copyright (c) Worth Solutions Limited 2004-2013 * * This file is part of PatientView. * * PatientView is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * PatientView is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with PatientView in a file * titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @package PatientView * @link http://www.patientview.org * @author PatientView <[email protected]> * @copyright Copyright (c) 2004-2013, Worth Solutions Limited * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0 */ package org.patientview.patientview.logon; import org.patientview.actionutils.ActionUtils; import org.patientview.patientview.model.User; import org.patientview.patientview.user.NhsnoUnitcode; import org.patientview.utils.LegacySpringUtils; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class PatientEditInputAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String username = ActionUtils.retrieveStringPropertyValue("username", form, request); String unitcode = ActionUtils.retrieveStringPropertyValue("unitcode", form, request); String nhsno = ActionUtils.retrieveStringPropertyValue("nhsno", form, request); User user = LegacySpringUtils.getUserManager().get(username); // String nhsno = UserUtils.retrieveUsersRealNhsnoBestGuess(username); NhsnoUnitcode nhsnoThing = new NhsnoUnitcode(nhsno, unitcode); request.getSession().setAttribute("patient", user); - request.setAttribute("nhsnot", nhsnoThing); + request.getSession().setAttribute("nhsnot", nhsnoThing); return LogonUtils.logonChecks(mapping, request); } }
true
true
public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String username = ActionUtils.retrieveStringPropertyValue("username", form, request); String unitcode = ActionUtils.retrieveStringPropertyValue("unitcode", form, request); String nhsno = ActionUtils.retrieveStringPropertyValue("nhsno", form, request); User user = LegacySpringUtils.getUserManager().get(username); // String nhsno = UserUtils.retrieveUsersRealNhsnoBestGuess(username); NhsnoUnitcode nhsnoThing = new NhsnoUnitcode(nhsno, unitcode); request.getSession().setAttribute("patient", user); request.setAttribute("nhsnot", nhsnoThing); return LogonUtils.logonChecks(mapping, request); }
public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String username = ActionUtils.retrieveStringPropertyValue("username", form, request); String unitcode = ActionUtils.retrieveStringPropertyValue("unitcode", form, request); String nhsno = ActionUtils.retrieveStringPropertyValue("nhsno", form, request); User user = LegacySpringUtils.getUserManager().get(username); // String nhsno = UserUtils.retrieveUsersRealNhsnoBestGuess(username); NhsnoUnitcode nhsnoThing = new NhsnoUnitcode(nhsno, unitcode); request.getSession().setAttribute("patient", user); request.getSession().setAttribute("nhsnot", nhsnoThing); return LogonUtils.logonChecks(mapping, request); }
diff --git a/src/Waterflames/websend/ConfigHandler.java b/src/Waterflames/websend/ConfigHandler.java index b7942ed..009b748 100644 --- a/src/Waterflames/websend/ConfigHandler.java +++ b/src/Waterflames/websend/ConfigHandler.java @@ -1,173 +1,173 @@ package Waterflames.websend; import java.io.*; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.logging.Level; public class ConfigHandler { public Settings loadSettings() throws FileNotFoundException, IOException { // Prepare new settings map Settings settings = new Settings(); // Set default values settings.setPort(4445); settings.setDebugMode(false); settings.setServerActive(false); // Open file BufferedReader reader = openFile(); // Parse each line if line is not null String currentLine; while ((currentLine = reader.readLine()) != null) { parseLine(currentLine, settings); } return settings; } public void generateConfig() { // File declaration File websendDir = Main.getInstance().getDataFolder(); File configFile = new File(websendDir, "config.txt"); // Prepare file PrintWriter writer = null; try { if(!configFile.createNewFile()){ Main.getMainLogger().log(Level.WARNING, "Could not create new config file."); } writer = new PrintWriter(new FileWriter(configFile)); } catch (IOException ex) { Main.getMainLogger().info("Websend failed to create a new configuration file."); Main.getMainLogger().log(Level.SEVERE, null, ex); } // Fill file writer.println("#Configuration and settings file!"); writer.println("#Help: PASS: change the password to one of your choice (set the same in the server php file)."); writer.println("#Help: DEBUG_WEBSEND: shows debugging messages for easier tracking of bugs."); writer.println("#Help: SALT: adds a salt to the hashed password when sending over bukkit -> php connection."); writer.println("PASS=YourPassHere"); writer.println("#Optional settings. Remove the '#' to use."); writer.println("#URL=yoururl.com/page.php"); writer.println("#WEBLISTENER_ACTIVE=false/true"); writer.println("#ALTPORT=1234"); writer.println("#DEBUG_WEBSEND=false/true"); writer.println("#SALT=abc123"); writer.close(); } private BufferedReader openFile() throws FileNotFoundException { // File declaration File folder = Main.getInstance().getDataFolder(); File configFile = new File(folder, "config.txt"); // Reader opening BufferedReader reader = new BufferedReader(new FileReader(configFile)); return reader; } private void parseLine(String line, Settings settings) { // Is the line a comment? if (line.trim().startsWith("#")) { return; } else { // What value does this line contain? if (line.startsWith("RESPONSEURL=")) { // Clean and store value String value = line.replaceFirst("RESPONSEURL=", ""); settings.setResponseURL(value); } else if (line.startsWith("PASS=")) { String value = line.replaceFirst("PASS=", ""); settings.setPassword(value); } else if (line.startsWith("ALTPORT=")) { String value = line.replaceFirst("ALTPORT=", ""); int convertedValue = 0; try { convertedValue = Integer.parseInt(value.trim()); if (convertedValue == Main.getBukkitServer().getPort()) { Main.getMainLogger().log(Level.WARNING, "You are trying to host Websend on the minecraft server port! Choose a different port."); } } catch (Exception ex) { Main.getMainLogger().log(Level.SEVERE, "Websend failed to parse your new port value:" + value, ex); return; } settings.setPort(convertedValue); } else if (line.startsWith("DEBUG_WEBSEND=")) { String value = line.replaceFirst("DEBUG_WEBSEND=", ""); if (value.toLowerCase().trim().contains("true")) { settings.setDebugMode(true); } else { settings.setDebugMode(false); } } else if (line.startsWith("WEBLISTENER_ACTIVE=")) { String value = line.replaceFirst("WEBLISTENER_ACTIVE=", ""); if (value.toLowerCase().trim().contains("true")) { settings.setServerActive(true); } else { settings.setServerActive(false); } } else if (line.startsWith("URL=")) { String value = line.replaceFirst("URL=", ""); settings.setURL(value); } else if (line.startsWith("SALT=")) { String value = line.replaceFirst("SALT=", ""); settings.setSalt(value); - }if (line.startsWith("HASH_ALGORITHM=")){ + }else if (line.startsWith("HASH_ALGORITHM=")){ String value = line.replaceFirst("HASH_ALGORITHM=", ""); try { MessageDigest md = MessageDigest.getInstance(value); settings.setHashingAlgorithm(value); } catch (NoSuchAlgorithmException ex) { Main.getMainLogger().info("Hashing algorithm '"+value+"' is not available on this machine. Reverting to MD5"); } } else { Main.getMainLogger().info("WEBSEND ERROR: Error while parsing config file."); Main.getMainLogger().info("Invalid line: " + line); } } } }
true
true
private void parseLine(String line, Settings settings) { // Is the line a comment? if (line.trim().startsWith("#")) { return; } else { // What value does this line contain? if (line.startsWith("RESPONSEURL=")) { // Clean and store value String value = line.replaceFirst("RESPONSEURL=", ""); settings.setResponseURL(value); } else if (line.startsWith("PASS=")) { String value = line.replaceFirst("PASS=", ""); settings.setPassword(value); } else if (line.startsWith("ALTPORT=")) { String value = line.replaceFirst("ALTPORT=", ""); int convertedValue = 0; try { convertedValue = Integer.parseInt(value.trim()); if (convertedValue == Main.getBukkitServer().getPort()) { Main.getMainLogger().log(Level.WARNING, "You are trying to host Websend on the minecraft server port! Choose a different port."); } } catch (Exception ex) { Main.getMainLogger().log(Level.SEVERE, "Websend failed to parse your new port value:" + value, ex); return; } settings.setPort(convertedValue); } else if (line.startsWith("DEBUG_WEBSEND=")) { String value = line.replaceFirst("DEBUG_WEBSEND=", ""); if (value.toLowerCase().trim().contains("true")) { settings.setDebugMode(true); } else { settings.setDebugMode(false); } } else if (line.startsWith("WEBLISTENER_ACTIVE=")) { String value = line.replaceFirst("WEBLISTENER_ACTIVE=", ""); if (value.toLowerCase().trim().contains("true")) { settings.setServerActive(true); } else { settings.setServerActive(false); } } else if (line.startsWith("URL=")) { String value = line.replaceFirst("URL=", ""); settings.setURL(value); } else if (line.startsWith("SALT=")) { String value = line.replaceFirst("SALT=", ""); settings.setSalt(value); }if (line.startsWith("HASH_ALGORITHM=")){ String value = line.replaceFirst("HASH_ALGORITHM=", ""); try { MessageDigest md = MessageDigest.getInstance(value); settings.setHashingAlgorithm(value); } catch (NoSuchAlgorithmException ex) { Main.getMainLogger().info("Hashing algorithm '"+value+"' is not available on this machine. Reverting to MD5"); } } else { Main.getMainLogger().info("WEBSEND ERROR: Error while parsing config file."); Main.getMainLogger().info("Invalid line: " + line); } } }
private void parseLine(String line, Settings settings) { // Is the line a comment? if (line.trim().startsWith("#")) { return; } else { // What value does this line contain? if (line.startsWith("RESPONSEURL=")) { // Clean and store value String value = line.replaceFirst("RESPONSEURL=", ""); settings.setResponseURL(value); } else if (line.startsWith("PASS=")) { String value = line.replaceFirst("PASS=", ""); settings.setPassword(value); } else if (line.startsWith("ALTPORT=")) { String value = line.replaceFirst("ALTPORT=", ""); int convertedValue = 0; try { convertedValue = Integer.parseInt(value.trim()); if (convertedValue == Main.getBukkitServer().getPort()) { Main.getMainLogger().log(Level.WARNING, "You are trying to host Websend on the minecraft server port! Choose a different port."); } } catch (Exception ex) { Main.getMainLogger().log(Level.SEVERE, "Websend failed to parse your new port value:" + value, ex); return; } settings.setPort(convertedValue); } else if (line.startsWith("DEBUG_WEBSEND=")) { String value = line.replaceFirst("DEBUG_WEBSEND=", ""); if (value.toLowerCase().trim().contains("true")) { settings.setDebugMode(true); } else { settings.setDebugMode(false); } } else if (line.startsWith("WEBLISTENER_ACTIVE=")) { String value = line.replaceFirst("WEBLISTENER_ACTIVE=", ""); if (value.toLowerCase().trim().contains("true")) { settings.setServerActive(true); } else { settings.setServerActive(false); } } else if (line.startsWith("URL=")) { String value = line.replaceFirst("URL=", ""); settings.setURL(value); } else if (line.startsWith("SALT=")) { String value = line.replaceFirst("SALT=", ""); settings.setSalt(value); }else if (line.startsWith("HASH_ALGORITHM=")){ String value = line.replaceFirst("HASH_ALGORITHM=", ""); try { MessageDigest md = MessageDigest.getInstance(value); settings.setHashingAlgorithm(value); } catch (NoSuchAlgorithmException ex) { Main.getMainLogger().info("Hashing algorithm '"+value+"' is not available on this machine. Reverting to MD5"); } } else { Main.getMainLogger().info("WEBSEND ERROR: Error while parsing config file."); Main.getMainLogger().info("Invalid line: " + line); } } }
diff --git a/morphia/src/main/java/com/google/code/morphia/query/QueryImpl.java b/morphia/src/main/java/com/google/code/morphia/query/QueryImpl.java index 51252f7..1cadf08 100644 --- a/morphia/src/main/java/com/google/code/morphia/query/QueryImpl.java +++ b/morphia/src/main/java/com/google/code/morphia/query/QueryImpl.java @@ -1,550 +1,550 @@ package com.google.code.morphia.query; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.bson.types.CodeWScope; import org.bson.types.ObjectId; import com.google.code.morphia.Datastore; import com.google.code.morphia.DatastoreImpl; import com.google.code.morphia.Key; import com.google.code.morphia.annotations.Reference; import com.google.code.morphia.annotations.Serialized; import com.google.code.morphia.logging.MorphiaLogger; import com.google.code.morphia.logging.MorphiaLoggerFactory; import com.google.code.morphia.mapping.MappedClass; import com.google.code.morphia.mapping.MappedField; import com.google.code.morphia.mapping.Mapper; import com.google.code.morphia.mapping.MappingException; import com.google.code.morphia.mapping.Serializer; import com.google.code.morphia.mapping.cache.EntityCache; import com.google.code.morphia.utils.Assert; import com.google.code.morphia.utils.ReflectionUtils; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; /** * <p>Implementation of Query</p> * * @author Scott Hernandez * * @param <T> The type we will be querying for, and returning. */ public class QueryImpl<T> implements Query<T> { private static final MorphiaLogger log = MorphiaLoggerFactory.get(Mapper.class); private final EntityCache cache; private boolean validating = true; private Map<String, Object> query = null; private String[] fields = null; private Boolean includeFields = null; private BasicDBObjectBuilder sort = null; private DatastoreImpl ds = null; private DBCollection dbColl = null; private int offset = 0; private int limit = -1; private String indexHint; private Class<T> clazz = null; public QueryImpl(Class<T> clazz, DBCollection coll, Datastore ds) { this.clazz = clazz; this.ds = ((DatastoreImpl)ds); this.dbColl = coll; this.cache = this.ds.getMapper().createEntityCache(); } public QueryImpl(Class<T> clazz, DBCollection coll, Datastore ds, int offset, int limit) { this(clazz, coll, ds); this.offset = offset; this.limit = limit; } @SuppressWarnings("unchecked") public void setQueryObject(DBObject query) { this.query = (Map<String, Object>) query; } public DBObject getQueryObject() { return (query == null) ? null : new BasicDBObject(query); } public DBObject getFieldsObject() { if (fields == null || fields.length == 0) return null; Map<String, Boolean> fieldsFilter = new HashMap<String, Boolean>(); for(String field : this.fields) fieldsFilter.put(field, (includeFields)); return new BasicDBObject(fieldsFilter); } public DBObject getSortObject() { return (sort == null) ? null : sort.get(); } public long countAll() { return dbColl.getCount(getQueryObject()); } public DBCursor prepareCursor() { DBObject query = getQueryObject(); DBObject fields = getFieldsObject(); if (log.isDebugEnabled()) log.debug("Running query: " + query + ", " + fields + ",off:" + offset + ",limit:" + limit); DBCursor cursor = dbColl.find(query, fields); if (offset > 0) cursor.skip(offset); if (limit > 0) cursor.limit(limit); if (sort != null) cursor.sort(getSortObject()); if (indexHint != null) cursor.hint(indexHint); return cursor; } public Iterable<T> fetch() { DBCursor cursor = prepareCursor(); return new MorphiaIterator<T>(cursor, ds.getMapper(), clazz, dbColl.getName(), cache); } public Iterable<Key<T>> fetchKeys() { String[] oldFields = fields; Boolean oldInclude = includeFields; fields = new String[] {Mapper.ID_KEY}; includeFields = true; DBCursor cursor = prepareCursor(); fields = oldFields; includeFields = oldInclude; return new MorphiaKeyIterator<T>(cursor, ds.getMapper(), clazz, dbColl.getName()); } public List<T> asList() { List<T> results = new ArrayList<T>(); for(T ent : fetch()) results.add(ent); if (log.isTraceEnabled()) log.trace("\nasList: " + dbColl.getName() + "\n result size " + results.size() + "\n cache: " + (cache.stats()) + "\n for " + ((query != null) ? new BasicDBObject(query) : "{}")); return results; } public List<Key<T>> asKeyList() { List<Key<T>> results = new ArrayList<Key<T>>(); for(Key<T> key : fetchKeys()) results.add(key); return results; } public Iterable<T> fetchEmptyEntities() { String[] oldFields = fields; Boolean oldInclude = includeFields; fields = new String[] {Mapper.ID_KEY}; includeFields = true; Iterable<T> res = fetch(); fields = oldFields; includeFields = oldInclude; return res; } /** * Converts the textual operator (">", "<=", etc) into a FilterOperator. * Forgiving about the syntax; != and <> are NOT_EQUAL, = and == are EQUAL. */ protected FilterOperator translate(String operator) { operator = operator.trim(); if (operator.equals("=") || operator.equals("==")) return FilterOperator.EQUAL; else if (operator.equals(">")) return FilterOperator.GREATER_THAN; else if (operator.equals(">=")) return FilterOperator.GREATER_THAN_OR_EQUAL; else if (operator.equals("<")) return FilterOperator.LESS_THAN; else if (operator.equals("<=")) return FilterOperator.LESS_THAN_OR_EQUAL; else if (operator.equals("!=") || operator.equals("<>")) return FilterOperator.NOT_EQUAL; else if (operator.toLowerCase().equals("in")) return FilterOperator.IN; else if (operator.toLowerCase().equals("nin")) return FilterOperator.NOT_IN; else if (operator.toLowerCase().equals("all")) return FilterOperator.ALL; else if (operator.toLowerCase().equals("exists")) return FilterOperator.EXISTS; else if (operator.toLowerCase().equals("elem")) return FilterOperator.ELEMENT_MATCH; else if (operator.toLowerCase().equals("size")) return FilterOperator.SIZE; else throw new IllegalArgumentException("Unknown operator '" + operator + "'"); } @SuppressWarnings("unchecked") public Query<T> filter(String condition, Object value) { String[] parts = condition.trim().split(" "); if (parts.length < 1 || parts.length > 6) throw new IllegalArgumentException("'" + condition + "' is not a legal filter condition"); String prop = parts[0].trim(); FilterOperator op = (parts.length == 2) ? this.translate(parts[1]) : FilterOperator.EQUAL; //The field we are filtering on, in the java object MappedField mf = null; if (validating) mf = validate(prop, value); //TODO differentiate between the key/value for maps; we will just get the mf for the field, not which part we are looking for if (query == null) query = new HashMap<String, Object>(); Mapper mapr = ds.getMapper(); Object mappedValue; MappedClass mc = null; try { if (value != null && !ReflectionUtils.isPropertyType(value.getClass())) if (mf!=null && !mf.isTypeMongoCompatible()) mc=mapr.getMappedClass((mf.isSingleValue()) ? mf.getType() : mf.getSubType()); else mc = mapr.getMappedClass(value); } catch (Exception e) { //Ignore these. It is likely they related to mapping validation that is unimportant for queries (the query will fail/return-empty anyway) log.debug("Error during mapping filter criteria: ", e); } //convert the value to Key (DBRef) if it is a entity/@Reference or the field type is Key if ((mf!=null && (mf.hasAnnotation(Reference.class) || mf.getType().isAssignableFrom(Key.class))) || (mc != null && mc.getEntityAnnotation() != null)) { try { Key<?> k = (value instanceof Key) ? (Key<?>)value : ds.getKey(value); mappedValue = k.toRef(mapr); } catch (Exception e) { log.debug("Error converting value(" + value + ") to reference.", e); mappedValue = mapr.toMongoObject(value); } } else if (mf!=null && mf.hasAnnotation(Serialized.class)) try { mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression()); } catch (IOException e) { throw new RuntimeException(e); } else mappedValue = ReflectionUtils.asObjectIdMaybe(mapr.toMongoObject(value)); Class<?> type = (mappedValue != null) ? mappedValue.getClass() : null; //convert single values into lists for $in/$nin if (type != null && (op == FilterOperator.IN || op == FilterOperator.NOT_IN) && !type.isArray() && !ReflectionUtils.implementsAnyInterface(type, Iterable.class) ) { mappedValue = Collections.singletonList(mappedValue); } if (FilterOperator.EQUAL.equals(op)) query.put(prop, mappedValue); // no operator, prop equals value else { Object inner = query.get(prop); // operator within inner object if (!(inner instanceof Map)) { inner = new HashMap<String, Object>(); query.put(prop, inner); } - ((Map)inner).put(op.val(), mappedValue); + ((Map<String, Object>)inner).put(op.val(), mappedValue); } return this; } protected Query<T> filterWhere(Object obj){ if (query == null) { query = new HashMap<String, Object>(); } query.put(FilterOperator.WHERE.val(), obj); return this; } public Query<T> where(String js) { return filterWhere(js); } public Query<T> where(CodeWScope cws) { return filterWhere(cws); } public Query<T> enableValidation(){ validating = true; return this; } public Query<T> disableValidation(){ validating = false; return this; } /** Validate the path, and value type, returning the mappedfield for the field at the path */ private MappedField validate(String prop, Object value) { String[] parts = prop.split("\\."); // if (parts.length == 0) parts = new String[]{prop}; if (this.clazz == null) return null; MappedClass mc = ds.getMapper().getMappedClass(this.clazz); MappedField mf; for(int i=0; ; ) { String part = parts[i]; mf = mc.getMappedField(part); if (mf == null) { mf = mc.getMappedFieldByJavaField(part); if (mf != null) throw new MappingException("The field '" + part + "' is named '" + mf.getNameToStore() + "' in '" + this.clazz.getName()+ "' " + "(while validating - '" + prop + "'); Please use '" + mf.getNameToStore() + "' in your query."); else throw new MappingException("The field '" + part + "' could not be found in '" + this.clazz.getName()+ "' while validating - " + prop); } i++; if (mf.isMap()) { //skip the map key validation, and move to the next part i++; } //catch people trying to search into @Reference/@Serialized fields if (i < parts.length && !canQueryPast(mf)) throw new MappingException("Can not use dot-notation past '" + part + "' could not be found in '" + this.clazz.getName()+ "' while validating - " + prop); if (i >= parts.length) break; mc = ds.getMapper().getMappedClass((mf.isSingleValue()) ? mf.getType() : mf.getSubType()); } if ( (mf.isSingleValue() && !isCompatibleForQuery(mf.getType(), value)) || ((mf.isMultipleValues() && !isCompatibleForQuery(mf.getSubType(), value)))) { Throwable t = new Throwable(); log.warning("Datatypes for the query may be inconsistent; searching with an instance of " + value.getClass().getName() + " when the field " + mf.getDeclaringClass().getName()+ "." + mf.getJavaFieldName() + " is a " + mf.getType().getName()); log.debug("Location of warning:\r\n", t); } return mf; } /** Returns if the MappedField is a Reference or Serilized */ public static boolean canQueryPast(MappedField mf) { return !(mf.hasAnnotation(Reference.class) || mf.hasAnnotation(Serialized.class)); } public static boolean isCompatibleForQuery(Class<?> type, Object value) { if (value == null || type == null) return true; else if (value instanceof Integer && (int.class.equals(type) || long.class.equals(type) || Long.class.equals(type))) return true; else if ((value instanceof Integer || value instanceof Long) && (double.class.equals(type) || Double.class.equals(type))) return true; else if (value instanceof Pattern && String.class.equals(type)) return true; else if (value instanceof List) return true; else if (value instanceof ObjectId && String.class.equals(type)) return true; else if (!value.getClass().isAssignableFrom(type) && //hack to let Long match long, and so on !value.getClass().getSimpleName().toLowerCase().equals(type.getSimpleName().toLowerCase())) { return false; } return true; } public T get() { int oldLimit = limit; limit = 1; Iterator<T> it = fetch().iterator(); limit = oldLimit; return (it.hasNext()) ? it.next() : null ; } public Key<T> getKey() { int oldLimit = limit; limit = 1; Iterator<Key<T>> it = fetchKeys().iterator(); limit = oldLimit; return (it.hasNext()) ? it.next() : null; } public Query<T> limit(int value) { this.limit = value; return this; } public Query<T> skip(int value) { this.offset = value; return this; } public Query<T> offset(int value) { this.offset = value; return this; } public Query<T> order(String condition) { sort = BasicDBObjectBuilder.start(); String[] sorts = condition.split(","); for (String s : sorts) { s = s.trim(); int dir = 1; if (s.startsWith("-")) { dir = -1; s = s.substring(1).trim(); } sort = sort.add(s, dir); } return this; } public Iterator<T> iterator() { return fetch().iterator(); } public Class<T> getEntityClass() { return this.clazz; } public static class QueryFieldEndImpl<T> implements QueryFieldEnd<T>{ protected final String fieldExpr; protected final QueryImpl<T> query; public QueryFieldEndImpl(String fe, QueryImpl<T> q) {this.fieldExpr = fe; this.query=q;} public Query<T> startsWith(String prefix) { Assert.parametersNotNull("prefix",prefix); query.filter("" + fieldExpr, Pattern.compile("^" + prefix)); return query; } public Query<T> startsWithIgnoreCase(String prefix) { Assert.parametersNotNull("prefix", prefix); query.filter("" + fieldExpr, Pattern.compile("^" + prefix, Pattern.CASE_INSENSITIVE)); return query; } public Query<T> doesNotExist() { query.filter("" + fieldExpr + " exists", 0); return query; } public Query<T> equal(Object val) { query.filter(fieldExpr + " =", val); return query; } public Query<T> exists() { query.filter("" + fieldExpr + " exists", true); return query; } public Query<T> greaterThan(Object val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " >", val); return query; } public Query<T> greaterThanOrEq(Object val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " >=", val); return query; } public Query<T> hasThisOne(Object val) { query.filter(fieldExpr + " =", val); return query; } public Query<T> hasAllOf(Iterable<?> vals) { Assert.parametersNotNull("vals",vals); Assert.parameterNotEmpty(vals,"vals"); query.filter(fieldExpr + " all", vals); return query; } public Query<T> hasAnyOf(Iterable<?> vals) { Assert.parametersNotNull("vals",vals); Assert.parameterNotEmpty(vals,"vals"); query.filter(fieldExpr + " in", vals); return query; } public Query<T> hasThisElement(Object val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " elem", val); return query; } public Query<T> hasNoneOf(Iterable<?> vals) { Assert.parametersNotNull("vals",vals); Assert.parameterNotEmpty(vals,"vals"); query.filter(fieldExpr + " nin", vals); return query; } public Query<T> lessThan(Object val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " <", val); return query; } public Query<T> lessThanOrEq(Object val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " <=", val); return query; } public Query<T> notEqual(Object val) { query.filter(fieldExpr + " <>", val); return query; } public Query<T> sizeEq(int val) { Assert.parametersNotNull("val",val); query.filter(fieldExpr + " size", val); return query; } } public QueryFieldEnd<T> field(String fieldExpr) { return new QueryFieldEndImpl<T>(fieldExpr, this); } public Query<T> hintIndex(String idxName) { return null; } public Query<T> retrievedFields(boolean include, String...fields){ if (includeFields != null && include != includeFields) throw new IllegalStateException("You cannot mix include and excluded fields together!"); this.includeFields = include; this.fields = fields; return this; } }
true
true
public Query<T> filter(String condition, Object value) { String[] parts = condition.trim().split(" "); if (parts.length < 1 || parts.length > 6) throw new IllegalArgumentException("'" + condition + "' is not a legal filter condition"); String prop = parts[0].trim(); FilterOperator op = (parts.length == 2) ? this.translate(parts[1]) : FilterOperator.EQUAL; //The field we are filtering on, in the java object MappedField mf = null; if (validating) mf = validate(prop, value); //TODO differentiate between the key/value for maps; we will just get the mf for the field, not which part we are looking for if (query == null) query = new HashMap<String, Object>(); Mapper mapr = ds.getMapper(); Object mappedValue; MappedClass mc = null; try { if (value != null && !ReflectionUtils.isPropertyType(value.getClass())) if (mf!=null && !mf.isTypeMongoCompatible()) mc=mapr.getMappedClass((mf.isSingleValue()) ? mf.getType() : mf.getSubType()); else mc = mapr.getMappedClass(value); } catch (Exception e) { //Ignore these. It is likely they related to mapping validation that is unimportant for queries (the query will fail/return-empty anyway) log.debug("Error during mapping filter criteria: ", e); } //convert the value to Key (DBRef) if it is a entity/@Reference or the field type is Key if ((mf!=null && (mf.hasAnnotation(Reference.class) || mf.getType().isAssignableFrom(Key.class))) || (mc != null && mc.getEntityAnnotation() != null)) { try { Key<?> k = (value instanceof Key) ? (Key<?>)value : ds.getKey(value); mappedValue = k.toRef(mapr); } catch (Exception e) { log.debug("Error converting value(" + value + ") to reference.", e); mappedValue = mapr.toMongoObject(value); } } else if (mf!=null && mf.hasAnnotation(Serialized.class)) try { mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression()); } catch (IOException e) { throw new RuntimeException(e); } else mappedValue = ReflectionUtils.asObjectIdMaybe(mapr.toMongoObject(value)); Class<?> type = (mappedValue != null) ? mappedValue.getClass() : null; //convert single values into lists for $in/$nin if (type != null && (op == FilterOperator.IN || op == FilterOperator.NOT_IN) && !type.isArray() && !ReflectionUtils.implementsAnyInterface(type, Iterable.class) ) { mappedValue = Collections.singletonList(mappedValue); } if (FilterOperator.EQUAL.equals(op)) query.put(prop, mappedValue); // no operator, prop equals value else { Object inner = query.get(prop); // operator within inner object if (!(inner instanceof Map)) { inner = new HashMap<String, Object>(); query.put(prop, inner); } ((Map)inner).put(op.val(), mappedValue); } return this; }
public Query<T> filter(String condition, Object value) { String[] parts = condition.trim().split(" "); if (parts.length < 1 || parts.length > 6) throw new IllegalArgumentException("'" + condition + "' is not a legal filter condition"); String prop = parts[0].trim(); FilterOperator op = (parts.length == 2) ? this.translate(parts[1]) : FilterOperator.EQUAL; //The field we are filtering on, in the java object MappedField mf = null; if (validating) mf = validate(prop, value); //TODO differentiate between the key/value for maps; we will just get the mf for the field, not which part we are looking for if (query == null) query = new HashMap<String, Object>(); Mapper mapr = ds.getMapper(); Object mappedValue; MappedClass mc = null; try { if (value != null && !ReflectionUtils.isPropertyType(value.getClass())) if (mf!=null && !mf.isTypeMongoCompatible()) mc=mapr.getMappedClass((mf.isSingleValue()) ? mf.getType() : mf.getSubType()); else mc = mapr.getMappedClass(value); } catch (Exception e) { //Ignore these. It is likely they related to mapping validation that is unimportant for queries (the query will fail/return-empty anyway) log.debug("Error during mapping filter criteria: ", e); } //convert the value to Key (DBRef) if it is a entity/@Reference or the field type is Key if ((mf!=null && (mf.hasAnnotation(Reference.class) || mf.getType().isAssignableFrom(Key.class))) || (mc != null && mc.getEntityAnnotation() != null)) { try { Key<?> k = (value instanceof Key) ? (Key<?>)value : ds.getKey(value); mappedValue = k.toRef(mapr); } catch (Exception e) { log.debug("Error converting value(" + value + ") to reference.", e); mappedValue = mapr.toMongoObject(value); } } else if (mf!=null && mf.hasAnnotation(Serialized.class)) try { mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression()); } catch (IOException e) { throw new RuntimeException(e); } else mappedValue = ReflectionUtils.asObjectIdMaybe(mapr.toMongoObject(value)); Class<?> type = (mappedValue != null) ? mappedValue.getClass() : null; //convert single values into lists for $in/$nin if (type != null && (op == FilterOperator.IN || op == FilterOperator.NOT_IN) && !type.isArray() && !ReflectionUtils.implementsAnyInterface(type, Iterable.class) ) { mappedValue = Collections.singletonList(mappedValue); } if (FilterOperator.EQUAL.equals(op)) query.put(prop, mappedValue); // no operator, prop equals value else { Object inner = query.get(prop); // operator within inner object if (!(inner instanceof Map)) { inner = new HashMap<String, Object>(); query.put(prop, inner); } ((Map<String, Object>)inner).put(op.val(), mappedValue); } return this; }
diff --git a/common/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/AbstractXBeanDeployer.java b/common/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/AbstractXBeanDeployer.java index e7ec7d8b8..bfe9ad639 100644 --- a/common/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/AbstractXBeanDeployer.java +++ b/common/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/AbstractXBeanDeployer.java @@ -1,174 +1,179 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicemix.common.xbean; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.jbi.management.DeploymentException; import org.apache.servicemix.common.AbstractDeployer; import org.apache.servicemix.common.BaseLifeCycle; import org.apache.servicemix.common.Endpoint; import org.apache.servicemix.common.EndpointComponentContext; import org.apache.servicemix.common.ServiceMixComponent; import org.apache.servicemix.common.ServiceUnit; import org.apache.servicemix.jbi.container.JBIContainer; import org.apache.servicemix.jbi.framework.ComponentContextImpl; import org.apache.xbean.spring.context.FileSystemXmlApplicationContext; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.core.io.FileSystemResource; public class AbstractXBeanDeployer extends AbstractDeployer { public AbstractXBeanDeployer(ServiceMixComponent component) { super(component); } protected String getXBeanFile() { return "xbean"; } /* (non-Javadoc) * @see org.apache.servicemix.common.Deployer#canDeploy(java.lang.String, java.lang.String) */ public boolean canDeploy(String serviceUnitName, String serviceUnitRootPath) { File xbean = new File(serviceUnitRootPath, getXBeanFile() + ".xml"); if (logger.isDebugEnabled()) { logger.debug("Looking for " + xbean + ": " + xbean.exists()); } return xbean.exists(); } /* (non-Javadoc) * @see org.apache.servicemix.common.Deployer#deploy(java.lang.String, java.lang.String) */ public ServiceUnit deploy(String serviceUnitName, String serviceUnitRootPath) throws DeploymentException { AbstractXmlApplicationContext applicationContext = null; try { // Create service unit XBeanServiceUnit su = new XBeanServiceUnit(); su.setComponent(component); su.setName(serviceUnitName); su.setRootPath(serviceUnitRootPath); // Load configuration ClassLoader classLoader = component.getClass().getClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); File baseDir = new File(serviceUnitRootPath); String location = getXBeanFile(); applicationContext = createApplicationContext(serviceUnitRootPath); for (Iterator iter = getBeanFactoryPostProcessors(serviceUnitRootPath).iterator(); iter.hasNext();) { BeanFactoryPostProcessor processor = (BeanFactoryPostProcessor) iter.next(); applicationContext.addBeanFactoryPostProcessor(processor); } applicationContext.refresh(); su.setApplicationContext(applicationContext); // Use SU classloader Thread.currentThread().setContextClassLoader(su.getConfigurationClassLoader()); initApplicationContext(applicationContext); // Retrieve endpoints Collection<Endpoint> endpoints = getServices(applicationContext); for (Endpoint endpoint : endpoints) { endpoint.setServiceUnit(su); validate(endpoint); su.addEndpoint(endpoint); } validate(su); return su; } catch (Throwable e) { + logger.error(e); if (applicationContext != null) { - applicationContext.destroy(); + try { + applicationContext.destroy(); + } catch (Exception ne) { + logger.error(ne); + } } // There is a chance the thread context classloader has been changed by the xbean kernel, // so put back a good one Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); if (e instanceof DeploymentException) { throw ((DeploymentException) e); } else { throw failure("deploy", "Could not deploy xbean service unit", e); } } finally { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); } } protected void initApplicationContext(AbstractXmlApplicationContext applicationContext) throws Exception { } protected Collection<Endpoint> getServices(AbstractXmlApplicationContext applicationContext) throws Exception { return applicationContext.getBeansOfType(Endpoint.class).values(); } protected FileSystemXmlApplicationContext createApplicationContext(String serviceUnitRootPath) { File baseDir = new File(serviceUnitRootPath); String location = getXBeanFile(); return new FileSystemXmlApplicationContext( new String[] { "/" + baseDir.toURI().resolve(location).getPath() + ".xml" }, false, getXmlPreProcessors(serviceUnitRootPath)); } protected List getXmlPreProcessors(String serviceUnitRootPath) { JBIContainer container = null; try { container = ((ComponentContextImpl) component.getComponentContext()).getContainer(); } catch (Throwable t) { } ClassLoaderXmlPreprocessor classLoaderXmlPreprocessor = new ClassLoaderXmlPreprocessor(new File(serviceUnitRootPath), container); return Collections.singletonList(classLoaderXmlPreprocessor); } protected List getBeanFactoryPostProcessors(String serviceUnitRootPath) { List processors = new ArrayList(); // Property place holder PropertyPlaceholderConfigurer propertyPlaceholder = new PropertyPlaceholderConfigurer(); FileSystemResource propertiesFile = new FileSystemResource(new File(serviceUnitRootPath) + "/" + getXBeanFile() + ".properties"); if (propertiesFile.getFile().exists()) { propertyPlaceholder.setLocation(propertiesFile); processors.add(propertyPlaceholder); } // Parent beans map Map beans = getParentBeansMap(); if (beans != null) { processors.add(new ParentBeanFactoryPostProcessor(beans)); } return processors; } protected Map getParentBeansMap() { Map beans = new HashMap(); beans.put("context", new EndpointComponentContext(((BaseLifeCycle) component.getLifeCycle()).getContext())); beans.put("component", component); Object smx3 = component.getSmx3Container(); if (smx3 != null) { beans.put("container", smx3); } return beans; } }
false
true
public ServiceUnit deploy(String serviceUnitName, String serviceUnitRootPath) throws DeploymentException { AbstractXmlApplicationContext applicationContext = null; try { // Create service unit XBeanServiceUnit su = new XBeanServiceUnit(); su.setComponent(component); su.setName(serviceUnitName); su.setRootPath(serviceUnitRootPath); // Load configuration ClassLoader classLoader = component.getClass().getClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); File baseDir = new File(serviceUnitRootPath); String location = getXBeanFile(); applicationContext = createApplicationContext(serviceUnitRootPath); for (Iterator iter = getBeanFactoryPostProcessors(serviceUnitRootPath).iterator(); iter.hasNext();) { BeanFactoryPostProcessor processor = (BeanFactoryPostProcessor) iter.next(); applicationContext.addBeanFactoryPostProcessor(processor); } applicationContext.refresh(); su.setApplicationContext(applicationContext); // Use SU classloader Thread.currentThread().setContextClassLoader(su.getConfigurationClassLoader()); initApplicationContext(applicationContext); // Retrieve endpoints Collection<Endpoint> endpoints = getServices(applicationContext); for (Endpoint endpoint : endpoints) { endpoint.setServiceUnit(su); validate(endpoint); su.addEndpoint(endpoint); } validate(su); return su; } catch (Throwable e) { if (applicationContext != null) { applicationContext.destroy(); } // There is a chance the thread context classloader has been changed by the xbean kernel, // so put back a good one Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); if (e instanceof DeploymentException) { throw ((DeploymentException) e); } else { throw failure("deploy", "Could not deploy xbean service unit", e); } } finally { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); } }
public ServiceUnit deploy(String serviceUnitName, String serviceUnitRootPath) throws DeploymentException { AbstractXmlApplicationContext applicationContext = null; try { // Create service unit XBeanServiceUnit su = new XBeanServiceUnit(); su.setComponent(component); su.setName(serviceUnitName); su.setRootPath(serviceUnitRootPath); // Load configuration ClassLoader classLoader = component.getClass().getClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); File baseDir = new File(serviceUnitRootPath); String location = getXBeanFile(); applicationContext = createApplicationContext(serviceUnitRootPath); for (Iterator iter = getBeanFactoryPostProcessors(serviceUnitRootPath).iterator(); iter.hasNext();) { BeanFactoryPostProcessor processor = (BeanFactoryPostProcessor) iter.next(); applicationContext.addBeanFactoryPostProcessor(processor); } applicationContext.refresh(); su.setApplicationContext(applicationContext); // Use SU classloader Thread.currentThread().setContextClassLoader(su.getConfigurationClassLoader()); initApplicationContext(applicationContext); // Retrieve endpoints Collection<Endpoint> endpoints = getServices(applicationContext); for (Endpoint endpoint : endpoints) { endpoint.setServiceUnit(su); validate(endpoint); su.addEndpoint(endpoint); } validate(su); return su; } catch (Throwable e) { logger.error(e); if (applicationContext != null) { try { applicationContext.destroy(); } catch (Exception ne) { logger.error(ne); } } // There is a chance the thread context classloader has been changed by the xbean kernel, // so put back a good one Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); if (e instanceof DeploymentException) { throw ((DeploymentException) e); } else { throw failure("deploy", "Could not deploy xbean service unit", e); } } finally { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); } }
diff --git a/src/RayTracing/PointCloud.java b/src/RayTracing/PointCloud.java index 9d5e6ae..72295b2 100644 --- a/src/RayTracing/PointCloud.java +++ b/src/RayTracing/PointCloud.java @@ -1,218 +1,219 @@ package RayTracing; import java.util.ArrayList; import java.util.List; import Jama.Matrix; import Jama.SingularValueDecomposition; public class PointCloud { private List<Point> cloud; private int p_size; private Color color; private List<Vector> bbox_vectors; private PointCloud bbox; private final int bbox_point_size = 10; /** * @return the bbox */ public PointCloud getBbox() { return bbox; } /** * @param bbox * the bbox to set */ public void setBbox(PointCloud bbox) { this.bbox = bbox; } private Vector centerOfMass; private Vector centerOfBox; /** * @return the bbox_vectors */ public List<Vector> getBbox_vectors() { return bbox_vectors; } /** * @param bbox_vectors * the bbox_vectors to set */ public void setBbox_vectors(List<Vector> bbox_vectors) { this.bbox_vectors = bbox_vectors; } /** * @return the centerOfBox */ public Vector getCenterOfBox() { return centerOfBox; } /** * @param centerOfBox * the centerOfBox to set */ public void setCenterOfBox(Vector centerOfBox) { this.centerOfBox = centerOfBox; } /** * @param p_size * @param color */ public PointCloud(int p_size, Color color) { this.p_size = p_size; this.color = color; this.cloud = new ArrayList<Point>(); bbox_vectors = new ArrayList<Vector>(); bbox = null; } /** * @return the p_size */ public int getP_size() { return p_size; } /** * @param p_size * the p_size to set */ public void setP_size(int p_size) { this.p_size = p_size; } /** * @return the color */ public Color getColor() { return color; } /** * @param color * the color to set */ public void setColor(Color color) { this.color = color; } public void addPoint(Point p) { cloud.add(p); } /** * @return the cloud */ public List<Point> getCloud() { return cloud; } /** * @param cloud * the cloud to set */ public void setCloud(List<Point> cloud) { this.cloud = cloud; } public void calcBBox() { centerOfMass = centerOfMass(); - int offset = (int) Math.floor(cloud.size() / 1000.0d); + int points = Math.min(cloud.size(), 1000); + int offset = (int) Math.floor((double) cloud.size() / (double) points); double[][] m = new double[3][1000]; - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < points; i++) { m[0][i] = cloud.get(i * offset).getP().getX() - centerOfMass.getX(); m[1][i] = cloud.get(i * offset).getP().getY() - centerOfMass.getY(); m[2][i] = cloud.get(i * offset).getP().getZ() - centerOfMass.getZ(); } Matrix mat = new Matrix(m); SingularValueDecomposition svd = new SingularValueDecomposition(mat); Matrix u = svd.getU(); for (int i = 0; i < 3; i++) { Vector v = new Vector(u.get(0, i), u.get(1, i), u.get(2, i)); Vector.normalize(v); double neg_len = 0, pos_len = 0; for (int n = 0; n < cloud.size(); n++) { double dotp = Vector.dotProd( v, Vector.sum(cloud.get(n).getP(), Vector.multiplyByConst(centerOfMass, -1))); if (neg_len > dotp) { neg_len = dotp; } if (pos_len < dotp) { pos_len = dotp; } } bbox_vectors.add(Vector.multiplyByConst(v, pos_len)); bbox_vectors.add(Vector.multiplyByConst(v, neg_len)); } bbox = new PointCloud(bbox_point_size, new Color(0, 0, 0.5)); for (int i = 0; i < 2; i++) { Point p1 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(2)), bbox_vectors.get(4)), centerOfMass), null, bbox); Point p2 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(2)), bbox_vectors.get(5)), centerOfMass), null, bbox); Point p3 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(3)), bbox_vectors.get(5)), centerOfMass), null, bbox); Point p4 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(3)), bbox_vectors.get(4)), centerOfMass), null, bbox); bbox.addPoint(p1); bbox.addPoint(p2); bbox.addPoint(p3); bbox.addPoint(p4); } } /** * @return the centerOfMass */ public Vector getCenterOfMass() { return centerOfMass; } /** * @param centerOfMass * the centerOfMass to set */ public void setCenterOfMass(Vector centerOfMass) { this.centerOfMass = centerOfMass; } public Vector centerOfMass() { double sumX = 0, sumY = 0, sumZ = 0; double size = cloud.size(); for (int i = 0; i < size; i++) { sumX += cloud.get(i).getP().getX(); sumY += cloud.get(i).getP().getY(); sumZ += cloud.get(i).getP().getZ(); } return new Vector(sumX / size, sumY / size, sumZ / size); } public String toString() { String s = ""; for (int i = 0; i < bbox.getCloud().size(); i++) { s += bbox.getCloud().get(i).getP() + "\n"; } return s; } }
false
true
public void calcBBox() { centerOfMass = centerOfMass(); int offset = (int) Math.floor(cloud.size() / 1000.0d); double[][] m = new double[3][1000]; for (int i = 0; i < 1000; i++) { m[0][i] = cloud.get(i * offset).getP().getX() - centerOfMass.getX(); m[1][i] = cloud.get(i * offset).getP().getY() - centerOfMass.getY(); m[2][i] = cloud.get(i * offset).getP().getZ() - centerOfMass.getZ(); } Matrix mat = new Matrix(m); SingularValueDecomposition svd = new SingularValueDecomposition(mat); Matrix u = svd.getU(); for (int i = 0; i < 3; i++) { Vector v = new Vector(u.get(0, i), u.get(1, i), u.get(2, i)); Vector.normalize(v); double neg_len = 0, pos_len = 0; for (int n = 0; n < cloud.size(); n++) { double dotp = Vector.dotProd( v, Vector.sum(cloud.get(n).getP(), Vector.multiplyByConst(centerOfMass, -1))); if (neg_len > dotp) { neg_len = dotp; } if (pos_len < dotp) { pos_len = dotp; } } bbox_vectors.add(Vector.multiplyByConst(v, pos_len)); bbox_vectors.add(Vector.multiplyByConst(v, neg_len)); } bbox = new PointCloud(bbox_point_size, new Color(0, 0, 0.5)); for (int i = 0; i < 2; i++) { Point p1 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(2)), bbox_vectors.get(4)), centerOfMass), null, bbox); Point p2 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(2)), bbox_vectors.get(5)), centerOfMass), null, bbox); Point p3 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(3)), bbox_vectors.get(5)), centerOfMass), null, bbox); Point p4 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(3)), bbox_vectors.get(4)), centerOfMass), null, bbox); bbox.addPoint(p1); bbox.addPoint(p2); bbox.addPoint(p3); bbox.addPoint(p4); } }
public void calcBBox() { centerOfMass = centerOfMass(); int points = Math.min(cloud.size(), 1000); int offset = (int) Math.floor((double) cloud.size() / (double) points); double[][] m = new double[3][1000]; for (int i = 0; i < points; i++) { m[0][i] = cloud.get(i * offset).getP().getX() - centerOfMass.getX(); m[1][i] = cloud.get(i * offset).getP().getY() - centerOfMass.getY(); m[2][i] = cloud.get(i * offset).getP().getZ() - centerOfMass.getZ(); } Matrix mat = new Matrix(m); SingularValueDecomposition svd = new SingularValueDecomposition(mat); Matrix u = svd.getU(); for (int i = 0; i < 3; i++) { Vector v = new Vector(u.get(0, i), u.get(1, i), u.get(2, i)); Vector.normalize(v); double neg_len = 0, pos_len = 0; for (int n = 0; n < cloud.size(); n++) { double dotp = Vector.dotProd( v, Vector.sum(cloud.get(n).getP(), Vector.multiplyByConst(centerOfMass, -1))); if (neg_len > dotp) { neg_len = dotp; } if (pos_len < dotp) { pos_len = dotp; } } bbox_vectors.add(Vector.multiplyByConst(v, pos_len)); bbox_vectors.add(Vector.multiplyByConst(v, neg_len)); } bbox = new PointCloud(bbox_point_size, new Color(0, 0, 0.5)); for (int i = 0; i < 2; i++) { Point p1 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(2)), bbox_vectors.get(4)), centerOfMass), null, bbox); Point p2 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(2)), bbox_vectors.get(5)), centerOfMass), null, bbox); Point p3 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(3)), bbox_vectors.get(5)), centerOfMass), null, bbox); Point p4 = new Point(Vector.sum( Vector.sum(Vector.sum(bbox_vectors.get(i), bbox_vectors.get(3)), bbox_vectors.get(4)), centerOfMass), null, bbox); bbox.addPoint(p1); bbox.addPoint(p2); bbox.addPoint(p3); bbox.addPoint(p4); } }
diff --git a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/admin/GuestBookResponseDataPage.java b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/admin/GuestBookResponseDataPage.java index b407da58..dd84c471 100644 --- a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/admin/GuestBookResponseDataPage.java +++ b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/admin/GuestBookResponseDataPage.java @@ -1,121 +1,124 @@ /* Copyright (C) 2005-2012, by the President and Fellows of Harvard College. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Dataverse Network - A web application to share, preserve and analyze research data. Developed at the Institute for Quantitative Social Science, Harvard University. Version 3.1. */ package edu.harvard.iq.dvn.core.web.admin; import edu.harvard.iq.dvn.core.vdc.*; import edu.harvard.iq.dvn.core.web.common.VDCBaseBean; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.ejb.EJB; import javax.faces.bean.ViewScoped; import javax.inject.Named; /** * * @author skraffmiller */ @ViewScoped @Named("GuestBookResponseDataPage") public class GuestBookResponseDataPage extends VDCBaseBean implements java.io.Serializable { @EJB GuestBookResponseServiceBean guestBookResponseServiceBean; private List<GuestBookResponse> guestBookResponses = new ArrayList(); private List<GuestBookResponseDisplay> guestBookResponsesDisplay = new ArrayList(); private List<GuestBookResponse> guestBookResponsesAll = new ArrayList(); private List<String> columnHeadings = new ArrayList(); private List<Long> customQuestionIds = new ArrayList(); private VDC vdc; public void init() { guestBookResponsesAll = guestBookResponseServiceBean.findAll(); vdc = getVDCRequestBean().getCurrentVDC(); for (GuestBookResponse gbr : guestBookResponsesAll) { if (gbr.getStudy().getOwner().equals(vdc)) { guestBookResponses.add(gbr); if (!gbr.getCustomQuestionResponses().isEmpty()) { for (CustomQuestionResponse cqr : gbr.getCustomQuestionResponses()) { if (!customQuestionIds.contains(cqr.getCustomQuestion().getId())) { customQuestionIds.add(cqr.getCustomQuestion().getId()); columnHeadings.add(cqr.getCustomQuestion().getQuestionString()); } } } } } if (!customQuestionIds.isEmpty()) { for (GuestBookResponse gbr : guestBookResponses) { GuestBookResponseDisplay guestBookResponseDisplay = new GuestBookResponseDisplay(); guestBookResponseDisplay.setGuestBookResponse(gbr); List<String> customQuestionResponseStrings = new ArrayList(customQuestionIds.size()); + for (int i=0; i<customQuestionIds.size(); i++){ + customQuestionResponseStrings.add(i, ""); + } if (!gbr.getCustomQuestionResponses().isEmpty()) { for (Long id : customQuestionIds) { int index = customQuestionIds.indexOf(id); for (CustomQuestionResponse cqr : gbr.getCustomQuestionResponses()) { if (cqr.getCustomQuestion().getId().equals(id)) { - customQuestionResponseStrings.add(index, cqr.getResponse()); + customQuestionResponseStrings.set(index, cqr.getResponse()); } } } } guestBookResponseDisplay.setCustomQuestionResponses(customQuestionResponseStrings); guestBookResponsesDisplay.add(guestBookResponseDisplay); } } else { for (GuestBookResponse gbr : guestBookResponses) { GuestBookResponseDisplay guestBookResponseDisplay = new GuestBookResponseDisplay(); guestBookResponseDisplay.setGuestBookResponse(gbr); guestBookResponsesDisplay.add(guestBookResponseDisplay); } } } public List<GuestBookResponse> getGuestBookResponses() { return guestBookResponses; } public void setGuestBookResponses(List<GuestBookResponse> guestBookResponses) { this.guestBookResponses = guestBookResponses; } public List<String> getColumnHeadings() { return columnHeadings; } public void setColumnHeadings(List<String> columnHeadings) { this.columnHeadings = columnHeadings; } public List<GuestBookResponseDisplay> getGuestBookResponsesDisplay() { return guestBookResponsesDisplay; } public void setGuestBookResponsesDisplay(List<GuestBookResponseDisplay> guestBookResponsesDisplay) { this.guestBookResponsesDisplay = guestBookResponsesDisplay; } public String cancel_action() { return "/admin/OptionsPage?faces-redirect=true&vdcId=" + getVDCRequestBean().getCurrentVDC().getId(); } }
false
true
public void init() { guestBookResponsesAll = guestBookResponseServiceBean.findAll(); vdc = getVDCRequestBean().getCurrentVDC(); for (GuestBookResponse gbr : guestBookResponsesAll) { if (gbr.getStudy().getOwner().equals(vdc)) { guestBookResponses.add(gbr); if (!gbr.getCustomQuestionResponses().isEmpty()) { for (CustomQuestionResponse cqr : gbr.getCustomQuestionResponses()) { if (!customQuestionIds.contains(cqr.getCustomQuestion().getId())) { customQuestionIds.add(cqr.getCustomQuestion().getId()); columnHeadings.add(cqr.getCustomQuestion().getQuestionString()); } } } } } if (!customQuestionIds.isEmpty()) { for (GuestBookResponse gbr : guestBookResponses) { GuestBookResponseDisplay guestBookResponseDisplay = new GuestBookResponseDisplay(); guestBookResponseDisplay.setGuestBookResponse(gbr); List<String> customQuestionResponseStrings = new ArrayList(customQuestionIds.size()); if (!gbr.getCustomQuestionResponses().isEmpty()) { for (Long id : customQuestionIds) { int index = customQuestionIds.indexOf(id); for (CustomQuestionResponse cqr : gbr.getCustomQuestionResponses()) { if (cqr.getCustomQuestion().getId().equals(id)) { customQuestionResponseStrings.add(index, cqr.getResponse()); } } } } guestBookResponseDisplay.setCustomQuestionResponses(customQuestionResponseStrings); guestBookResponsesDisplay.add(guestBookResponseDisplay); } } else { for (GuestBookResponse gbr : guestBookResponses) { GuestBookResponseDisplay guestBookResponseDisplay = new GuestBookResponseDisplay(); guestBookResponseDisplay.setGuestBookResponse(gbr); guestBookResponsesDisplay.add(guestBookResponseDisplay); } } }
public void init() { guestBookResponsesAll = guestBookResponseServiceBean.findAll(); vdc = getVDCRequestBean().getCurrentVDC(); for (GuestBookResponse gbr : guestBookResponsesAll) { if (gbr.getStudy().getOwner().equals(vdc)) { guestBookResponses.add(gbr); if (!gbr.getCustomQuestionResponses().isEmpty()) { for (CustomQuestionResponse cqr : gbr.getCustomQuestionResponses()) { if (!customQuestionIds.contains(cqr.getCustomQuestion().getId())) { customQuestionIds.add(cqr.getCustomQuestion().getId()); columnHeadings.add(cqr.getCustomQuestion().getQuestionString()); } } } } } if (!customQuestionIds.isEmpty()) { for (GuestBookResponse gbr : guestBookResponses) { GuestBookResponseDisplay guestBookResponseDisplay = new GuestBookResponseDisplay(); guestBookResponseDisplay.setGuestBookResponse(gbr); List<String> customQuestionResponseStrings = new ArrayList(customQuestionIds.size()); for (int i=0; i<customQuestionIds.size(); i++){ customQuestionResponseStrings.add(i, ""); } if (!gbr.getCustomQuestionResponses().isEmpty()) { for (Long id : customQuestionIds) { int index = customQuestionIds.indexOf(id); for (CustomQuestionResponse cqr : gbr.getCustomQuestionResponses()) { if (cqr.getCustomQuestion().getId().equals(id)) { customQuestionResponseStrings.set(index, cqr.getResponse()); } } } } guestBookResponseDisplay.setCustomQuestionResponses(customQuestionResponseStrings); guestBookResponsesDisplay.add(guestBookResponseDisplay); } } else { for (GuestBookResponse gbr : guestBookResponses) { GuestBookResponseDisplay guestBookResponseDisplay = new GuestBookResponseDisplay(); guestBookResponseDisplay.setGuestBookResponse(gbr); guestBookResponsesDisplay.add(guestBookResponseDisplay); } } }
diff --git a/src/org/pneditor/editor/actions/AboutAction.java b/src/org/pneditor/editor/actions/AboutAction.java index 7a198f7..14e0b71 100644 --- a/src/org/pneditor/editor/actions/AboutAction.java +++ b/src/org/pneditor/editor/actions/AboutAction.java @@ -1,70 +1,70 @@ /* * Copyright (C) 2008-2010 Martin Riesz <riesz.martin at gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.pneditor.editor.actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.JOptionPane; import org.pneditor.editor.Root; import org.pneditor.util.GraphicsTools; /** * * @author Martin Riesz <riesz.martin at gmail.com> */ public class AboutAction extends AbstractAction { private Root root; public AboutAction(Root root) { this.root = root; String name = "About..."; putValue(NAME, name); putValue(SMALL_ICON, GraphicsTools.getIcon("pneditor/About16.gif")); putValue(SHORT_DESCRIPTION, name); } public void actionPerformed(ActionEvent e) { JOptionPane.showOptionDialog( root.getParentFrame(), root.getAppLongName() + "\n" + "http://www.pneditor.org/\n" + "\n" + - "Contributors:\n" + - "Martin Riesz, Milka Knapereková\n" + + "Author: Martin Riesz\n" + + "Contributors: Milka Knapereková\n" + "\n" + "This program is free software: you can redistribute it and/or modify\n" + "it under the terms of the GNU General Public License as published by\n" + "the Free Software Foundation, either version 3 of the License, or\n" + "(at your option) any later version.\n" + "\n" + "This program is distributed in the hope that it will be useful,\n" + "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + "GNU General Public License for more details.\n" + "You should have received a copy of the GNU General Public License\n" + "along with this program. If not, see <http://www.gnu.org/licenses/>.", "About", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] {"OK"}, "OK"); } }
true
true
public void actionPerformed(ActionEvent e) { JOptionPane.showOptionDialog( root.getParentFrame(), root.getAppLongName() + "\n" + "http://www.pneditor.org/\n" + "\n" + "Contributors:\n" + "Martin Riesz, Milka Knapereková\n" + "\n" + "This program is free software: you can redistribute it and/or modify\n" + "it under the terms of the GNU General Public License as published by\n" + "the Free Software Foundation, either version 3 of the License, or\n" + "(at your option) any later version.\n" + "\n" + "This program is distributed in the hope that it will be useful,\n" + "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + "GNU General Public License for more details.\n" + "You should have received a copy of the GNU General Public License\n" + "along with this program. If not, see <http://www.gnu.org/licenses/>.", "About", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] {"OK"}, "OK"); }
public void actionPerformed(ActionEvent e) { JOptionPane.showOptionDialog( root.getParentFrame(), root.getAppLongName() + "\n" + "http://www.pneditor.org/\n" + "\n" + "Author: Martin Riesz\n" + "Contributors: Milka Knapereková\n" + "\n" + "This program is free software: you can redistribute it and/or modify\n" + "it under the terms of the GNU General Public License as published by\n" + "the Free Software Foundation, either version 3 of the License, or\n" + "(at your option) any later version.\n" + "\n" + "This program is distributed in the hope that it will be useful,\n" + "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + "GNU General Public License for more details.\n" + "You should have received a copy of the GNU General Public License\n" + "along with this program. If not, see <http://www.gnu.org/licenses/>.", "About", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new String[] {"OK"}, "OK"); }
diff --git a/src/main/java/org/jfrog/hudson/ArtifactoryServer.java b/src/main/java/org/jfrog/hudson/ArtifactoryServer.java index 763a837a..63b7f4d5 100644 --- a/src/main/java/org/jfrog/hudson/ArtifactoryServer.java +++ b/src/main/java/org/jfrog/hudson/ArtifactoryServer.java @@ -1,237 +1,238 @@ /* * Copyright (C) 2010 JFrog Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jfrog.hudson; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.thoughtworks.xstream.converters.UnmarshallingContext; import hudson.ProxyConfiguration; import hudson.model.Hudson; import hudson.util.Scrambler; import hudson.util.XStream2; import org.apache.commons.lang.StringUtils; import org.jfrog.build.api.util.NullLog; import org.jfrog.build.client.ArtifactoryBuildInfoClient; import org.jfrog.build.client.ArtifactoryHttpClient; import org.jfrog.hudson.util.Credentials; import org.kohsuke.stapler.DataBoundConstructor; import java.io.IOException; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Represents an artifactory instance. * * @author Yossi Shaul */ public class ArtifactoryServer { private static final Logger log = Logger.getLogger(ArtifactoryServer.class.getName()); private static final int DEFAULT_CONNECTION_TIMEOUT = 300; // 5 Minutes private final String url; private final Credentials deployerCredentials; private Credentials resolverCredentials; // Network timeout in milliseconds to use both for connection establishment and for unanswered requests private int timeout = DEFAULT_CONNECTION_TIMEOUT; private boolean bypassProxy; /** * List of repository keys, last time we checked. Copy on write semantics. */ private transient volatile List<String> repositories; private transient volatile List<VirtualRepository> virtualRepositories; @DataBoundConstructor public ArtifactoryServer(String url, Credentials deployerCredentials, Credentials resolverCredentials, int timeout, boolean bypassProxy) { this.url = StringUtils.removeEnd(url, "/"); this.deployerCredentials = deployerCredentials; this.resolverCredentials = resolverCredentials; this.timeout = timeout > 0 ? timeout : DEFAULT_CONNECTION_TIMEOUT; this.bypassProxy = bypassProxy; } public String getName() { return url; } public String getUrl() { return url; } public Credentials getDeployerCredentials() { return deployerCredentials; } public Credentials getResolverCredentials() { return resolverCredentials; } public int getTimeout() { return timeout; } public boolean isBypassProxy() { return bypassProxy; } public List<String> getRepositoryKeys() { Credentials resolvingCredentials = getResolvingCredentials(); try { ArtifactoryBuildInfoClient client = createArtifactoryClient(resolvingCredentials.getUsername(), resolvingCredentials.getPassword()); repositories = client.getLocalRepositoriesKeys(); } catch (IOException e) { log.log(Level.WARNING, "Failed to obtain list of local repositories: " + e.getMessage()); } return repositories; } public List<String> getReleaseRepositoryKeysFirst() { List<String> repositoryKeys = getRepositoryKeys(); if (repositoryKeys == null || repositoryKeys.isEmpty()) { return Lists.newArrayList(); } Collections.sort(repositoryKeys, new RepositoryComparator()); return repositoryKeys; } public List<String> getSnapshotRepositoryKeysFirst() { List<String> repositoryKeys = getRepositoryKeys(); if (repositoryKeys == null || repositoryKeys.isEmpty()) { return Lists.newArrayList(); } Collections.sort(repositoryKeys, Collections.reverseOrder(new RepositoryComparator())); return repositoryKeys; } private static class RepositoryComparator implements Comparator<String> { public int compare(String o1, String o2) { if (o1.contains("snapshot") && !o2.contains("snapshot")) { return 1; } else { return -1; } } } public List<VirtualRepository> getVirtualRepositoryKeys() { Credentials resolvingCredentials = getResolvingCredentials(); try { ArtifactoryBuildInfoClient client = createArtifactoryClient(resolvingCredentials.getUsername(), resolvingCredentials.getPassword()); List<String> keys = client.getVirtualRepositoryKeys(); virtualRepositories = Lists.newArrayList(Lists.transform(keys, new Function<String, VirtualRepository>() { public VirtualRepository apply(String from) { return new VirtualRepository(from, from); } })); } catch (IOException e) { log.log(Level.WARNING, "Failed to obtain list of virtual repositories: " + e.getMessage()); return Lists.newArrayList(); } virtualRepositories - .add(0, new VirtualRepository("- To use Artifactory for resolution select a virtual repository -", "")); + .add(0, new VirtualRepository("-- To use Artifactory for resolution select a virtual repository --", + "")); return virtualRepositories; } public boolean isPowerPack() { Credentials resolvingCredentials = getResolvingCredentials(); try { ArtifactoryHttpClient client = new ArtifactoryHttpClient(url, resolvingCredentials.getUsername(), resolvingCredentials.getPassword(), new NullLog()); ArtifactoryHttpClient.Version version = client.getVersion(); return version.hasAddons(); } catch (IOException e) { log.log(Level.WARNING, "Failed to obtain list of virtual repositories: " + e.getMessage()); } return false; } public ArtifactoryBuildInfoClient createArtifactoryClient(String userName, String password) { ArtifactoryBuildInfoClient client = new ArtifactoryBuildInfoClient(url, userName, password, new NullLog()); client.setConnectionTimeout(timeout); ProxyConfiguration proxyConfiguration = Hudson.getInstance().proxy; if (!bypassProxy && proxyConfiguration != null) { client.setProxyConfiguration(proxyConfiguration.name, proxyConfiguration.port, proxyConfiguration.getUserName(), proxyConfiguration.getPassword()); } return client; } /** * When upgrading from an older version, a user might have resolver credentials as local variables. This converter * Will check for existing old resolver credentials and "move" them to a credentials object instead */ public static final class ConverterImpl extends XStream2.PassthruConverter<ArtifactoryServer> { public ConverterImpl(XStream2 xstream) { super(xstream); } @Override protected void callback(ArtifactoryServer server, UnmarshallingContext context) { if (StringUtils.isNotBlank(server.userName) && (server.resolverCredentials == null)) { server.resolverCredentials = new Credentials(server.userName, Scrambler.descramble(server.password)); } } } /** * Decides what are the preferred credentials to use for resolving the repo keys of the server * * @return Preferred credentials for repo resolving */ public Credentials getResolvingCredentials() { if (getResolverCredentials() != null) { return getResolverCredentials(); } if (getDeployerCredentials() != null) { return getDeployerCredentials(); } return new Credentials(null, null); } /** * @deprecated: Use org.jfrog.hudson.DeployerOverrider#getOverridingDeployerCredentials() */ @Deprecated private transient String userName; /** * @deprecated: Use org.jfrog.hudson.DeployerOverrider#getOverridingDeployerCredentials() */ @Deprecated private transient String password; // base64 scrambled password }
true
true
public List<VirtualRepository> getVirtualRepositoryKeys() { Credentials resolvingCredentials = getResolvingCredentials(); try { ArtifactoryBuildInfoClient client = createArtifactoryClient(resolvingCredentials.getUsername(), resolvingCredentials.getPassword()); List<String> keys = client.getVirtualRepositoryKeys(); virtualRepositories = Lists.newArrayList(Lists.transform(keys, new Function<String, VirtualRepository>() { public VirtualRepository apply(String from) { return new VirtualRepository(from, from); } })); } catch (IOException e) { log.log(Level.WARNING, "Failed to obtain list of virtual repositories: " + e.getMessage()); return Lists.newArrayList(); } virtualRepositories .add(0, new VirtualRepository("- To use Artifactory for resolution select a virtual repository -", "")); return virtualRepositories; }
public List<VirtualRepository> getVirtualRepositoryKeys() { Credentials resolvingCredentials = getResolvingCredentials(); try { ArtifactoryBuildInfoClient client = createArtifactoryClient(resolvingCredentials.getUsername(), resolvingCredentials.getPassword()); List<String> keys = client.getVirtualRepositoryKeys(); virtualRepositories = Lists.newArrayList(Lists.transform(keys, new Function<String, VirtualRepository>() { public VirtualRepository apply(String from) { return new VirtualRepository(from, from); } })); } catch (IOException e) { log.log(Level.WARNING, "Failed to obtain list of virtual repositories: " + e.getMessage()); return Lists.newArrayList(); } virtualRepositories .add(0, new VirtualRepository("-- To use Artifactory for resolution select a virtual repository --", "")); return virtualRepositories; }
diff --git a/Annis-Service/src/main/java/annis/dao/GraphExtractor.java b/Annis-Service/src/main/java/annis/dao/GraphExtractor.java index 1d5067737..9b834c4cf 100644 --- a/Annis-Service/src/main/java/annis/dao/GraphExtractor.java +++ b/Annis-Service/src/main/java/annis/dao/GraphExtractor.java @@ -1,392 +1,398 @@ /* * Copyright 2010 thomas. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * under the License. */ package annis.dao; import static annis.sqlgen.TableAccessStrategy.FACTS_TABLE; import annis.model.AnnisNode; import annis.model.Annotation; import annis.model.AnnotationGraph; import annis.model.Edge; import annis.sqlgen.TableAccessStrategy; import java.math.BigDecimal; import java.sql.Array; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.apache.log4j.Logger; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ResultSetExtractor; import org.springframework.jdbc.core.simple.ParameterizedSingleColumnRowMapper; /** * * @author thomas */ public class GraphExtractor implements ResultSetExtractor { private static final Logger log = Logger.getLogger(GraphExtractor.class); private String matchedNodesViewName; private AnnotationRowMapper nodeAnnotationRowMapper; private AnnotationRowMapper edgeAnnotationRowMapper; private EdgeRowMapper edgeRowMapper; private AnnisNodeRowMapper annisNodeRowMapper; public GraphExtractor() { // FIXME: totally ugly, but the query has fixed column names (and needs its own column aliasing) // TableAccessStrategyFactory wants a corpus selection strategy // solution: build AnnisNodes with API and refactor SqlGenerator to accept GROUP BY nodes Map<String, String> nodeColumns = new HashMap<String, String>(); nodeColumns.put("namespace", "node_namespace"); nodeColumns.put("name", "node_name"); Map<String, String> nodeAnnotationColumns = new HashMap<String, String>(); nodeAnnotationColumns.put("node_ref", "id"); nodeAnnotationColumns.put("namespace", "node_annotation_namespace"); nodeAnnotationColumns.put("name", "node_annotation_name"); nodeAnnotationColumns.put("value", "node_annotation_value"); Map<String, String> edgeAnnotationColumns = new HashMap<String, String>(); nodeAnnotationColumns.put("rank_ref", "pre"); edgeAnnotationColumns.put("namespace", "edge_annotation_namespace"); edgeAnnotationColumns.put("name", "edge_annotation_name"); edgeAnnotationColumns.put("value", "edge_annotation_value"); Map<String, String> edgeColumns = new HashMap<String, String>(); edgeColumns.put("node_ref", "id"); edgeColumns.put("name", "edge_name"); edgeColumns.put("namespace", "edge_name"); Map<String, Map<String, String>> columnAliases = new HashMap<String, Map<String, String>>(); columnAliases.put(TableAccessStrategy.NODE_TABLE, nodeColumns); columnAliases.put(TableAccessStrategy.NODE_ANNOTATION_TABLE, nodeAnnotationColumns); columnAliases.put(TableAccessStrategy.EDGE_ANNOTATION_TABLE, edgeAnnotationColumns); columnAliases.put(TableAccessStrategy.RANK_TABLE, edgeColumns); TableAccessStrategy tableAccessStrategy = new TableAccessStrategy(null); tableAccessStrategy.setColumnAliases(columnAliases); edgeRowMapper = new EdgeRowMapper(); edgeRowMapper.setTableAccessStrategy(tableAccessStrategy); annisNodeRowMapper = new AnnisNodeRowMapper(); annisNodeRowMapper.setTableAccessStrategy(tableAccessStrategy); nodeAnnotationRowMapper = new AnnotationRowMapper(TableAccessStrategy.NODE_ANNOTATION_TABLE); nodeAnnotationRowMapper.setTableAccessStrategy(tableAccessStrategy); edgeAnnotationRowMapper = new AnnotationRowMapper(TableAccessStrategy.EDGE_ANNOTATION_TABLE); edgeAnnotationRowMapper.setTableAccessStrategy(tableAccessStrategy); } public String explain(JdbcTemplate jdbcTemplate, List<Long> corpusList, int nodeCount, long offset, long limit, int left, int right, boolean analyze) { ParameterizedSingleColumnRowMapper<String> planRowMapper = new ParameterizedSingleColumnRowMapper<String>(); List<String> plan = jdbcTemplate.query((analyze ? "EXPLAIN ANALYZE " : "EXPLAIN ") + "\n" + getContextQuery(corpusList, left, right, limit, offset, nodeCount), planRowMapper); return StringUtils.join(plan, "\n"); } public List<AnnotationGraph> queryAnnotationGraph(JdbcTemplate jdbcTemplate, List<Long> corpusList, int nodeCount, long offset, long limit, int left, int right) { return (List<AnnotationGraph>) jdbcTemplate.query(getContextQuery(corpusList, left, right, limit, offset, nodeCount), this); } public List<AnnotationGraph> queryAnnotationGraph(JdbcTemplate jdbcTemplate, long textID) { return (List<AnnotationGraph>) jdbcTemplate.query(getTextQuery(textID), this); } public String getContextQuery(List<Long> corpusList, int left, int right, long limit, long offset, int nodeCount) { // key for annotation graph matches StringBuilder keySb = new StringBuilder(); keySb.append("ARRAY[matches.id1"); for (int i = 2; i <= nodeCount; ++i) { keySb.append(","); keySb.append("matches.id"); keySb.append(i); } keySb.append("] AS key"); String key = keySb.toString(); // sql for matches StringBuilder matchSb = new StringBuilder(); matchSb.append("SELECT * FROM "); matchSb.append(matchedNodesViewName); matchSb.append(" ORDER BY "); matchSb.append("id1"); for (int i = 2; i <= nodeCount; ++i) { matchSb.append(", "); matchSb.append("id"); matchSb.append(i); } matchSb.append(" OFFSET "); matchSb.append(offset); matchSb.append(" LIMIT "); matchSb.append(limit); String matchSql = matchSb.toString(); StringBuilder sb = new StringBuilder(); sb.append("SELECT DISTINCT \n"); sb.append("\t"); sb.append(key); sb.append(", facts.*\n"); sb.append("FROM\n"); sb.append("\t("); sb.append(matchSql); sb.append(") AS matches,\n"); sb.append("\t"); sb.append(FACTS_TABLE); sb.append(" AS facts\n"); sb.append("WHERE\n"); if (corpusList != null) { sb.append("facts.toplevel_corpus IN ("); sb.append(corpusList.isEmpty() ? "NULL" : StringUtils.join(corpusList, ",")); sb.append(") AND\n"); } sb.append("\t(\n"); sb.append("\t(facts.text_ref = matches.text_ref1 AND ((facts.left_token >= matches.left_token1 - ") .append(left).append(" AND facts.right_token <= matches.right_token1 + ") .append(right).append(") OR (facts.left_token <= matches.left_token1 - ") .append(left).append(" AND matches.left_token1 - ").append(left) .append(" <= facts.right_token) OR (facts.left_token <= matches.right_token1 + ") .append(right).append(" AND matches.right_token1 + ") .append(right).append(" <= facts.right_token)))"); for (int i = 2; i <= nodeCount; ++i) { sb.append(" OR\n"); sb.append("\t(facts.text_ref = matches.text_ref"); sb.append(i); sb.append(" AND ((facts.left_token >= matches.left_token"); sb.append(i); sb.append(" - "); sb.append(left); sb.append(" AND facts.right_token <= matches.right_token"); sb.append(i); sb.append(" + "); sb.append(right); sb.append(") OR (facts.left_token <= matches.left_token"); sb.append(i); sb.append(" - "); sb.append(left); sb.append(" AND matches.left_token"); sb.append(i); sb.append(" - "); sb.append(left); sb.append(" <= facts.right_token) OR (facts.left_token <= matches.right_token"); sb.append(i); sb.append(" + "); sb.append(right); sb.append(" AND matches.right_token"); sb.append(i); sb.append(" + "); sb.append(right); sb.append(" <= facts.right_token)))"); } sb.append("\n\t)\n"); sb.append("\nORDER BY key, facts.pre"); return sb.toString(); } public String getTextQuery(long textID) { String template = "SELECT DISTINCT \n" + "\t'-1' AS key, facts.*\n" + "FROM\n" + "\tfacts AS facts\n" + "WHERE\n" + "\tfacts.text_ref = :text_id\n" + "ORDER BY facts.pre"; String sql = template.replace(":text_id", String.valueOf(textID)); return sql; } @Override public List<AnnotationGraph> extractData(ResultSet resultSet) throws SQLException, DataAccessException { List<AnnotationGraph> graphs = new LinkedList<AnnotationGraph>(); // fn: match group -> annotation graph Map<List<Long>, AnnotationGraph> graphByMatchGroup = new HashMap<List<Long>, AnnotationGraph>(); // fn: node id -> node Map<Long, AnnisNode> nodeById = new HashMap<Long, AnnisNode>(); // fn: edge pre order value -> edge Map<Long, Edge> edgeByPre = new HashMap<Long, Edge>(); int rowNum = 0; while (resultSet.next()) { // process result by match group // match group is identified by the ids of the matched nodes Array sqlKey = resultSet.getArray("key"); Validate.isTrue(!resultSet.wasNull(), "Match group identifier must not be null"); Validate.isTrue(sqlKey.getBaseType() == Types.NUMERIC, "Key in database must be from the type \"numeric\" but was \"" + sqlKey.getBaseTypeName() + "\""); BigDecimal[] keyArray = (BigDecimal[]) sqlKey.getArray(); ArrayList<Long> key = new ArrayList<Long>(); for (BigDecimal bd : keyArray) { - key.add(bd.longValue()); + key.add(bd == null ? null : bd.longValue()); } if (!graphByMatchGroup.containsKey(key)) { log.debug("starting annotation graph for match: " + key); AnnotationGraph graph = new AnnotationGraph(); graphs.add(graph); graphByMatchGroup.put(key, graph); // clear mapping functions for this graph // assumes that the result set is sorted by key, pre nodeById.clear(); edgeByPre.clear(); // set the matched keys - for (long l : key) + for (Long l : key) { - graph.addMatchedNodeId(l); + if(l != null) + { + graph.addMatchedNodeId(l); + } } } AnnotationGraph graph = graphByMatchGroup.get(key); // get node data AnnisNode node = annisNodeRowMapper.mapRow(resultSet, rowNum); // add node to graph if it is new, else get known copy long id = node.getId(); if (!nodeById.containsKey(id)) { log.debug("new node: " + id); nodeById.put(id, node); graph.addNode(node); } else { node = nodeById.get(id); } // we now have the id of the node and the general key, so we can // add the matched node index to the graph (if matched) long matchIndex = 1; //node.setMatchedNodeInQuery(null); - for (long l : key) + for (Long l : key) { - if (id == l) + if(l != null) { - node.setMatchedNodeInQuery(matchIndex); - break; + if (id == l) + { + node.setMatchedNodeInQuery(matchIndex); + break; + } + matchIndex++; } - matchIndex++; } // get edge data Edge edge = edgeRowMapper.mapRow(resultSet, rowNum); // add edge to graph if it is new, else get known copy long pre = edge.getPre(); if (!edgeByPre.containsKey(pre)) { // fix source references in edge edge.setDestination(node); fixNodes(edge, edgeByPre, nodeById); // add edge to src and dst nodes node.addIncomingEdge(edge); AnnisNode source = edge.getSource(); if (source != null) { source.addOutgoingEdge(edge); } log.debug("new edge: " + edge); edgeByPre.put(pre, edge); graph.addEdge(edge); } else { edge = edgeByPre.get(pre); } // add annotation data Annotation nodeAnnotation = nodeAnnotationRowMapper.mapRow(resultSet, rowNum); if (nodeAnnotation != null) { node.addNodeAnnotation(nodeAnnotation); } Annotation edgeAnnotation = edgeAnnotationRowMapper.mapRow(resultSet, rowNum); if (edgeAnnotation != null) { edge.addAnnotation(edgeAnnotation); } rowNum++; } return graphs; } protected void fixNodes(Edge edge, Map<Long, Edge> edgeByPre, Map<Long, AnnisNode> nodeById) { // pull source node from parent edge AnnisNode source = edge.getSource(); if (source == null) { return; } long pre = source.getId(); Edge parentEdge = edgeByPre.get(pre); AnnisNode parent = parentEdge != null ? parentEdge.getDestination() : null; // log.debug("looking for node with rank.pre = " + pre + "; found: " + parent); edge.setSource(parent); // pull destination node from mapping function long destinationId = edge.getDestination().getId(); edge.setDestination(nodeById.get(destinationId)); } public String getMatchedNodesViewName() { return matchedNodesViewName; } public void setMatchedNodesViewName(String matchedNodesViewName) { this.matchedNodesViewName = matchedNodesViewName; } }
false
true
public List<AnnotationGraph> extractData(ResultSet resultSet) throws SQLException, DataAccessException { List<AnnotationGraph> graphs = new LinkedList<AnnotationGraph>(); // fn: match group -> annotation graph Map<List<Long>, AnnotationGraph> graphByMatchGroup = new HashMap<List<Long>, AnnotationGraph>(); // fn: node id -> node Map<Long, AnnisNode> nodeById = new HashMap<Long, AnnisNode>(); // fn: edge pre order value -> edge Map<Long, Edge> edgeByPre = new HashMap<Long, Edge>(); int rowNum = 0; while (resultSet.next()) { // process result by match group // match group is identified by the ids of the matched nodes Array sqlKey = resultSet.getArray("key"); Validate.isTrue(!resultSet.wasNull(), "Match group identifier must not be null"); Validate.isTrue(sqlKey.getBaseType() == Types.NUMERIC, "Key in database must be from the type \"numeric\" but was \"" + sqlKey.getBaseTypeName() + "\""); BigDecimal[] keyArray = (BigDecimal[]) sqlKey.getArray(); ArrayList<Long> key = new ArrayList<Long>(); for (BigDecimal bd : keyArray) { key.add(bd.longValue()); } if (!graphByMatchGroup.containsKey(key)) { log.debug("starting annotation graph for match: " + key); AnnotationGraph graph = new AnnotationGraph(); graphs.add(graph); graphByMatchGroup.put(key, graph); // clear mapping functions for this graph // assumes that the result set is sorted by key, pre nodeById.clear(); edgeByPre.clear(); // set the matched keys for (long l : key) { graph.addMatchedNodeId(l); } } AnnotationGraph graph = graphByMatchGroup.get(key); // get node data AnnisNode node = annisNodeRowMapper.mapRow(resultSet, rowNum); // add node to graph if it is new, else get known copy long id = node.getId(); if (!nodeById.containsKey(id)) { log.debug("new node: " + id); nodeById.put(id, node); graph.addNode(node); } else { node = nodeById.get(id); } // we now have the id of the node and the general key, so we can // add the matched node index to the graph (if matched) long matchIndex = 1; //node.setMatchedNodeInQuery(null); for (long l : key) { if (id == l) { node.setMatchedNodeInQuery(matchIndex); break; } matchIndex++; } // get edge data Edge edge = edgeRowMapper.mapRow(resultSet, rowNum); // add edge to graph if it is new, else get known copy long pre = edge.getPre(); if (!edgeByPre.containsKey(pre)) { // fix source references in edge edge.setDestination(node); fixNodes(edge, edgeByPre, nodeById); // add edge to src and dst nodes node.addIncomingEdge(edge); AnnisNode source = edge.getSource(); if (source != null) { source.addOutgoingEdge(edge); } log.debug("new edge: " + edge); edgeByPre.put(pre, edge); graph.addEdge(edge); } else { edge = edgeByPre.get(pre); } // add annotation data Annotation nodeAnnotation = nodeAnnotationRowMapper.mapRow(resultSet, rowNum); if (nodeAnnotation != null) { node.addNodeAnnotation(nodeAnnotation); } Annotation edgeAnnotation = edgeAnnotationRowMapper.mapRow(resultSet, rowNum); if (edgeAnnotation != null) { edge.addAnnotation(edgeAnnotation); } rowNum++; } return graphs; }
public List<AnnotationGraph> extractData(ResultSet resultSet) throws SQLException, DataAccessException { List<AnnotationGraph> graphs = new LinkedList<AnnotationGraph>(); // fn: match group -> annotation graph Map<List<Long>, AnnotationGraph> graphByMatchGroup = new HashMap<List<Long>, AnnotationGraph>(); // fn: node id -> node Map<Long, AnnisNode> nodeById = new HashMap<Long, AnnisNode>(); // fn: edge pre order value -> edge Map<Long, Edge> edgeByPre = new HashMap<Long, Edge>(); int rowNum = 0; while (resultSet.next()) { // process result by match group // match group is identified by the ids of the matched nodes Array sqlKey = resultSet.getArray("key"); Validate.isTrue(!resultSet.wasNull(), "Match group identifier must not be null"); Validate.isTrue(sqlKey.getBaseType() == Types.NUMERIC, "Key in database must be from the type \"numeric\" but was \"" + sqlKey.getBaseTypeName() + "\""); BigDecimal[] keyArray = (BigDecimal[]) sqlKey.getArray(); ArrayList<Long> key = new ArrayList<Long>(); for (BigDecimal bd : keyArray) { key.add(bd == null ? null : bd.longValue()); } if (!graphByMatchGroup.containsKey(key)) { log.debug("starting annotation graph for match: " + key); AnnotationGraph graph = new AnnotationGraph(); graphs.add(graph); graphByMatchGroup.put(key, graph); // clear mapping functions for this graph // assumes that the result set is sorted by key, pre nodeById.clear(); edgeByPre.clear(); // set the matched keys for (Long l : key) { if(l != null) { graph.addMatchedNodeId(l); } } } AnnotationGraph graph = graphByMatchGroup.get(key); // get node data AnnisNode node = annisNodeRowMapper.mapRow(resultSet, rowNum); // add node to graph if it is new, else get known copy long id = node.getId(); if (!nodeById.containsKey(id)) { log.debug("new node: " + id); nodeById.put(id, node); graph.addNode(node); } else { node = nodeById.get(id); } // we now have the id of the node and the general key, so we can // add the matched node index to the graph (if matched) long matchIndex = 1; //node.setMatchedNodeInQuery(null); for (Long l : key) { if(l != null) { if (id == l) { node.setMatchedNodeInQuery(matchIndex); break; } matchIndex++; } } // get edge data Edge edge = edgeRowMapper.mapRow(resultSet, rowNum); // add edge to graph if it is new, else get known copy long pre = edge.getPre(); if (!edgeByPre.containsKey(pre)) { // fix source references in edge edge.setDestination(node); fixNodes(edge, edgeByPre, nodeById); // add edge to src and dst nodes node.addIncomingEdge(edge); AnnisNode source = edge.getSource(); if (source != null) { source.addOutgoingEdge(edge); } log.debug("new edge: " + edge); edgeByPre.put(pre, edge); graph.addEdge(edge); } else { edge = edgeByPre.get(pre); } // add annotation data Annotation nodeAnnotation = nodeAnnotationRowMapper.mapRow(resultSet, rowNum); if (nodeAnnotation != null) { node.addNodeAnnotation(nodeAnnotation); } Annotation edgeAnnotation = edgeAnnotationRowMapper.mapRow(resultSet, rowNum); if (edgeAnnotation != null) { edge.addAnnotation(edgeAnnotation); } rowNum++; } return graphs; }
diff --git a/bundles/org.eclipse.rap.rwt/src/org/eclipse/rwt/internal/theme/Theme.java b/bundles/org.eclipse.rap.rwt/src/org/eclipse/rwt/internal/theme/Theme.java index 06727e7da..c6aa117d7 100644 --- a/bundles/org.eclipse.rap.rwt/src/org/eclipse/rwt/internal/theme/Theme.java +++ b/bundles/org.eclipse.rap.rwt/src/org/eclipse/rwt/internal/theme/Theme.java @@ -1,469 +1,472 @@ /******************************************************************************* * Copyright (c) 2007, 2008 Innoopract Informationssysteme GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Innoopract Informationssysteme GmbH - initial API and implementation ******************************************************************************/ package org.eclipse.rwt.internal.theme; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.rwt.internal.theme.css.*; import org.w3c.css.sac.CSSException; /** * An instance of this class represents all the information provided by an RWT * theme, i.e. values from the theme properties file, derived values from the * default theme, and the name given to the theme. */ public final class Theme { private final String name; private final Map values; private final Map defaultValues; // --- CSS --- private final Map cssValues; private StyleSheet styleSheet; private ResourceLoader loader; StyleSheet getStyleSheet() { return styleSheet; } void setStyleSheet( StyleSheet styleSheet ) { this.styleSheet = styleSheet; } void setLoader( ResourceLoader loader ) { this.loader = loader; } ResourceLoader getLoader() { return loader; } // --- CSS --- /** * Creates a new theme which has no default theme. In RWT theming, only the * predefined theme has no default theme. * * @param name the name of the theme, must not be <code>null</code> */ public Theme( final String name ) { this( name, null ); } /** * Creates a new theme with the given default theme. The default theme * specifies the possible keys and their default values. <strong>Important:</strong> * Modifying the default theme afterwards has no effect on this theme. * * @param name the name of the theme, must not be <code>null</code> * @param defaultTheme the default theme */ public Theme( final String name, final Theme defaultTheme ) { checkName( name ); if( name == null ) { throw new NullPointerException( "name is null" ); } this.name = name; this.defaultValues = defaultTheme != null ? defaultTheme.values : null; values = new HashMap(); cssValues = new HashMap(); } /** * Loads a theme from a <code>.properties</code> file. * * @param name the name for the theme to create, must not be <code>null</code> * @param inStr the input stream of the theme file to read * @param loader the loader for resources provided by the theme * @return the newly created theme */ public static Theme loadFromFile( final String name, final Theme defaultTheme, final InputStream inStr, final ResourceLoader loader ) throws IOException { if( inStr == null ) { throw new NullPointerException( "null argument" ); } Theme newTheme = new Theme( name, defaultTheme ); Properties properties = new Properties(); properties.load( inStr ); Iterator iterator = properties.keySet().iterator(); while( iterator.hasNext() ) { String key = ( ( String )iterator.next() ).trim(); String keyName; String keyVariant; int index = key.indexOf( '/' ); if( index != -1 ) { keyVariant = key.substring( 0, index ); keyName = key.substring( index + 1 ); } else { keyName = key; keyVariant = null; } if( !defaultTheme.definesKey( keyName ) ) { String pattern = "Invalid key for themeing: ''{0}'' in ''{1}''"; Object[] arguments = new Object[] { keyName, key }; String message = MessageFormat.format( pattern, arguments ); throw new IllegalArgumentException( message ); } QxType defValue = defaultTheme.getValue( keyName, null ); String value = ( ( String )properties.get( key ) ) .trim(); if( value != null && value.trim().length() > 0 ) { QxType newValue; if( defValue instanceof QxBorder ) { newValue = QxBorder.valueOf( value ); } else if( defValue instanceof QxBoolean ) { newValue = QxBoolean.valueOf( value ); } else if( defValue instanceof QxBoxDimensions ) { newValue = QxBoxDimensions.valueOf( value ); } else if( defValue instanceof QxFont ) { newValue = QxFont.valueOf( value ); } else if( defValue instanceof QxColor ) { newValue = QxColor.valueOf( value ); } else if( defValue instanceof QxDimension ) { newValue = QxDimension.valueOf( value ); } else if( defValue instanceof QxImage ) { newValue = QxImage.valueOf( value, loader ); } else { throw new RuntimeException( "unknown type" ); } newTheme.setValue( keyName, keyVariant, newValue ); } } return newTheme; } public static Theme loadFromCssFile( final String name, final Theme defaultTheme, final InputStream inputStream, final ResourceLoader loader, final String uri, final ThemeProperty[] properties ) throws CSSException, IOException { Theme result = new Theme( name, defaultTheme ); CssFileReader reader = new CssFileReader(); StyleSheet styleSheet = reader.parse( inputStream, uri ); result.styleSheet = styleSheet; result.loader = loader; // == New CSS support // For each value in the style sheet, create a dummy property that will be // registered with the qx themes. StyleRule[] styleRules = styleSheet.getStyleRules(); for( int i = 0; i < styleRules.length; i++ ) { StyleRule styleRule = styleRules[ i ]; IStylePropertyMap propertyMap = styleRule.getProperties(); String[] propertyNames = propertyMap.getProperties(); for( int j = 0; j < propertyNames.length; j++ ) { String propertyName = propertyNames[ j ]; QxType value = propertyMap.getValue( propertyName, loader ); - String hash = getDummyPropertyName( value ); - result.cssValues.put( hash, value ); + // TODO [rst] Quick fix for NPE, revise + if( value != null ) { + String hash = getDummyPropertyName( value ); + result.cssValues.put( hash, value ); + } } } // == Old property system support == // For each property, extract the value from the style sheet for( int i = 0; i < properties.length; i++ ) { ThemeProperty property = properties[ i ]; if( property.cssElements.length > 0 && property.cssProperty != null ) { String[] variants = new String[ 0 ]; for( int j = 0; j < property.cssElements.length; j++ ) { String[] newVar = styleSheet.getVariants( property.cssElements[ 0 ] ); if( newVar.length > 0 ) { String[] oldVar = variants; variants = new String[ variants.length + newVar.length ]; System.arraycopy( oldVar, 0, variants, 0, oldVar.length ); System.arraycopy( newVar, 0, variants, oldVar.length, newVar.length ); } } StylableElement element = createDummyElement( property, null ); QxType value = styleSheet.getValue( property.cssProperty, element, loader ); if( value != null ) { result.setValue( property.name, value ); } for( int j = 0; j < variants.length; j++ ) { String variant = variants[ j ]; StylableElement vElement = createDummyElement( property, variant ); QxType vValue = styleSheet.getValue( property.cssProperty, vElement, loader ); if( vValue != null && !vValue.equals( value ) ) { result.setValue( property.name, variant, vValue ); } } } else { System.err.println( "Property without CSS support: " + property.name ); } } return result; } public String getName() { return name; } /** * Indicates whether this theme has a value for the specified key, no matter * if the value is defined in the theme itself or derived from the default * theme. * * @return <code>true</code> if either the theme itself or its default theme * has a value for key, <code>false</code> otherwise. */ public boolean hasKey( final String key ) { boolean result = values.containsKey( key ); if( defaultValues != null ) { result |= defaultValues.containsKey( key ); } return result; } /** * Indicates whether this theme defines the specified key. If the key is only * defined in the default theme, <code>false</code> is returned. */ public boolean definesKey( final String key ) { return values.containsKey( key ); } /** * Returns all keys defined in this theme, including the keys of the default * theme. Variant keys will be omitted. * * @return an array of keys, never <code>null</code> */ public String[] getKeys() { Set keySet; if( defaultValues != null ) { keySet = defaultValues.keySet(); } else { keySet = values.keySet(); } return ( String[] )keySet.toArray( new String[ keySet.size() ] ); } /** * Returns all keys defined in this theme, including the keys of the default * theme and variant keys. * * @return An array of keys, never <code>null</code> */ public String[] getKeysWithVariants() { Set keySet = new HashSet( values.keySet() ); if( defaultValues != null ) { keySet.addAll( defaultValues.keySet() ); } keySet.addAll( cssValues.keySet() ); return ( String[] )keySet.toArray( new String[ keySet.size() ] ); } public QxBorder getBorder( final String key, final String variant ) { QxType value = getValue( key, variant ); checkType( key, value, QxBorder.class ); return ( QxBorder )value; } public QxBoxDimensions getBoxDimensions( final String key, final String variant ) { QxType value = getValue( key, variant ); checkType( key, value, QxBoxDimensions.class ); return ( QxBoxDimensions )value; } public QxFont getFont( final String key, final String variant ) { QxType value = getValue( key, variant ); checkType( key, value, QxFont.class ); return ( QxFont )value; } public QxColor getColor( final String key, final String variant ) { QxType value = getValue( key, variant ); checkType( key, value, QxColor.class ); return ( QxColor )value; } public QxImage getImage( final String key, final String variant ) { QxType value = getValue( key, variant ); checkType( key, value, QxImage.class ); return ( QxImage )value; } public QxDimension getDimension( final String key, final String variant ) { QxType value = getValue( key, variant ); checkType( key, value, QxDimension.class ); return ( QxDimension )value; } /** * Returns the value for the given key. If the theme does not define a value * for the given key, the default value is returned. * * @param key the key to get the value for, may include variant * @return the value for the given key, never <code>null</code> */ public QxType getValue( final String key ) { return getValue( key, null ); } /** * Returns the value for the given key and variant. If the variant is * <code>null</code> or there is no such variant defined for the given key, * the default variant is assumed. If the theme does not define a value for * the given key, the default value is returned. * * @param key the key to get the value for * @param variant the variant to get the value for, or <code>null</code> for * the default variant * @return the value for the given key, never <code>null</code> */ public QxType getValue( final String key, final String variant ) { QxType result; if( variant != null && values.containsKey( variant + "/" + key ) ) { result = ( QxType )values.get( variant + "/" + key ); } else if( values.containsKey( key ) ) { result = ( QxType )values.get( key ); } else if( defaultValues != null && defaultValues.containsKey( key ) ) { result = ( QxType )defaultValues.get( key ); } else if( cssValues.containsKey( key ) ) { result = ( QxType )cssValues.get( key ); } else { String pattern = "Undefined key: ''{0}'' in theme ''{1}''"; Object[] arguments = new Object[] { key, name }; String message = MessageFormat.format( pattern, arguments ); throw new IllegalArgumentException( message ); } return result; } public void setValue( final String key, final QxType value ) { setValue( key, null, value ); } public void setValue( final String key, final String variant, final QxType value ) { if( key == null ) { throw new NullPointerException( "null argument" ); } if( variant != null && defaultValues == null ) { throw new IllegalArgumentException( "Variants not allowed in default theme" ); } if( variant == null && values.containsKey( key ) ) { String msg = "Tried to redefine key: " + key; throw new IllegalArgumentException( msg ); } if( defaultValues != null ) { if( defaultValues.containsKey( key ) ) { if( !defaultValues.get( key ).getClass().isInstance( value ) ) { String msg = "Tried to define key with wrong type: " + key; throw new IllegalArgumentException( msg ); } } else { String msg = "Key does not exist in default theme: " + key; throw new IllegalArgumentException( msg ); } } values.put( variant == null ? key : variant + "/" + key, value ); } public boolean equals( final Object obj ) { boolean result; if( obj == this ) { result = true; } else if( obj instanceof Theme ) { Theme other = ( Theme )obj; result = name.equals( other.name ); if( defaultValues == null ) { result &= other.defaultValues == null; } else { result &= defaultValues.equals( other.defaultValues ); } result &= values.equals( other.values ); } else { result = false; } return result; } public int hashCode() { int result = 17; result = 37 * result + name.hashCode(); if( defaultValues != null ) { result = 37 * defaultValues.hashCode(); } result = 37 * result + values.hashCode(); return result; } public static String getDummyPropertyName( final QxType value ) { return "_" + value.getClass().hashCode() + "-" + value.hashCode(); } private void checkType( final String key, final QxType value, final Class type ) { if( !value.getClass().isAssignableFrom( type ) ) { String pattern = "Requested key ''{{0}}'' has a different type"; Object[] arguments = new Object[] { key }; String message = MessageFormat.format( pattern, arguments ); throw new IllegalArgumentException( message ); } } private void checkName( final String name ) { if( name == null ) { throw new NullPointerException( "name" ); } if( name.length() == 0 ) { throw new IllegalArgumentException( "empty argument" ); } } private static StylableElement createDummyElement( final ThemeProperty property, final String variant ) { StylableElement result = new StylableElement( property.cssElements[ 0 ] ); if( property.cssSelectors.length > 0 ) { String selector = property.cssSelectors[ 0 ]; Pattern pattern = Pattern.compile( "\\[([A-Z]+)\\]|:([a-z]+)|.+" ); Matcher matcher = pattern.matcher( selector ); while( matcher.find() ) { String style = matcher.group( 1 ); String state = matcher.group( 2 ); if( style != null ) { result.setAttribute( style ); } else if( state != null ) { result.setPseudoClass( state ); } else { System.err.println( "Garbage found in css-selectors attribute: " + matcher.group() ); } } } if( variant != null ) { result.setClass( variant ); } return result; } }
true
true
public static Theme loadFromCssFile( final String name, final Theme defaultTheme, final InputStream inputStream, final ResourceLoader loader, final String uri, final ThemeProperty[] properties ) throws CSSException, IOException { Theme result = new Theme( name, defaultTheme ); CssFileReader reader = new CssFileReader(); StyleSheet styleSheet = reader.parse( inputStream, uri ); result.styleSheet = styleSheet; result.loader = loader; // == New CSS support // For each value in the style sheet, create a dummy property that will be // registered with the qx themes. StyleRule[] styleRules = styleSheet.getStyleRules(); for( int i = 0; i < styleRules.length; i++ ) { StyleRule styleRule = styleRules[ i ]; IStylePropertyMap propertyMap = styleRule.getProperties(); String[] propertyNames = propertyMap.getProperties(); for( int j = 0; j < propertyNames.length; j++ ) { String propertyName = propertyNames[ j ]; QxType value = propertyMap.getValue( propertyName, loader ); String hash = getDummyPropertyName( value ); result.cssValues.put( hash, value ); } } // == Old property system support == // For each property, extract the value from the style sheet for( int i = 0; i < properties.length; i++ ) { ThemeProperty property = properties[ i ]; if( property.cssElements.length > 0 && property.cssProperty != null ) { String[] variants = new String[ 0 ]; for( int j = 0; j < property.cssElements.length; j++ ) { String[] newVar = styleSheet.getVariants( property.cssElements[ 0 ] ); if( newVar.length > 0 ) { String[] oldVar = variants; variants = new String[ variants.length + newVar.length ]; System.arraycopy( oldVar, 0, variants, 0, oldVar.length ); System.arraycopy( newVar, 0, variants, oldVar.length, newVar.length ); } } StylableElement element = createDummyElement( property, null ); QxType value = styleSheet.getValue( property.cssProperty, element, loader ); if( value != null ) { result.setValue( property.name, value ); } for( int j = 0; j < variants.length; j++ ) { String variant = variants[ j ]; StylableElement vElement = createDummyElement( property, variant ); QxType vValue = styleSheet.getValue( property.cssProperty, vElement, loader ); if( vValue != null && !vValue.equals( value ) ) { result.setValue( property.name, variant, vValue ); } } } else { System.err.println( "Property without CSS support: " + property.name ); } } return result; }
public static Theme loadFromCssFile( final String name, final Theme defaultTheme, final InputStream inputStream, final ResourceLoader loader, final String uri, final ThemeProperty[] properties ) throws CSSException, IOException { Theme result = new Theme( name, defaultTheme ); CssFileReader reader = new CssFileReader(); StyleSheet styleSheet = reader.parse( inputStream, uri ); result.styleSheet = styleSheet; result.loader = loader; // == New CSS support // For each value in the style sheet, create a dummy property that will be // registered with the qx themes. StyleRule[] styleRules = styleSheet.getStyleRules(); for( int i = 0; i < styleRules.length; i++ ) { StyleRule styleRule = styleRules[ i ]; IStylePropertyMap propertyMap = styleRule.getProperties(); String[] propertyNames = propertyMap.getProperties(); for( int j = 0; j < propertyNames.length; j++ ) { String propertyName = propertyNames[ j ]; QxType value = propertyMap.getValue( propertyName, loader ); // TODO [rst] Quick fix for NPE, revise if( value != null ) { String hash = getDummyPropertyName( value ); result.cssValues.put( hash, value ); } } } // == Old property system support == // For each property, extract the value from the style sheet for( int i = 0; i < properties.length; i++ ) { ThemeProperty property = properties[ i ]; if( property.cssElements.length > 0 && property.cssProperty != null ) { String[] variants = new String[ 0 ]; for( int j = 0; j < property.cssElements.length; j++ ) { String[] newVar = styleSheet.getVariants( property.cssElements[ 0 ] ); if( newVar.length > 0 ) { String[] oldVar = variants; variants = new String[ variants.length + newVar.length ]; System.arraycopy( oldVar, 0, variants, 0, oldVar.length ); System.arraycopy( newVar, 0, variants, oldVar.length, newVar.length ); } } StylableElement element = createDummyElement( property, null ); QxType value = styleSheet.getValue( property.cssProperty, element, loader ); if( value != null ) { result.setValue( property.name, value ); } for( int j = 0; j < variants.length; j++ ) { String variant = variants[ j ]; StylableElement vElement = createDummyElement( property, variant ); QxType vValue = styleSheet.getValue( property.cssProperty, vElement, loader ); if( vValue != null && !vValue.equals( value ) ) { result.setValue( property.name, variant, vValue ); } } } else { System.err.println( "Property without CSS support: " + property.name ); } } return result; }
diff --git a/src/main/java/ru/tehkode/permissions/PermissionManager.java b/src/main/java/ru/tehkode/permissions/PermissionManager.java index 8a7e6a0..44f825c 100644 --- a/src/main/java/ru/tehkode/permissions/PermissionManager.java +++ b/src/main/java/ru/tehkode/permissions/PermissionManager.java @@ -1,454 +1,454 @@ /* * PermissionsEx - Permissions plugin for Bukkit * Copyright (C) 2011 t3hk0d3 http://www.tehkode.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ru.tehkode.permissions; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import ru.tehkode.permissions.config.Configuration; import ru.tehkode.permissions.events.PermissionEntityEvent; import ru.tehkode.permissions.events.PermissionEvent; import ru.tehkode.permissions.events.PermissionSystemEvent; /** * * @author code */ public class PermissionManager { public final static int TRANSIENT_PERMISSION = 0; protected static final Logger logger = Logger.getLogger("Minecraft"); protected Map<String, PermissionUser> users = new HashMap<String, PermissionUser>(); protected Map<String, PermissionGroup> groups = new HashMap<String, PermissionGroup>(); protected Map<String, PermissionGroup> defaultGroups = new HashMap<String, PermissionGroup>(); protected PermissionBackend backend = null; protected Configuration config; protected Timer timer = new Timer("PermissionsCleaner"); protected boolean debugMode = false; public PermissionManager(Configuration config) { this.config = config; this.initBackend(); this.debugMode = config.getBoolean("permissions.debug", false); } /** * Check if specified player has specified permission * * @param player player object * @param permission permission string to check against * @return true on success false otherwise */ public boolean has(Player player, String permission) { return this.has(player.getName(), permission, player.getWorld().getName()); } /** * Check if player has specified permission in world * * @param player player object * @param permission permission as string to check against * @param world world's name as string * @return true on success false otherwise */ public boolean has(Player player, String permission, String world) { return this.has(player.getName(), permission, world); } /** * Check if player with name has permission in world * * @param player player object * @param permission permission as string to check against * @param world world's name as string * @return true on success false otherwise */ public boolean has(String playerName, String permission, String world) { PermissionUser user = this.getUser(playerName); if (user == null) { return false; } return user.has(permission, world); } /** * Return user's object * * @param username get PermissionUser with given name * @return PermissionUser instance */ public PermissionUser getUser(String username) { if (username == null || username.isEmpty()) { return null; } PermissionUser user = users.get(username.toLowerCase()); if (user == null) { user = this.backend.getUser(username); if (user != null) { this.users.put(username.toLowerCase(), user); } } return user; } /** * Return object of specified player * * @param player player object * @return PermissionUser instance */ public PermissionUser getUser(Player player) { return this.getUser(player.getName()); } /** * Return all registered user objects * * @return PermissionUser array */ public PermissionUser[] getUsers() { return backend.getUsers(); } /** * Return all users in group * * @param groupName group's name * @return PermissionUser array */ public PermissionUser[] getUsers(String groupName, String worldName) { return backend.getUsers(groupName, worldName); } public PermissionUser[] getUsers(String groupName) { return backend.getUsers(groupName); } /** * Return all users in group and descendant groups * * @param groupName group's name * @param inheritance true return members of descendant groups of specified group * @return PermissionUser array for groupnName */ public PermissionUser[] getUsers(String groupName, String worldName, boolean inheritance) { return backend.getUsers(groupName, worldName, inheritance); } public PermissionUser[] getUsers(String groupName, boolean inheritance) { return backend.getUsers(groupName, inheritance); } /** * Reset in-memory object of specified group * * @param userName user's name */ public void resetUser(String userName) { this.users.remove(userName); } /** * Return object for specified group * * @param groupname group's name * @return PermissionGroup object */ public PermissionGroup getGroup(String groupname) { if (groupname == null || groupname.isEmpty()) { return null; } PermissionGroup group = groups.get(groupname.toLowerCase()); if (group == null) { group = this.backend.getGroup(groupname); if (group != null) { this.groups.put(groupname.toLowerCase(), group); } } return group; } /** * Return all groups * * @return PermissionGroup array */ public PermissionGroup[] getGroups() { return backend.getGroups(); } /** * Return all child groups of specified group * * @param groupName group's name * @return PermissionGroup array */ public PermissionGroup[] getGroups(String groupName, String worldName) { return backend.getGroups(groupName, worldName); } public PermissionGroup[] getGroups(String groupName) { return backend.getGroups(groupName); } /** * Return all descendants or child groups for groupName * * @param groupName group's name * @param inheritance true: only direct child groups would be returned * @return PermissionGroup array for specified groupName */ public PermissionGroup[] getGroups(String groupName, String worldName, boolean inheritance) { return backend.getGroups(groupName, worldName, inheritance); } public PermissionGroup[] getGroups(String groupName, boolean inheritance) { return backend.getGroups(groupName, inheritance); } /** * Return default group object * * @return default group object. null if not specified */ public PermissionGroup getDefaultGroup(String worldName) { String worldIndex = worldName != null ? worldName : ""; if (!this.defaultGroups.containsKey(worldIndex)) { this.defaultGroups.put(worldIndex, this.getDefaultGroup(worldName, this.getDefaultGroup(null, null))); } return this.defaultGroups.get(worldIndex); } public PermissionGroup getDefaultGroup() { return this.getDefaultGroup(null); } protected PermissionGroup getDefaultGroup(String worldName, PermissionGroup fallback) { PermissionGroup defaultGroup = this.backend.getDefaultGroup(worldName); if (defaultGroup == null && worldName == null) { - throw new IllegalStateException("No default group defined. Use \"pex default group set <group> [world]\" to define default group."); + throw new IllegalStateException("No default group defined. Use \"pex set default group <group> [world]\" to define default group."); } if (defaultGroup != null) { return defaultGroup; } if (worldName != null) { // check world-inheritance for (String parentWorld : this.getWorldInheritance(worldName)) { defaultGroup = this.getDefaultGroup(parentWorld, null); if (defaultGroup != null) { return defaultGroup; } } } return fallback; } /** * Set default group to specified group * * @param group PermissionGroup group object */ public void setDefaultGroup(PermissionGroup group, String worldName) { if (group == null || group.equals(this.defaultGroups)) { return; } backend.setDefaultGroup(group, worldName); this.defaultGroups.clear(); this.callEvent(PermissionSystemEvent.Action.DEFAULTGROUP_CHANGED); this.callEvent(new PermissionEntityEvent(group, PermissionEntityEvent.Action.DEFAULTGROUP_CHANGED)); } public void setDefaultGroup(PermissionGroup group) { this.setDefaultGroup(group, null); } /** * Reset in-memory object for groupName * * @param groupName group's name */ public void resetGroup(String groupName) { this.groups.remove(groupName); } /** * Set debug mode * * @param debug true enables debug mode, false disables */ public void setDebug(boolean debug) { this.debugMode = debug; this.callEvent(PermissionSystemEvent.Action.DEBUGMODE_TOGGLE); } /** * Return current state of debug mode * * @return true debug is enabled, false if disabled */ public boolean isDebug() { return this.debugMode; } /** * Return groups of specified rank ladder * * @param ladderName * @return Map of ladder, key - rank of group, value - group object. Empty map if ladder does not exist */ public Map<Integer, PermissionGroup> getRankLadder(String ladderName) { Map<Integer, PermissionGroup> ladder = new HashMap<Integer, PermissionGroup>(); for (PermissionGroup group : this.getGroups()) { if (!group.isRanked()) { continue; } if (group.getRankLadder().equalsIgnoreCase(ladderName)) { ladder.put(group.getRank(), group); } } return ladder; } /** * Return array of world names who has world inheritance * * @param world World name * @return Array of parent world, if world does not exist return empty array */ public String[] getWorldInheritance(String worldName) { return backend.getWorldInheritance(worldName); } /** * Set world inheritance parents for world * * @param world world name which inheritance should be set * @param parentWorlds array of parent world names */ public void setWorldInheritance(String world, String[] parentWorlds) { backend.setWorldInheritance(world, parentWorlds); this.callEvent(PermissionSystemEvent.Action.WORLDINHERITANCE_CHANGED); } /** * Return current backend * * @return current backend object */ public PermissionBackend getBackend() { return this.backend; } /** * Set backend to specified backend. * This would also cause backend resetting. * * @param backendName name of backend to set to */ public void setBackend(String backendName) { synchronized (this) { this.clearCache(); this.backend = PermissionBackend.getBackend(backendName, this, config); this.backend.initialize(); } this.callEvent(PermissionSystemEvent.Action.BACKEND_CHANGED); } /** * Register new timer task * * @param task TimerTask object * @param delay delay in seconds */ protected void registerTask(TimerTask task, int delay) { if (delay == TRANSIENT_PERMISSION) { return; } timer.schedule(task, delay * 1000); } /** * Reset all in-memory groups and users, clean up runtime stuff, reloads backend */ public void reset() { this.clearCache(); if (this.backend != null) { this.backend.reload(); } this.callEvent(PermissionSystemEvent.Action.RELOADED); } protected void clearCache() { this.users.clear(); this.groups.clear(); this.defaultGroups.clear(); // Close old timed Permission Timer timer.cancel(); timer = new Timer("PermissionsCleaner"); } private void initBackend() { String backendName = this.config.getString("permissions.backend"); if (backendName == null || backendName.isEmpty()) { backendName = PermissionBackend.defaultBackend; //Default backend this.config.setProperty("permissions.backend", backendName); this.config.save(); } this.setBackend(backendName); } protected void callEvent(PermissionEvent event) { Bukkit.getServer().getPluginManager().callEvent(event); } protected void callEvent(PermissionSystemEvent.Action action) { this.callEvent(new PermissionSystemEvent(action)); } }
true
true
protected PermissionGroup getDefaultGroup(String worldName, PermissionGroup fallback) { PermissionGroup defaultGroup = this.backend.getDefaultGroup(worldName); if (defaultGroup == null && worldName == null) { throw new IllegalStateException("No default group defined. Use \"pex default group set <group> [world]\" to define default group."); } if (defaultGroup != null) { return defaultGroup; } if (worldName != null) { // check world-inheritance for (String parentWorld : this.getWorldInheritance(worldName)) { defaultGroup = this.getDefaultGroup(parentWorld, null); if (defaultGroup != null) { return defaultGroup; } } } return fallback; }
protected PermissionGroup getDefaultGroup(String worldName, PermissionGroup fallback) { PermissionGroup defaultGroup = this.backend.getDefaultGroup(worldName); if (defaultGroup == null && worldName == null) { throw new IllegalStateException("No default group defined. Use \"pex set default group <group> [world]\" to define default group."); } if (defaultGroup != null) { return defaultGroup; } if (worldName != null) { // check world-inheritance for (String parentWorld : this.getWorldInheritance(worldName)) { defaultGroup = this.getDefaultGroup(parentWorld, null); if (defaultGroup != null) { return defaultGroup; } } } return fallback; }
diff --git a/ngrinder-controller/src/main/java/org/ngrinder/user/service/UserService.java b/ngrinder-controller/src/main/java/org/ngrinder/user/service/UserService.java index 849a5518..3c66f05d 100644 --- a/ngrinder-controller/src/main/java/org/ngrinder/user/service/UserService.java +++ b/ngrinder-controller/src/main/java/org/ngrinder/user/service/UserService.java @@ -1,264 +1,264 @@ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngrinder.user.service; import static org.ngrinder.common.util.Preconditions.checkNotNull; import static org.ngrinder.common.util.Preconditions.checkNull; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.google.common.collect.Lists; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.hibernate.Hibernate; import org.ngrinder.common.constant.NGrinderConstants; import org.ngrinder.infra.config.Config; import org.ngrinder.model.PerfTest; import org.ngrinder.model.Role; import org.ngrinder.model.User; import org.ngrinder.perftest.service.PerfTestService; import org.ngrinder.script.service.FileEntryService; import org.ngrinder.security.SecuredUser; import org.ngrinder.service.IUserService; import org.ngrinder.user.repository.UserRepository; import org.ngrinder.user.repository.UserSpecification; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.security.authentication.dao.SaltSource; import org.springframework.security.authentication.encoding.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * The Class UserService. * * @author Yubin Mao * @author AlexQin */ @Service public class UserService implements IUserService { @Autowired private UserRepository userRepository; @Autowired private PerfTestService perfTestService; @Autowired private FileEntryService scriptService; @Autowired private SaltSource saltSource; @Autowired private PasswordEncoder passwordEncoder; @Autowired private Config config; /** * Get user by user id. * * @param userId user id * @return user */ @Transactional @Cacheable("users") @Override public User getUserById(String userId) { return userRepository.findOneByUserId(userId); } /** * Encoding given user's password. * * @param user user */ public void encodePassword(User user) { if (StringUtils.isNotBlank(user.getPassword())) { SecuredUser securedUser = new SecuredUser(user, null); String encodePassword = passwordEncoder.encodePassword(user.getPassword(), saltSource.getSalt(securedUser)); user.setPassword(encodePassword); } } /** * Save user. * * @param user include id, userID, fullName, role, password. * @return result */ @Transactional @CachePut(value = "users", key = "#user.userId") @Override public User saveUser(User user) { encodePassword(user); return saveUserWithoutPasswordEncoding(user); } /** * Save user. * * @param user include id, userID, fullName, role, password. * @return result */ @Transactional @CachePut(value = "users", key = "#user.userId") @Override public User saveUserWithoutPasswordEncoding(User user) { user.setFollowers(getFollowUsers(user.getFollowersStr())); - if (user.getPassword() != null || StringUtils.isBlank(user.getPassword())) { + if (user.getPassword() != null && StringUtils.isBlank(user.getPassword())) { user.setPassword(null); } final User existing = userRepository.findOneByUserId(user.getUserId()); if (existing != null) { user = existing.merge(user); } User createdUser = userRepository.save(user); prepareUserEnv(user); return createdUser; } @Transactional @CachePut(value = "users", key = "#user.userId") @Override @Deprecated public User saveUser(User user, Role role) { user.setRole(role); return saveUser(user); } private void prepareUserEnv(User user) { scriptService.prepare(user); } private List<User> getFollowUsers(String followersStr) { List<User> newShareUsers = new ArrayList<User>(); String[] userIds = StringUtils.split(StringUtils.trimToEmpty(followersStr), ','); for (String userId : userIds) { User shareUser = userRepository.findOneByUserId(userId.trim()); if (shareUser != null) { newShareUsers.add(shareUser); } } return newShareUsers; } /** * Delete user. All corresponding perftest and directories are deleted as well. * * @param userId the user id string list */ @Transactional @CacheEvict(value = "users", key = "#userId") public void deleteUser(String userId) { User user = getUserById(userId); List<PerfTest> deletePerfTests = perfTestService.deleteAllPerfTests(user); userRepository.delete(user); for (PerfTest perfTest : deletePerfTests) { FileUtils.deleteQuietly(config.getHome().getPerfTestDirectory(perfTest)); } FileUtils.deleteQuietly(config.getHome().getScriptDirectory(user)); FileUtils.deleteQuietly(config.getHome().getUserRepoDirectory(user)); } /** * get the user list by the given role. * * @param role role * @param sort sort * @return found user list * @throws Exception */ public List<User> getUsersByRole(Role role, Sort sort) { return (role == null) ? userRepository.findAll(sort) : userRepository.findAllByRole(role, sort); } /** * get the user list by the given role. * * @param role role * @param pageable sort * @return found user list * @throws Exception */ public Page<User> getUsersByRole(Role role, Pageable pageable) { return (role == null) ? userRepository.findAll(pageable) : userRepository.findAllByRole(role, pageable); } /** * Get the users by the given role. * * @param role role * @return found user list * @throws Exception */ public List<User> getUsersByRole(Role role) { return getUsersByRole(role, new Sort(Direction.ASC, "userName")); } /** * Get the users by nameLike spec. * * @param name name of user * @return found user list */ public List<User> getUsersByKeyWord(String name) { return userRepository.findAll(UserSpecification.nameLike(name)); } /** * Get user page by the given keyword. * * @param keyword keyword to be like search. * @param pageable page * @return user page */ public Page<User> getUsersByKeyWord(String keyword, Pageable pageable) { return userRepository.findAll(UserSpecification.nameLike(keyword), pageable); } /** * Create an user avoiding ModelAspect behavior. * * @param user userID, fullName, role, password. * @return result */ @Transactional @CachePut(value = "users", key = "#user.userId") @Override public User createUser(User user) { encodePassword(user); Date createdDate = new Date(); user.setCreatedDate(createdDate); user.setLastModifiedDate(createdDate); User createdUser = getUserById(NGrinderConstants.NGRINDER_INITIAL_ADMIN_USERID); user.setCreatedUser(createdUser); user.setLastModifiedUser(createdUser); return saveUserWithoutPasswordEncoding(user); } }
true
true
public User saveUserWithoutPasswordEncoding(User user) { user.setFollowers(getFollowUsers(user.getFollowersStr())); if (user.getPassword() != null || StringUtils.isBlank(user.getPassword())) { user.setPassword(null); } final User existing = userRepository.findOneByUserId(user.getUserId()); if (existing != null) { user = existing.merge(user); } User createdUser = userRepository.save(user); prepareUserEnv(user); return createdUser; }
public User saveUserWithoutPasswordEncoding(User user) { user.setFollowers(getFollowUsers(user.getFollowersStr())); if (user.getPassword() != null && StringUtils.isBlank(user.getPassword())) { user.setPassword(null); } final User existing = userRepository.findOneByUserId(user.getUserId()); if (existing != null) { user = existing.merge(user); } User createdUser = userRepository.save(user); prepareUserEnv(user); return createdUser; }