file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
36.3k
|
---|---|---|---|---|---|---|---|---|
204381_32 | /*
* Copyright 2012 Alex Usachev, [email protected]
*
* This file is part of Parallax project.
*
* Parallax is free software: you can redistribute it and/or modify it
* under the terms of the Creative Commons Attribution 3.0 Unported License.
*
* Parallax 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 Creative Commons Attribution
* 3.0 Unported License. for more details.
*
* You should have received a copy of the the Creative Commons Attribution
* 3.0 Unported License along with Parallax.
* If not, see http://creativecommons.org/licenses/by/3.0/.
*/
package org.parallax3d.parallax.graphics.extras.core;
import org.parallax3d.parallax.Log;
import org.parallax3d.parallax.graphics.core.Face3;
import org.parallax3d.parallax.graphics.core.Geometry;
import org.parallax3d.parallax.graphics.extras.ShapeUtils;
import org.parallax3d.parallax.graphics.extras.geometries.FrenetFrames;
import org.parallax3d.parallax.math.Box3;
import org.parallax3d.parallax.math.Color;
import org.parallax3d.parallax.math.Vector2;
import org.parallax3d.parallax.math.Vector3;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Creates extruded geometry from a path shape.
* <p>
* Based on the three.js code.
*/
public class ExtrudeGeometry extends Geometry
{
public static class ExtrudeGeometryParameters
{
// size of the text
public double size;
// thickness to extrude text
public double height;
// number of points on the curves
public int curveSegments = 12;
// number of points for z-side extrusions / used for subdividing segements of extrude spline too
public int steps = 1;
// Amount
public int amount = 100;
// turn on bevel
public boolean bevelEnabled = true;
// how deep into text bevel goes
public double bevelThickness = 6;
// how far from text outline is bevel
public double bevelSize = bevelThickness - 2;
// number of bevel layers
public int bevelSegments = 3;
// 2d/3d spline path to extrude shape orthogonality to
public Curve extrudePath;
// 2d path for bend the shape around x/y plane
public CurvePath bendPath;
// material index for front and back faces
public int material;
// material index for extrusion and beveled faces
public int extrudeMaterial;
}
private static Vector2 __v1 = new Vector2();
private static Vector2 __v2 = new Vector2();
private static Vector2 __v3 = new Vector2();
private static Vector2 __v4 = new Vector2();
private static Vector2 __v5 = new Vector2();
private static Vector2 __v6 = new Vector2();
Box3 shapebb;
List<List<Vector2>> holes;
List<List<Integer>> localFaces;
ExtrudeGeometryParameters options;
int shapesOffset;
int verticesCount;
public ExtrudeGeometry(ExtrudeGeometryParameters options)
{
this(new ArrayList<Shape>(), options);
}
public ExtrudeGeometry(Shape shape, ExtrudeGeometryParameters options)
{
this(Arrays.asList(shape), options);
}
public ExtrudeGeometry(List<Shape> shapes, ExtrudeGeometryParameters options)
{
super();
if(!shapes.isEmpty())
this.shapebb = shapes.get( shapes.size() - 1 ).getBoundingBox();
this.options = options;
this.addShape( shapes, options );
this.computeFaceNormals();
}
public void addShape(List<Shape> shapes, ExtrudeGeometryParameters options)
{
int sl = shapes.size();
for ( int s = 0; s < sl; s ++ )
this.addShape( shapes.get( s ), options );
}
public void addShape( Shape shape, ExtrudeGeometryParameters options )
{
List<Vector2> extrudePts = null;
boolean extrudeByPath = false;
Vector3 binormal = new Vector3();
Vector3 normal = new Vector3();
Vector3 position2 = new Vector3();
FrenetFrames splineTube = null;
if ( options.extrudePath != null)
{
extrudePts = options.extrudePath.getSpacedPoints( options.steps );
extrudeByPath = true;
// bevels not supported for path extrusion
options.bevelEnabled = false;
// SETUP TNB variables
// Reuse TNB from TubeGeomtry for now.
// TODO - have a .isClosed in spline?
splineTube = new FrenetFrames(options.extrudePath, options.steps, false);
}
// Safeguards if bevels are not enabled
if ( !options.bevelEnabled )
{
options.bevelSegments = 0;
options.bevelThickness = 0;
options.bevelSize = 0;
}
this.shapesOffset = getVertices().size();
if ( options.bendPath != null )
shape.addWrapPath( options.bendPath );
List<Vector2> vertices = shape.getTransformedPoints();
this.holes = shape.getPointsHoles();
boolean reverse = ! ShapeUtils.isClockWise( vertices ) ;
if ( reverse )
{
Collections.reverse(vertices);
// Maybe we should also check if holes are in the opposite direction, just to be safe ...
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
if ( ShapeUtils.isClockWise( ahole ) )
Collections.reverse(ahole);
}
// If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
}
localFaces = ShapeUtils.triangulateShape ( vertices, holes );
// Would it be better to move points after triangulation?
// shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
// vertices = shapePoints.shape;
// holes = shapePoints.holes;
////
/// Handle Vertices
////
// vertices has all points but contour has only points of circumference
List<Vector2> contour = new ArrayList<Vector2>(vertices);
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
vertices.addAll( this.holes.get( h ) );
verticesCount = vertices.size();
//
// Find directions for point movement
//
List<Vector2> contourMovements = new ArrayList<Vector2>();
for ( int i = 0, il = contour.size(), j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ )
{
if ( j == il ) j = 0;
if ( k == il ) k = 0;
contourMovements.add(
getBevelVec( contour.get( i ), contour.get( j ), contour.get( k ) ));
}
List<List<Vector2>> holesMovements = new ArrayList<List<Vector2>>();
List<Vector2> verticesMovements = (List<Vector2>) ((ArrayList) contourMovements).clone();
for ( int h = 0, hl = holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = holes.get( h );
List<Vector2> oneHoleMovements = new ArrayList<Vector2>();
for ( int i = 0, il = ahole.size(), j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ )
{
if ( j == il ) j = 0;
if ( k == il ) k = 0;
// (j)---(i)---(k)
oneHoleMovements.add(getBevelVec( ahole.get( i ), ahole.get( j ), ahole.get( k ) ));
}
holesMovements.add( oneHoleMovements );
verticesMovements.addAll( oneHoleMovements );
}
// Loop bevelSegments, 1 for the front, 1 for the back
for ( int b = 0; b < options.bevelSegments; b ++ )
{
double t = b / (double)options.bevelSegments;
double z = options.bevelThickness * ( 1.0 - t );
double bs = options.bevelSize * ( Math.sin ( t * Math.PI / 2.0 ) ) ; // curved
//bs = bevelSize * t ; // linear
// contract shape
for ( int i = 0, il = contour.size(); i < il; i ++ )
{
Vector2 vert = scalePt2( contour.get( i ), contourMovements.get( i ), bs );
v( vert.getX(), vert.getY(), - z );
}
// expand holes
for ( int h = 0, hl = holes.size(); h < hl; h++ )
{
List<Vector2> ahole = holes.get( h );
List<Vector2> oneHoleMovements = holesMovements.get( h );
for ( int i = 0, il = ahole.size(); i < il; i++ )
{
Vector2 vert = scalePt2( ahole.get( i ), oneHoleMovements.get( i ), bs );
v( vert.getX(), vert.getY(), -z );
}
}
}
// Back facing vertices
for ( int i = 0; i < vertices.size(); i ++ )
{
Vector2 vert = options.bevelEnabled
? scalePt2( vertices.get( i ), verticesMovements.get( i ), options.bevelSize )
: vertices.get( i );
if ( !extrudeByPath )
{
v( vert.getX(), vert.getY(), 0 );
}
else
{
normal.copy(splineTube.getNormals().get(0)).multiply(vert.getX());
binormal.copy(splineTube.getBinormals().get(0)).multiply(vert.getY());
position2.copy((Vector3)extrudePts.get(0)).add(normal).add(binormal);
v(position2.getX(), position2.getY(), position2.getZ());
}
}
// Add stepped vertices...
// Including front facing vertices
for ( int s = 1; s <= options.steps; s ++ )
{
for ( int i = 0; i < vertices.size(); i ++ )
{
Vector2 vert = options.bevelEnabled
? scalePt2( vertices.get( i ), verticesMovements.get( i ), options.bevelSize )
: vertices.get( i );
if ( !extrudeByPath )
{
v( vert.getX(), vert.getY(), (double)options.amount / options.steps * s );
}
else
{
normal.copy(splineTube.getNormals().get(s)).multiply(vert.getX());
binormal.copy(splineTube.getBinormals().get(s)).multiply(vert.getY());
position2.copy((Vector3)extrudePts.get(s)).add(normal).add(binormal);
v(position2.getX(), position2.getY(), position2.getZ() );
}
}
}
// Add bevel segments planes
for ( int b = options.bevelSegments - 1; b >= 0; b -- )
{
double t = (double)b / options.bevelSegments;
double z = options.bevelThickness * ( 1 - t );
double bs = options.bevelSize * Math.sin ( t * Math.PI/2.0 ) ;
// contract shape
for ( int i = 0, il = contour.size(); i < il; i ++ )
{
Vector2 vert = scalePt2( contour.get( i ), contourMovements.get( i ), bs );
v( vert.getX(), vert.getY(), options.amount + z );
}
// expand holes
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
List<Vector2> oneHoleMovements = holesMovements.get( h );
for ( int i = 0, il = ahole.size(); i < il; i++ )
{
Vector2 vert = scalePt2( ahole.get( i ), oneHoleMovements.get( i ), bs );
if ( !extrudeByPath )
v( vert.getX(), vert.getY(), options.amount + z );
else
v( vert.getX(),
vert.getY() + ((Vector3)extrudePts.get( options.steps - 1 )).getY(),
((Vector3)extrudePts.get( options.steps - 1 )).getX() + z );
}
}
}
//
// Handle Faces
//
// Top and bottom faces
buildLidFaces();
// Sides faces
buildSideFaces(contour);
}
private Vector2 getBevelVec( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
// Algorithm 2
return getBevelVec2( pt_i, pt_j, pt_k );
}
private Vector2 getBevelVec1( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
double anglea = Math.atan2( pt_j.getY() - pt_i.getY(), pt_j.getX() - pt_i.getX() );
double angleb = Math.atan2( pt_k.getY() - pt_i.getY(), pt_k.getX() - pt_i.getX() );
if ( anglea > angleb )
angleb += Math.PI * 2.0;
double anglec = ( anglea + angleb ) / 2.0;
double x = - Math.cos( anglec );
double y = - Math.sin( anglec );
return new Vector2( x, y );
}
private Vector2 scalePt2 ( Vector2 pt, Vector2 vec, double size )
{
return vec.clone().multiply( size ).add( pt );
}
/*
* good reading for line-line intersection
* http://sputsoft.com/blog/2010/03/line-line-intersection.html
*/
private Vector2 getBevelVec2( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
Vector2 a = ExtrudeGeometry.__v1;
Vector2 b = ExtrudeGeometry.__v2;
Vector2 v_hat = ExtrudeGeometry.__v3;
Vector2 w_hat = ExtrudeGeometry.__v4;
Vector2 p = ExtrudeGeometry.__v5;
Vector2 q = ExtrudeGeometry.__v6;
// define a as vector j->i
// define b as vectot k->i
a.set( pt_i.getX() - pt_j.getX(), pt_i.getY() - pt_j.getY() );
b.set( pt_i.getX() - pt_k.getX(), pt_i.getY() - pt_k.getY() );
// get unit vectors
Vector2 v = a.normalize();
Vector2 w = b.normalize();
// normals from pt i
v_hat.set( -v.getY(), v.getX() );
w_hat.set( w.getY(), -w.getX() );
// pts from i
p.copy( pt_i ).add( v_hat );
q.copy( pt_i ).add( w_hat );
if ( p.equals( q ) )
return w_hat.clone();
// Points from j, k. helps prevents points cross overover most of the time
p.copy( pt_j ).add( v_hat );
q.copy( pt_k ).add( w_hat );
double v_dot_w_hat = v.dot( w_hat );
double q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
// We should not reach these conditions
if ( v_dot_w_hat == 0 )
{
Log.warn("ExtrudeGeometry.getBevelVec2() Either infinite or no solutions!");
if ( q_sub_p_dot_w_hat == 0 )
Log.warn("ExtrudeGeometry.getBevelVec2() Its finite solutions.");
else
Log.warn("ExtrudeGeometry.getBevelVec2() Too bad, no solutions.");
}
double s = q_sub_p_dot_w_hat / v_dot_w_hat;
// in case of emergecy, revert to algorithm 1.
if ( s < 0 )
return getBevelVec1( pt_i, pt_j, pt_k );
Vector2 intersection = v.multiply( s ).add( p );
// Don't normalize!, otherwise sharp corners become ugly
return intersection.sub( pt_i ).clone();
}
private void buildLidFaces()
{
int flen = this.localFaces.size();
Log.debug( "ExtrudeGeometry.buildLidFaces() faces=" + flen);
if ( this.options.bevelEnabled )
{
int layer = 0 ; // steps + 1
int offset = this.shapesOffset * layer;
// Bottom faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = this.localFaces.get( i );
f3( face.get(2) + offset, face.get(1) + offset, face.get(0) + offset, true );
}
layer = this.options.steps + this.options.bevelSegments * 2;
offset = verticesCount * layer;
// Top faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = this.localFaces.get( i );
f3( face.get(0) + offset, face.get(1) + offset, face.get(2) + offset, false );
}
}
else
{
// Bottom faces
for ( int i = 0; i < flen; i++ )
{
List<Integer> face = localFaces.get( i );
f3( face.get(2), face.get(1), face.get(0), true );
}
// Top faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = localFaces.get( i );
f3( face.get(0) + verticesCount * this.options.steps,
face.get(1) + verticesCount * this.options.steps,
face.get(2) + verticesCount * this.options.steps, false );
}
}
}
// Create faces for the z-sides of the shape
private void buildSideFaces(List<Vector2> contour)
{
int layeroffset = 0;
sidewalls( contour, layeroffset );
layeroffset += contour.size();
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
sidewalls( ahole, layeroffset );
//, true
layeroffset += ahole.size();
}
}
private void sidewalls( List<Vector2> contour, int layeroffset )
{
int i = contour.size();
while ( --i >= 0 )
{
int j = i;
int k = i - 1;
if ( k < 0 )
k = contour.size() - 1;
int sl = this.options.steps + this.options.bevelSegments * 2;
for ( int s = 0; s < sl; s ++ )
{
int slen1 = this.verticesCount * s;
int slen2 = this.verticesCount * ( s + 1 );
int a = layeroffset + j + slen1;
int b = layeroffset + k + slen1;
int c = layeroffset + k + slen2;
int d = layeroffset + j + slen2;
f4( a, b, c, d);
}
}
}
private void v( double x, double y, double z )
{
getVertices().add( new Vector3( x, y, z ) );
}
private void f3( int a, int b, int c, boolean isBottom )
{
a += this.shapesOffset;
b += this.shapesOffset;
c += this.shapesOffset;
// normal, color, material
getFaces().add( new Face3( a, b, c, this.options.material ) );
List<Vector2> uvs = isBottom
? WorldUVGenerator.generateBottomUV( this, a, b, c)
: WorldUVGenerator.generateTopUV( this, a, b, c);
getFaceVertexUvs().get( 0 ).add(uvs);
}
private void f4( int a, int b, int c, int d)
{
a += this.shapesOffset;
b += this.shapesOffset;
c += this.shapesOffset;
d += this.shapesOffset;
List<Color> colors = new ArrayList<Color>();
List<Vector3> normals = new ArrayList<Vector3>();
getFaces().add( new Face3( a, b, d, normals, colors, this.options.extrudeMaterial ) );
List<Color> colors2 = new ArrayList<Color>();
List<Vector3> normals2 = new ArrayList<Vector3>();
getFaces().add( new Face3( b, c, d, normals2, colors2, this.options.extrudeMaterial ) );
List<Vector2> uvs = WorldUVGenerator.generateSideWallUV(this, a, b, c, d);
getFaceVertexUvs().get( 0 ).add( Arrays.asList( uvs.get( 0 ), uvs.get( 1 ), uvs.get( 3 ) ) );
getFaceVertexUvs().get( 0 ).add( Arrays.asList( uvs.get( 1 ), uvs.get( 2 ), uvs.get( 3 ) ) );
}
public static class WorldUVGenerator
{
private WorldUVGenerator() {}
public static List<Vector2> generateTopUV( Geometry geometry, int indexA, int indexB, int indexC )
{
double ax = geometry.getVertices().get( indexA ).getX();
double ay = geometry.getVertices().get( indexA ).getY();
double bx = geometry.getVertices().get( indexB ).getX();
double by = geometry.getVertices().get( indexB ).getY();
double cx = geometry.getVertices().get( indexC ).getX();
double cy = geometry.getVertices().get( indexC ).getY();
return Arrays.asList(
new Vector2( ax, 1 - ay ),
new Vector2( bx, 1 - by ),
new Vector2( cx, 1 - cy )
);
}
public static List<Vector2> generateBottomUV( ExtrudeGeometry geometry, int indexA, int indexB, int indexC)
{
return generateTopUV( geometry, indexA, indexB, indexC );
}
public static List<Vector2> generateSideWallUV( Geometry geometry, int indexA, int indexB, int indexC, int indexD)
{
double ax = geometry.getVertices().get( indexA ).getX();
double ay = geometry.getVertices().get( indexA ).getY();
double az = geometry.getVertices().get( indexA ).getZ();
double bx = geometry.getVertices().get( indexB ).getX();
double by = geometry.getVertices().get( indexB ).getY();
double bz = geometry.getVertices().get( indexB ).getZ();
double cx = geometry.getVertices().get( indexC ).getX();
double cy = geometry.getVertices().get( indexC ).getY();
double cz = geometry.getVertices().get( indexC ).getZ();
double dx = geometry.getVertices().get( indexD ).getX();
double dy = geometry.getVertices().get( indexD ).getY();
double dz = geometry.getVertices().get( indexD ).getZ();
if ( Math.abs( ay - by ) < 0.01 )
{
return Arrays.asList(
new Vector2( ax, az ),
new Vector2( bx, bz ),
new Vector2( cx, cz ),
new Vector2( dx, dz )
);
}
else
{
return Arrays.asList(
new Vector2( ay, az ),
new Vector2( by, bz ),
new Vector2( cy, cz ),
new Vector2( dy, dz )
);
}
}
}
} | thothbot/parallax | parallax/src/org/parallax3d/parallax/graphics/extras/core/ExtrudeGeometry.java | 6,885 | // Add bevel segments planes | line_comment | nl | /*
* Copyright 2012 Alex Usachev, [email protected]
*
* This file is part of Parallax project.
*
* Parallax is free software: you can redistribute it and/or modify it
* under the terms of the Creative Commons Attribution 3.0 Unported License.
*
* Parallax 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 Creative Commons Attribution
* 3.0 Unported License. for more details.
*
* You should have received a copy of the the Creative Commons Attribution
* 3.0 Unported License along with Parallax.
* If not, see http://creativecommons.org/licenses/by/3.0/.
*/
package org.parallax3d.parallax.graphics.extras.core;
import org.parallax3d.parallax.Log;
import org.parallax3d.parallax.graphics.core.Face3;
import org.parallax3d.parallax.graphics.core.Geometry;
import org.parallax3d.parallax.graphics.extras.ShapeUtils;
import org.parallax3d.parallax.graphics.extras.geometries.FrenetFrames;
import org.parallax3d.parallax.math.Box3;
import org.parallax3d.parallax.math.Color;
import org.parallax3d.parallax.math.Vector2;
import org.parallax3d.parallax.math.Vector3;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Creates extruded geometry from a path shape.
* <p>
* Based on the three.js code.
*/
public class ExtrudeGeometry extends Geometry
{
public static class ExtrudeGeometryParameters
{
// size of the text
public double size;
// thickness to extrude text
public double height;
// number of points on the curves
public int curveSegments = 12;
// number of points for z-side extrusions / used for subdividing segements of extrude spline too
public int steps = 1;
// Amount
public int amount = 100;
// turn on bevel
public boolean bevelEnabled = true;
// how deep into text bevel goes
public double bevelThickness = 6;
// how far from text outline is bevel
public double bevelSize = bevelThickness - 2;
// number of bevel layers
public int bevelSegments = 3;
// 2d/3d spline path to extrude shape orthogonality to
public Curve extrudePath;
// 2d path for bend the shape around x/y plane
public CurvePath bendPath;
// material index for front and back faces
public int material;
// material index for extrusion and beveled faces
public int extrudeMaterial;
}
private static Vector2 __v1 = new Vector2();
private static Vector2 __v2 = new Vector2();
private static Vector2 __v3 = new Vector2();
private static Vector2 __v4 = new Vector2();
private static Vector2 __v5 = new Vector2();
private static Vector2 __v6 = new Vector2();
Box3 shapebb;
List<List<Vector2>> holes;
List<List<Integer>> localFaces;
ExtrudeGeometryParameters options;
int shapesOffset;
int verticesCount;
public ExtrudeGeometry(ExtrudeGeometryParameters options)
{
this(new ArrayList<Shape>(), options);
}
public ExtrudeGeometry(Shape shape, ExtrudeGeometryParameters options)
{
this(Arrays.asList(shape), options);
}
public ExtrudeGeometry(List<Shape> shapes, ExtrudeGeometryParameters options)
{
super();
if(!shapes.isEmpty())
this.shapebb = shapes.get( shapes.size() - 1 ).getBoundingBox();
this.options = options;
this.addShape( shapes, options );
this.computeFaceNormals();
}
public void addShape(List<Shape> shapes, ExtrudeGeometryParameters options)
{
int sl = shapes.size();
for ( int s = 0; s < sl; s ++ )
this.addShape( shapes.get( s ), options );
}
public void addShape( Shape shape, ExtrudeGeometryParameters options )
{
List<Vector2> extrudePts = null;
boolean extrudeByPath = false;
Vector3 binormal = new Vector3();
Vector3 normal = new Vector3();
Vector3 position2 = new Vector3();
FrenetFrames splineTube = null;
if ( options.extrudePath != null)
{
extrudePts = options.extrudePath.getSpacedPoints( options.steps );
extrudeByPath = true;
// bevels not supported for path extrusion
options.bevelEnabled = false;
// SETUP TNB variables
// Reuse TNB from TubeGeomtry for now.
// TODO - have a .isClosed in spline?
splineTube = new FrenetFrames(options.extrudePath, options.steps, false);
}
// Safeguards if bevels are not enabled
if ( !options.bevelEnabled )
{
options.bevelSegments = 0;
options.bevelThickness = 0;
options.bevelSize = 0;
}
this.shapesOffset = getVertices().size();
if ( options.bendPath != null )
shape.addWrapPath( options.bendPath );
List<Vector2> vertices = shape.getTransformedPoints();
this.holes = shape.getPointsHoles();
boolean reverse = ! ShapeUtils.isClockWise( vertices ) ;
if ( reverse )
{
Collections.reverse(vertices);
// Maybe we should also check if holes are in the opposite direction, just to be safe ...
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
if ( ShapeUtils.isClockWise( ahole ) )
Collections.reverse(ahole);
}
// If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
}
localFaces = ShapeUtils.triangulateShape ( vertices, holes );
// Would it be better to move points after triangulation?
// shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
// vertices = shapePoints.shape;
// holes = shapePoints.holes;
////
/// Handle Vertices
////
// vertices has all points but contour has only points of circumference
List<Vector2> contour = new ArrayList<Vector2>(vertices);
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
vertices.addAll( this.holes.get( h ) );
verticesCount = vertices.size();
//
// Find directions for point movement
//
List<Vector2> contourMovements = new ArrayList<Vector2>();
for ( int i = 0, il = contour.size(), j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ )
{
if ( j == il ) j = 0;
if ( k == il ) k = 0;
contourMovements.add(
getBevelVec( contour.get( i ), contour.get( j ), contour.get( k ) ));
}
List<List<Vector2>> holesMovements = new ArrayList<List<Vector2>>();
List<Vector2> verticesMovements = (List<Vector2>) ((ArrayList) contourMovements).clone();
for ( int h = 0, hl = holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = holes.get( h );
List<Vector2> oneHoleMovements = new ArrayList<Vector2>();
for ( int i = 0, il = ahole.size(), j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ )
{
if ( j == il ) j = 0;
if ( k == il ) k = 0;
// (j)---(i)---(k)
oneHoleMovements.add(getBevelVec( ahole.get( i ), ahole.get( j ), ahole.get( k ) ));
}
holesMovements.add( oneHoleMovements );
verticesMovements.addAll( oneHoleMovements );
}
// Loop bevelSegments, 1 for the front, 1 for the back
for ( int b = 0; b < options.bevelSegments; b ++ )
{
double t = b / (double)options.bevelSegments;
double z = options.bevelThickness * ( 1.0 - t );
double bs = options.bevelSize * ( Math.sin ( t * Math.PI / 2.0 ) ) ; // curved
//bs = bevelSize * t ; // linear
// contract shape
for ( int i = 0, il = contour.size(); i < il; i ++ )
{
Vector2 vert = scalePt2( contour.get( i ), contourMovements.get( i ), bs );
v( vert.getX(), vert.getY(), - z );
}
// expand holes
for ( int h = 0, hl = holes.size(); h < hl; h++ )
{
List<Vector2> ahole = holes.get( h );
List<Vector2> oneHoleMovements = holesMovements.get( h );
for ( int i = 0, il = ahole.size(); i < il; i++ )
{
Vector2 vert = scalePt2( ahole.get( i ), oneHoleMovements.get( i ), bs );
v( vert.getX(), vert.getY(), -z );
}
}
}
// Back facing vertices
for ( int i = 0; i < vertices.size(); i ++ )
{
Vector2 vert = options.bevelEnabled
? scalePt2( vertices.get( i ), verticesMovements.get( i ), options.bevelSize )
: vertices.get( i );
if ( !extrudeByPath )
{
v( vert.getX(), vert.getY(), 0 );
}
else
{
normal.copy(splineTube.getNormals().get(0)).multiply(vert.getX());
binormal.copy(splineTube.getBinormals().get(0)).multiply(vert.getY());
position2.copy((Vector3)extrudePts.get(0)).add(normal).add(binormal);
v(position2.getX(), position2.getY(), position2.getZ());
}
}
// Add stepped vertices...
// Including front facing vertices
for ( int s = 1; s <= options.steps; s ++ )
{
for ( int i = 0; i < vertices.size(); i ++ )
{
Vector2 vert = options.bevelEnabled
? scalePt2( vertices.get( i ), verticesMovements.get( i ), options.bevelSize )
: vertices.get( i );
if ( !extrudeByPath )
{
v( vert.getX(), vert.getY(), (double)options.amount / options.steps * s );
}
else
{
normal.copy(splineTube.getNormals().get(s)).multiply(vert.getX());
binormal.copy(splineTube.getBinormals().get(s)).multiply(vert.getY());
position2.copy((Vector3)extrudePts.get(s)).add(normal).add(binormal);
v(position2.getX(), position2.getY(), position2.getZ() );
}
}
}
// Add bevel<SUF>
for ( int b = options.bevelSegments - 1; b >= 0; b -- )
{
double t = (double)b / options.bevelSegments;
double z = options.bevelThickness * ( 1 - t );
double bs = options.bevelSize * Math.sin ( t * Math.PI/2.0 ) ;
// contract shape
for ( int i = 0, il = contour.size(); i < il; i ++ )
{
Vector2 vert = scalePt2( contour.get( i ), contourMovements.get( i ), bs );
v( vert.getX(), vert.getY(), options.amount + z );
}
// expand holes
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
List<Vector2> oneHoleMovements = holesMovements.get( h );
for ( int i = 0, il = ahole.size(); i < il; i++ )
{
Vector2 vert = scalePt2( ahole.get( i ), oneHoleMovements.get( i ), bs );
if ( !extrudeByPath )
v( vert.getX(), vert.getY(), options.amount + z );
else
v( vert.getX(),
vert.getY() + ((Vector3)extrudePts.get( options.steps - 1 )).getY(),
((Vector3)extrudePts.get( options.steps - 1 )).getX() + z );
}
}
}
//
// Handle Faces
//
// Top and bottom faces
buildLidFaces();
// Sides faces
buildSideFaces(contour);
}
private Vector2 getBevelVec( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
// Algorithm 2
return getBevelVec2( pt_i, pt_j, pt_k );
}
private Vector2 getBevelVec1( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
double anglea = Math.atan2( pt_j.getY() - pt_i.getY(), pt_j.getX() - pt_i.getX() );
double angleb = Math.atan2( pt_k.getY() - pt_i.getY(), pt_k.getX() - pt_i.getX() );
if ( anglea > angleb )
angleb += Math.PI * 2.0;
double anglec = ( anglea + angleb ) / 2.0;
double x = - Math.cos( anglec );
double y = - Math.sin( anglec );
return new Vector2( x, y );
}
private Vector2 scalePt2 ( Vector2 pt, Vector2 vec, double size )
{
return vec.clone().multiply( size ).add( pt );
}
/*
* good reading for line-line intersection
* http://sputsoft.com/blog/2010/03/line-line-intersection.html
*/
private Vector2 getBevelVec2( Vector2 pt_i, Vector2 pt_j, Vector2 pt_k )
{
Vector2 a = ExtrudeGeometry.__v1;
Vector2 b = ExtrudeGeometry.__v2;
Vector2 v_hat = ExtrudeGeometry.__v3;
Vector2 w_hat = ExtrudeGeometry.__v4;
Vector2 p = ExtrudeGeometry.__v5;
Vector2 q = ExtrudeGeometry.__v6;
// define a as vector j->i
// define b as vectot k->i
a.set( pt_i.getX() - pt_j.getX(), pt_i.getY() - pt_j.getY() );
b.set( pt_i.getX() - pt_k.getX(), pt_i.getY() - pt_k.getY() );
// get unit vectors
Vector2 v = a.normalize();
Vector2 w = b.normalize();
// normals from pt i
v_hat.set( -v.getY(), v.getX() );
w_hat.set( w.getY(), -w.getX() );
// pts from i
p.copy( pt_i ).add( v_hat );
q.copy( pt_i ).add( w_hat );
if ( p.equals( q ) )
return w_hat.clone();
// Points from j, k. helps prevents points cross overover most of the time
p.copy( pt_j ).add( v_hat );
q.copy( pt_k ).add( w_hat );
double v_dot_w_hat = v.dot( w_hat );
double q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
// We should not reach these conditions
if ( v_dot_w_hat == 0 )
{
Log.warn("ExtrudeGeometry.getBevelVec2() Either infinite or no solutions!");
if ( q_sub_p_dot_w_hat == 0 )
Log.warn("ExtrudeGeometry.getBevelVec2() Its finite solutions.");
else
Log.warn("ExtrudeGeometry.getBevelVec2() Too bad, no solutions.");
}
double s = q_sub_p_dot_w_hat / v_dot_w_hat;
// in case of emergecy, revert to algorithm 1.
if ( s < 0 )
return getBevelVec1( pt_i, pt_j, pt_k );
Vector2 intersection = v.multiply( s ).add( p );
// Don't normalize!, otherwise sharp corners become ugly
return intersection.sub( pt_i ).clone();
}
private void buildLidFaces()
{
int flen = this.localFaces.size();
Log.debug( "ExtrudeGeometry.buildLidFaces() faces=" + flen);
if ( this.options.bevelEnabled )
{
int layer = 0 ; // steps + 1
int offset = this.shapesOffset * layer;
// Bottom faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = this.localFaces.get( i );
f3( face.get(2) + offset, face.get(1) + offset, face.get(0) + offset, true );
}
layer = this.options.steps + this.options.bevelSegments * 2;
offset = verticesCount * layer;
// Top faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = this.localFaces.get( i );
f3( face.get(0) + offset, face.get(1) + offset, face.get(2) + offset, false );
}
}
else
{
// Bottom faces
for ( int i = 0; i < flen; i++ )
{
List<Integer> face = localFaces.get( i );
f3( face.get(2), face.get(1), face.get(0), true );
}
// Top faces
for ( int i = 0; i < flen; i ++ )
{
List<Integer> face = localFaces.get( i );
f3( face.get(0) + verticesCount * this.options.steps,
face.get(1) + verticesCount * this.options.steps,
face.get(2) + verticesCount * this.options.steps, false );
}
}
}
// Create faces for the z-sides of the shape
private void buildSideFaces(List<Vector2> contour)
{
int layeroffset = 0;
sidewalls( contour, layeroffset );
layeroffset += contour.size();
for ( int h = 0, hl = this.holes.size(); h < hl; h ++ )
{
List<Vector2> ahole = this.holes.get( h );
sidewalls( ahole, layeroffset );
//, true
layeroffset += ahole.size();
}
}
private void sidewalls( List<Vector2> contour, int layeroffset )
{
int i = contour.size();
while ( --i >= 0 )
{
int j = i;
int k = i - 1;
if ( k < 0 )
k = contour.size() - 1;
int sl = this.options.steps + this.options.bevelSegments * 2;
for ( int s = 0; s < sl; s ++ )
{
int slen1 = this.verticesCount * s;
int slen2 = this.verticesCount * ( s + 1 );
int a = layeroffset + j + slen1;
int b = layeroffset + k + slen1;
int c = layeroffset + k + slen2;
int d = layeroffset + j + slen2;
f4( a, b, c, d);
}
}
}
private void v( double x, double y, double z )
{
getVertices().add( new Vector3( x, y, z ) );
}
private void f3( int a, int b, int c, boolean isBottom )
{
a += this.shapesOffset;
b += this.shapesOffset;
c += this.shapesOffset;
// normal, color, material
getFaces().add( new Face3( a, b, c, this.options.material ) );
List<Vector2> uvs = isBottom
? WorldUVGenerator.generateBottomUV( this, a, b, c)
: WorldUVGenerator.generateTopUV( this, a, b, c);
getFaceVertexUvs().get( 0 ).add(uvs);
}
private void f4( int a, int b, int c, int d)
{
a += this.shapesOffset;
b += this.shapesOffset;
c += this.shapesOffset;
d += this.shapesOffset;
List<Color> colors = new ArrayList<Color>();
List<Vector3> normals = new ArrayList<Vector3>();
getFaces().add( new Face3( a, b, d, normals, colors, this.options.extrudeMaterial ) );
List<Color> colors2 = new ArrayList<Color>();
List<Vector3> normals2 = new ArrayList<Vector3>();
getFaces().add( new Face3( b, c, d, normals2, colors2, this.options.extrudeMaterial ) );
List<Vector2> uvs = WorldUVGenerator.generateSideWallUV(this, a, b, c, d);
getFaceVertexUvs().get( 0 ).add( Arrays.asList( uvs.get( 0 ), uvs.get( 1 ), uvs.get( 3 ) ) );
getFaceVertexUvs().get( 0 ).add( Arrays.asList( uvs.get( 1 ), uvs.get( 2 ), uvs.get( 3 ) ) );
}
public static class WorldUVGenerator
{
private WorldUVGenerator() {}
public static List<Vector2> generateTopUV( Geometry geometry, int indexA, int indexB, int indexC )
{
double ax = geometry.getVertices().get( indexA ).getX();
double ay = geometry.getVertices().get( indexA ).getY();
double bx = geometry.getVertices().get( indexB ).getX();
double by = geometry.getVertices().get( indexB ).getY();
double cx = geometry.getVertices().get( indexC ).getX();
double cy = geometry.getVertices().get( indexC ).getY();
return Arrays.asList(
new Vector2( ax, 1 - ay ),
new Vector2( bx, 1 - by ),
new Vector2( cx, 1 - cy )
);
}
public static List<Vector2> generateBottomUV( ExtrudeGeometry geometry, int indexA, int indexB, int indexC)
{
return generateTopUV( geometry, indexA, indexB, indexC );
}
public static List<Vector2> generateSideWallUV( Geometry geometry, int indexA, int indexB, int indexC, int indexD)
{
double ax = geometry.getVertices().get( indexA ).getX();
double ay = geometry.getVertices().get( indexA ).getY();
double az = geometry.getVertices().get( indexA ).getZ();
double bx = geometry.getVertices().get( indexB ).getX();
double by = geometry.getVertices().get( indexB ).getY();
double bz = geometry.getVertices().get( indexB ).getZ();
double cx = geometry.getVertices().get( indexC ).getX();
double cy = geometry.getVertices().get( indexC ).getY();
double cz = geometry.getVertices().get( indexC ).getZ();
double dx = geometry.getVertices().get( indexD ).getX();
double dy = geometry.getVertices().get( indexD ).getY();
double dz = geometry.getVertices().get( indexD ).getZ();
if ( Math.abs( ay - by ) < 0.01 )
{
return Arrays.asList(
new Vector2( ax, az ),
new Vector2( bx, bz ),
new Vector2( cx, cz ),
new Vector2( dx, dz )
);
}
else
{
return Arrays.asList(
new Vector2( ay, az ),
new Vector2( by, bz ),
new Vector2( cy, cz ),
new Vector2( dy, dz )
);
}
}
}
} |
204400_9 | /*
* Copyright 2012 Alex Usachev, [email protected]
*
* This file is part of Parallax project.
*
* Parallax is free software: you can redistribute it and/or modify it
* under the terms of the Creative Commons Attribution 3.0 Unported License.
*
* Parallax 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 Creative Commons Attribution
* 3.0 Unported License. for more details.
*
* You should have received a copy of the the Creative Commons Attribution
* 3.0 Unported License along with Parallax.
* If not, see http://creativecommons.org/licenses/by/3.0/.
*/
package org.parallax3d.parallax.demo.content;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import thothbot.parallax.core.client.RenderingPanel;
import thothbot.parallax.core.shared.cameras.PerspectiveCamera;
import thothbot.parallax.core.shared.core.Geometry;
import thothbot.parallax.core.shared.core.Object3D;
import thothbot.parallax.core.shared.curves.Path;
import thothbot.parallax.core.shared.curves.Shape;
import thothbot.parallax.core.shared.curves.SplineCurve3;
import thothbot.parallax.core.shared.curves.SplineCurve3Closed;
import thothbot.parallax.core.shared.lights.DirectionalLight;
import thothbot.parallax.core.shared.materials.Material;
import thothbot.parallax.core.shared.materials.MeshBasicMaterial;
import thothbot.parallax.core.shared.materials.MeshLambertMaterial;
import thothbot.parallax.core.shared.math.Color;
import thothbot.parallax.core.shared.math.Mathematics;
import thothbot.parallax.core.shared.math.Vector2;
import thothbot.parallax.core.shared.math.Vector3;
import thothbot.parallax.core.shared.utils.SceneUtils;
import org.parallax3d.parallax.demo.client.ContentWidget;
import org.parallax3d.parallax.demo.client.DemoAnnotations.DemoSource;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.user.client.rpc.AsyncCallback;
public class GeometryExtrudeShapes extends ContentWidget
{
/*
* Prepare Rendering Scene
*/
@DemoSource
class DemoScene extends DemoAnimatedScene
{
private static final String texture = "./static/textures/crate.gif";
PerspectiveCamera camera;
Object3D parentObject;
@Override
protected void onStart()
{
camera = new PerspectiveCamera( 50,
getRenderer().getAbsoluteAspectRation(),
1,
1000
);
camera.getPosition().set(0, 150, 150);
DirectionalLight light = new DirectionalLight( 0xffffff );
light.getPosition().set( 0, 0, 1 );
getScene().add( light );
this.parentObject = new Object3D();
this.parentObject.getPosition().setY(50);
getScene().add( this.parentObject );
//Closed
SplineCurve3 extrudeBend = new SplineCurve3(Arrays.asList(
new Vector3( 30, 12, 83),
new Vector3( 40, 20, 67),
new Vector3( 60, 40, 99),
new Vector3( 10, 60, 49),
new Vector3( 25, 80, 40)));
SplineCurve3 pipeSpline = new SplineCurve3(Arrays.asList(
new Vector3(0, 10, -10),
new Vector3(10, 0, -10),
new Vector3(20, 0, 0),
new Vector3(30, 0, 10),
new Vector3(30, 0, 20),
new Vector3(20, 0, 30),
new Vector3(10, 0, 30),
new Vector3(0, 0, 30),
new Vector3(-10, 10, 30),
new Vector3(-10, 20, 30),
new Vector3(0, 30, 30),
new Vector3(10, 30, 30),
new Vector3(20, 30, 15),
new Vector3(10, 30, 10),
new Vector3(0, 30, 10),
new Vector3(-10, 20, 10),
new Vector3(-10, 10, 10),
new Vector3(0, 0, 10),
new Vector3(10, -10, 10),
new Vector3(20, -15, 10),
new Vector3(30, -15, 10),
new Vector3(40, -15, 10),
new Vector3(50, -15, 10),
new Vector3(60, 0, 10),
new Vector3(70, 0, 0),
new Vector3(80, 0, 0),
new Vector3(90, 0, 0),
new Vector3(100, 0, 0)));
SplineCurve3Closed sampleClosedSpline = new SplineCurve3Closed(Arrays.asList(
new Vector3(0, -40, -40),
new Vector3(0, 40, -40),
new Vector3(0, 140, -40),
new Vector3(0, 40, 40),
new Vector3(0, -40, 40)));
// List<Vector3> randomPoints = new ArrayList<Vector3>();
//
// for (int i=0; i<10; i++)
// randomPoints.add(new Vector3((double)Math.random() * 200.0f, (double)Math.random() * 200.0f, (double)Math.random() * 200.0f ));
//
// SplineCurve3 randomSpline = new SplineCurve3(randomPoints);
SplineCurve3 randomSpline = new SplineCurve3(Arrays.asList(
new Vector3(-40, -40, 0),
new Vector3(40, -40, 0),
new Vector3( 140, -40, 0),
new Vector3(40, 40, 0),
new Vector3(-40, 40, 20)));
// ExtrudeGeometry.ExtrudeGeometryParameters extrudeParameters = new ExtrudeGeometry.ExtrudeGeometryParameters();
// extrudeParameters.amount = 200;
// extrudeParameters.bevelEnabled = true;
// extrudeParameters.bevelSegments = 2;
// extrudeParameters.steps = 150;
// extrudeParameters.extrudePath = randomSpline;
// CircleGeometry
double circleRadius = 4.0;
Shape circleShape = new Shape();
circleShape.moveTo( 0, circleRadius );
circleShape.quadraticCurveTo( circleRadius, circleRadius, circleRadius, 0 );
circleShape.quadraticCurveTo( circleRadius, -circleRadius, 0, -circleRadius );
circleShape.quadraticCurveTo( -circleRadius, -circleRadius, -circleRadius, 0 );
circleShape.quadraticCurveTo( -circleRadius, circleRadius, 0, circleRadius);
double rectLength = 12.0;
double rectWidth = 4.0;
Shape rectShape = new Shape();
rectShape.moveTo( -rectLength/2, -rectWidth/2 );
rectShape.lineTo( -rectLength/2, rectWidth/2 );
rectShape.lineTo( rectLength/2, rectWidth/2 );
rectShape.lineTo( rectLength/2, -rectLength/2 );
rectShape.lineTo( -rectLength/2, -rectLength/2 );
// Smiley
Shape smileyShape = new Shape();
smileyShape.moveTo( 80, 40 );
smileyShape.arc( 40, 40, 40, 0.0, Math.PI * 2.0, false );
Path smileyEye1Path = new Path();
smileyEye1Path.moveTo( 35, 20 );
smileyEye1Path.arc( 25, 20, 10, 0.0, Math.PI * 2.0, true );
smileyShape.getHoles().add( smileyEye1Path );
Path smileyEye2Path = new Path();
smileyEye2Path.moveTo( 65, 20 );
smileyEye2Path.arc( 55, 20, 10, 0.0, Math.PI * 2.0, true );
smileyShape.getHoles().add( smileyEye2Path );
Path smileyMouthPath = new Path();
smileyMouthPath.moveTo( 20, 40 );
smileyMouthPath.quadraticCurveTo( 40, 60, 60, 40 );
smileyMouthPath.bezierCurveTo( 70, 45, 70, 50, 60, 60 );
smileyMouthPath.quadraticCurveTo( 40, 80, 20, 60 );
smileyMouthPath.quadraticCurveTo( 5, 50, 20, 40 );
smileyShape.getHoles().add( smileyMouthPath );
List<Vector2> pts = new ArrayList<Vector2>();
int starPoints = 5;
double l;
for (int i = 0; i < starPoints * 2; i++)
{
l = (Mathematics.isEven(i)) ? 5.0 : 10.0;
double a = i / starPoints * Math.PI;
pts.add(new Vector2(Math.cos(a) * l, Math.sin(a) * l ));
}
Shape starShape = new Shape(pts);
// ExtrudeGeometry circle3d = starShape.extrude( extrudeParameters ); //circleShape rectShape smileyShape starShape
// TubeGeometry tubeGeometry = new TubeGeometry((CurvePath) extrudeParameters.extrudePath, 150, 4.0, 5, false, true);
// addGeometry( circle3d, new Color(0xff1111),
// -100f, 0, 0,
// 0, 0, 0,
// 1);
// addGeometry( tubeGeometry, new Color(0x00ff11),
// 0, 0, 0,
// 0, 0, 0,
// 1);
}
private void addGeometry( Geometry geometry, Color color, double x, double y, double z, double rx, double ry, double rz, double s )
{
// 3d shape
MeshLambertMaterial ml = new MeshLambertMaterial();
ml.setColor(color);
ml.setOpacity( 0.2 );
ml.setTransparent(true);
MeshBasicMaterial mb = new MeshBasicMaterial();
mb.setColor( new Color(0x000000) );
mb.setWireframe( true );
mb.setOpacity( 0.3 );
List<Material> materials= new ArrayList<Material>();
materials.add(ml);
materials.add(mb);
Object3D mesh = SceneUtils.createMultiMaterialObject( geometry, materials );
mesh.getPosition().set( x, y, z - 75.0 );
mesh.getScale().set( s );
// if (geometry.debug)
// mesh.add(geometry.debug);
this.parentObject.add( mesh );
getRenderer().render(getScene(), camera);
}
@Override
protected void onUpdate(double duration)
{
}
}
public GeometryExtrudeShapes()
{
super("Geometry - extrude shapes", "Shapes Extrusion via Spline path. (Drag to spin)");
}
@Override
protected void loadRenderingPanelAttributes(RenderingPanel renderingPanel)
{
super.loadRenderingPanelAttributes(renderingPanel);
renderingPanel.setBackground(0xCCCCCC);
}
@Override
public DemoScene onInitialize()
{
return new DemoScene();
}
@Override
protected void asyncOnInitialize(final AsyncCallback<DemoAnimatedScene> callback)
{
GWT.runAsync(GeometryExtrudeShapes.class, new RunAsyncCallback()
{
public void onFailure(Throwable caught)
{
callback.onFailure(caught);
}
public void onSuccess()
{
callback.onSuccess(onInitialize());
}
});
}
}
| thothbot/parallax-demo | tmp/demo/content/GeometryExtrudeShapes.java | 3,562 | // extrudeParameters.bevelSegments = 2; | line_comment | nl | /*
* Copyright 2012 Alex Usachev, [email protected]
*
* This file is part of Parallax project.
*
* Parallax is free software: you can redistribute it and/or modify it
* under the terms of the Creative Commons Attribution 3.0 Unported License.
*
* Parallax 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 Creative Commons Attribution
* 3.0 Unported License. for more details.
*
* You should have received a copy of the the Creative Commons Attribution
* 3.0 Unported License along with Parallax.
* If not, see http://creativecommons.org/licenses/by/3.0/.
*/
package org.parallax3d.parallax.demo.content;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import thothbot.parallax.core.client.RenderingPanel;
import thothbot.parallax.core.shared.cameras.PerspectiveCamera;
import thothbot.parallax.core.shared.core.Geometry;
import thothbot.parallax.core.shared.core.Object3D;
import thothbot.parallax.core.shared.curves.Path;
import thothbot.parallax.core.shared.curves.Shape;
import thothbot.parallax.core.shared.curves.SplineCurve3;
import thothbot.parallax.core.shared.curves.SplineCurve3Closed;
import thothbot.parallax.core.shared.lights.DirectionalLight;
import thothbot.parallax.core.shared.materials.Material;
import thothbot.parallax.core.shared.materials.MeshBasicMaterial;
import thothbot.parallax.core.shared.materials.MeshLambertMaterial;
import thothbot.parallax.core.shared.math.Color;
import thothbot.parallax.core.shared.math.Mathematics;
import thothbot.parallax.core.shared.math.Vector2;
import thothbot.parallax.core.shared.math.Vector3;
import thothbot.parallax.core.shared.utils.SceneUtils;
import org.parallax3d.parallax.demo.client.ContentWidget;
import org.parallax3d.parallax.demo.client.DemoAnnotations.DemoSource;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.RunAsyncCallback;
import com.google.gwt.user.client.rpc.AsyncCallback;
public class GeometryExtrudeShapes extends ContentWidget
{
/*
* Prepare Rendering Scene
*/
@DemoSource
class DemoScene extends DemoAnimatedScene
{
private static final String texture = "./static/textures/crate.gif";
PerspectiveCamera camera;
Object3D parentObject;
@Override
protected void onStart()
{
camera = new PerspectiveCamera( 50,
getRenderer().getAbsoluteAspectRation(),
1,
1000
);
camera.getPosition().set(0, 150, 150);
DirectionalLight light = new DirectionalLight( 0xffffff );
light.getPosition().set( 0, 0, 1 );
getScene().add( light );
this.parentObject = new Object3D();
this.parentObject.getPosition().setY(50);
getScene().add( this.parentObject );
//Closed
SplineCurve3 extrudeBend = new SplineCurve3(Arrays.asList(
new Vector3( 30, 12, 83),
new Vector3( 40, 20, 67),
new Vector3( 60, 40, 99),
new Vector3( 10, 60, 49),
new Vector3( 25, 80, 40)));
SplineCurve3 pipeSpline = new SplineCurve3(Arrays.asList(
new Vector3(0, 10, -10),
new Vector3(10, 0, -10),
new Vector3(20, 0, 0),
new Vector3(30, 0, 10),
new Vector3(30, 0, 20),
new Vector3(20, 0, 30),
new Vector3(10, 0, 30),
new Vector3(0, 0, 30),
new Vector3(-10, 10, 30),
new Vector3(-10, 20, 30),
new Vector3(0, 30, 30),
new Vector3(10, 30, 30),
new Vector3(20, 30, 15),
new Vector3(10, 30, 10),
new Vector3(0, 30, 10),
new Vector3(-10, 20, 10),
new Vector3(-10, 10, 10),
new Vector3(0, 0, 10),
new Vector3(10, -10, 10),
new Vector3(20, -15, 10),
new Vector3(30, -15, 10),
new Vector3(40, -15, 10),
new Vector3(50, -15, 10),
new Vector3(60, 0, 10),
new Vector3(70, 0, 0),
new Vector3(80, 0, 0),
new Vector3(90, 0, 0),
new Vector3(100, 0, 0)));
SplineCurve3Closed sampleClosedSpline = new SplineCurve3Closed(Arrays.asList(
new Vector3(0, -40, -40),
new Vector3(0, 40, -40),
new Vector3(0, 140, -40),
new Vector3(0, 40, 40),
new Vector3(0, -40, 40)));
// List<Vector3> randomPoints = new ArrayList<Vector3>();
//
// for (int i=0; i<10; i++)
// randomPoints.add(new Vector3((double)Math.random() * 200.0f, (double)Math.random() * 200.0f, (double)Math.random() * 200.0f ));
//
// SplineCurve3 randomSpline = new SplineCurve3(randomPoints);
SplineCurve3 randomSpline = new SplineCurve3(Arrays.asList(
new Vector3(-40, -40, 0),
new Vector3(40, -40, 0),
new Vector3( 140, -40, 0),
new Vector3(40, 40, 0),
new Vector3(-40, 40, 20)));
// ExtrudeGeometry.ExtrudeGeometryParameters extrudeParameters = new ExtrudeGeometry.ExtrudeGeometryParameters();
// extrudeParameters.amount = 200;
// extrudeParameters.bevelEnabled = true;
// extrudeParameters.bevelSegments =<SUF>
// extrudeParameters.steps = 150;
// extrudeParameters.extrudePath = randomSpline;
// CircleGeometry
double circleRadius = 4.0;
Shape circleShape = new Shape();
circleShape.moveTo( 0, circleRadius );
circleShape.quadraticCurveTo( circleRadius, circleRadius, circleRadius, 0 );
circleShape.quadraticCurveTo( circleRadius, -circleRadius, 0, -circleRadius );
circleShape.quadraticCurveTo( -circleRadius, -circleRadius, -circleRadius, 0 );
circleShape.quadraticCurveTo( -circleRadius, circleRadius, 0, circleRadius);
double rectLength = 12.0;
double rectWidth = 4.0;
Shape rectShape = new Shape();
rectShape.moveTo( -rectLength/2, -rectWidth/2 );
rectShape.lineTo( -rectLength/2, rectWidth/2 );
rectShape.lineTo( rectLength/2, rectWidth/2 );
rectShape.lineTo( rectLength/2, -rectLength/2 );
rectShape.lineTo( -rectLength/2, -rectLength/2 );
// Smiley
Shape smileyShape = new Shape();
smileyShape.moveTo( 80, 40 );
smileyShape.arc( 40, 40, 40, 0.0, Math.PI * 2.0, false );
Path smileyEye1Path = new Path();
smileyEye1Path.moveTo( 35, 20 );
smileyEye1Path.arc( 25, 20, 10, 0.0, Math.PI * 2.0, true );
smileyShape.getHoles().add( smileyEye1Path );
Path smileyEye2Path = new Path();
smileyEye2Path.moveTo( 65, 20 );
smileyEye2Path.arc( 55, 20, 10, 0.0, Math.PI * 2.0, true );
smileyShape.getHoles().add( smileyEye2Path );
Path smileyMouthPath = new Path();
smileyMouthPath.moveTo( 20, 40 );
smileyMouthPath.quadraticCurveTo( 40, 60, 60, 40 );
smileyMouthPath.bezierCurveTo( 70, 45, 70, 50, 60, 60 );
smileyMouthPath.quadraticCurveTo( 40, 80, 20, 60 );
smileyMouthPath.quadraticCurveTo( 5, 50, 20, 40 );
smileyShape.getHoles().add( smileyMouthPath );
List<Vector2> pts = new ArrayList<Vector2>();
int starPoints = 5;
double l;
for (int i = 0; i < starPoints * 2; i++)
{
l = (Mathematics.isEven(i)) ? 5.0 : 10.0;
double a = i / starPoints * Math.PI;
pts.add(new Vector2(Math.cos(a) * l, Math.sin(a) * l ));
}
Shape starShape = new Shape(pts);
// ExtrudeGeometry circle3d = starShape.extrude( extrudeParameters ); //circleShape rectShape smileyShape starShape
// TubeGeometry tubeGeometry = new TubeGeometry((CurvePath) extrudeParameters.extrudePath, 150, 4.0, 5, false, true);
// addGeometry( circle3d, new Color(0xff1111),
// -100f, 0, 0,
// 0, 0, 0,
// 1);
// addGeometry( tubeGeometry, new Color(0x00ff11),
// 0, 0, 0,
// 0, 0, 0,
// 1);
}
private void addGeometry( Geometry geometry, Color color, double x, double y, double z, double rx, double ry, double rz, double s )
{
// 3d shape
MeshLambertMaterial ml = new MeshLambertMaterial();
ml.setColor(color);
ml.setOpacity( 0.2 );
ml.setTransparent(true);
MeshBasicMaterial mb = new MeshBasicMaterial();
mb.setColor( new Color(0x000000) );
mb.setWireframe( true );
mb.setOpacity( 0.3 );
List<Material> materials= new ArrayList<Material>();
materials.add(ml);
materials.add(mb);
Object3D mesh = SceneUtils.createMultiMaterialObject( geometry, materials );
mesh.getPosition().set( x, y, z - 75.0 );
mesh.getScale().set( s );
// if (geometry.debug)
// mesh.add(geometry.debug);
this.parentObject.add( mesh );
getRenderer().render(getScene(), camera);
}
@Override
protected void onUpdate(double duration)
{
}
}
public GeometryExtrudeShapes()
{
super("Geometry - extrude shapes", "Shapes Extrusion via Spline path. (Drag to spin)");
}
@Override
protected void loadRenderingPanelAttributes(RenderingPanel renderingPanel)
{
super.loadRenderingPanelAttributes(renderingPanel);
renderingPanel.setBackground(0xCCCCCC);
}
@Override
public DemoScene onInitialize()
{
return new DemoScene();
}
@Override
protected void asyncOnInitialize(final AsyncCallback<DemoAnimatedScene> callback)
{
GWT.runAsync(GeometryExtrudeShapes.class, new RunAsyncCallback()
{
public void onFailure(Throwable caught)
{
callback.onFailure(caught);
}
public void onSuccess()
{
callback.onSuccess(onInitialize());
}
});
}
}
|
184918_1 | /**
* Copyright 2014 The PlayN 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 playn.robovm;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import org.robovm.apple.coregraphics.CGAffineTransform;
import org.robovm.apple.coregraphics.CGBitmapContext;
import org.robovm.apple.coregraphics.CGBlendMode;
import org.robovm.apple.coregraphics.CGImage;
import org.robovm.apple.coregraphics.CGInterpolationQuality;
import org.robovm.apple.coregraphics.CGLineCap;
import org.robovm.apple.coregraphics.CGLineJoin;
import org.robovm.apple.coregraphics.CGMutablePath;
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.coregraphics.CGTextEncoding;
import org.robovm.rt.bro.ptr.IntPtr;
import playn.core.Canvas;
import playn.core.Gradient;
import playn.core.Path;
import playn.core.Pattern;
import playn.core.TextLayout;
import playn.core.gl.AbstractCanvasGL;
/**
* Implements {@link Canvas}.
*/
public class RoboCanvas extends AbstractCanvasGL<CGBitmapContext> {
private final int texWidth, texHeight;
private float strokeWidth = 1;
private int strokeColor = 0xFF000000;
private int fillColor = 0xFF000000;
private CGBitmapContext bctx;
private final RoboGLContext ctx;
private LinkedList<RoboCanvasState> states = new LinkedList<RoboCanvasState>();
public RoboCanvas(RoboGLContext ctx, float width, float height, boolean interpolate) {
super(width, height);
// if our size is invalid, we'll fail below at CGBitmapContext, so fail here more usefully
if (width <= 0 || height <= 0) throw new IllegalArgumentException(
"Invalid size " + width + "x" + height);
states.addFirst(new RoboCanvasState());
this.ctx = ctx;
// create our raw image data
texWidth = ctx.scale.scaledCeil(width);
texHeight = ctx.scale.scaledCeil(height);
// create the bitmap context via which we'll render into it
bctx = RoboGraphics.createCGBitmap(texWidth, texHeight);
if (!interpolate) {
bctx.setInterpolationQuality(CGInterpolationQuality.None);
}
// clear the canvas before we scale our bitmap context to avoid artifacts
bctx.clearRect(new CGRect(0, 0, texWidth, texHeight));
// CG coordinate system is OpenGL-style (0,0 in lower left); so we flip it
bctx.translateCTM(0, ctx.scale.scaled(height));
bctx.scaleCTM(ctx.scale.factor, -ctx.scale.factor);
}
public IntPtr data() {
return bctx.getData();
}
public int texWidth() {
return texWidth;
}
public int texHeight() {
return texHeight;
}
public CGImage cgImage() {
// TODO: make sure the image created by this call doesn't require any manual resource
// releasing, other than being eventually garbage collected
return bctx.toImage();
}
public void dispose() {
if (bctx != null) {
bctx.dispose();
bctx = null;
}
}
@Override
public Canvas clear() {
bctx.clearRect(new CGRect(0, 0, texWidth, texHeight));
isDirty = true;
return this;
}
@Override
public Canvas clearRect(float x, float y, float width, float height) {
bctx.clearRect(new CGRect(x, y, width, height));
isDirty = true;
return this;
}
@Override
public Canvas clip(Path clipPath) {
bctx.addPath(((RoboPath) clipPath).cgPath);
bctx.clip();
return this;
}
@Override
public Canvas clipRect(float x, float y, float width, float height) {
bctx.clipToRect(new CGRect(x, y, width, height));
return this;
}
@Override
public Path createPath() {
return new RoboPath();
}
@Override
public Canvas drawLine(float x0, float y0, float x1, float y1) {
bctx.beginPath();
bctx.moveToPoint(x0, y0);
bctx.addLineToPoint(x1, y1);
bctx.strokePath();
isDirty = true;
return this;
}
@Override
public Canvas drawPoint(float x, float y) {
save();
setStrokeWidth(0.5f);
strokeRect(x + 0.25f, y + 0.25f, 0.5f, 0.5f);
restore();
return this;
}
@Override
public Canvas drawText(String text, float x, float y) {
bctx.saveGState();
bctx.translateCTM(x, y + RoboGraphics.defaultFont.ctFont.getDescent());
bctx.scaleCTM(1, -1);
bctx.selectFont(RoboGraphics.defaultFont.iosName(), RoboGraphics.defaultFont.size(),
CGTextEncoding.MacRoman);
bctx.showTextAtPoint(0, 0, text);
bctx.restoreGState();
isDirty = true;
return this;
}
@Override
public Canvas fillCircle(float x, float y, float radius) {
RoboGradient gradient = currentState().gradient;
if (gradient == null) {
bctx.fillEllipseInRect(new CGRect(x-radius, y-radius, 2*radius, 2*radius));
} else {
CGMutablePath cgPath = CGMutablePath.createMutable();
cgPath.addArc(null, x, y, radius, 0, 2*Math.PI, false);
bctx.addPath(cgPath);
bctx.clip();
gradient.fill(bctx);
}
isDirty = true;
return this;
}
@Override
public Canvas fillPath(Path path) {
bctx.addPath(((RoboPath) path).cgPath);
RoboGradient gradient = currentState().gradient;
if (gradient == null) {
bctx.fillPath();
} else {
bctx.clip();
gradient.fill(bctx);
}
isDirty = true;
return this;
}
@Override
public Canvas fillRect(float x, float y, float width, float height) {
RoboGradient gradient = currentState().gradient;
if (gradient == null) {
bctx.fillRect(new CGRect(x, y, width, height));
} else {
bctx.saveGState();
bctx.clipToRect(new CGRect(x, y, width, height));
gradient.fill(bctx);
bctx.restoreGState();
}
isDirty = true;
return this;
}
@Override
public Canvas fillRoundRect(float x, float y, float width, float height, float radius) {
addRoundRectPath(x, y, width, height, radius);
RoboGradient gradient = currentState().gradient;
if (gradient == null) {
bctx.fillPath();
} else {
bctx.clip();
gradient.fill(bctx);
}
isDirty = true;
return this;
}
@Override
public Canvas fillText(TextLayout layout, float x, float y) {
RoboGradient gradient = currentState().gradient;
RoboTextLayout ilayout = (RoboTextLayout) layout;
if (gradient == null) {
ilayout.fill(bctx, x, y, fillColor);
} else {
// draw our text into a fresh context so we can use it as a mask for the gradient
CGBitmapContext maskContext = RoboGraphics.createCGBitmap(texWidth, texHeight);
maskContext.clearRect(new CGRect(0, 0, texWidth, texHeight));
// scale the context based on our scale factor
maskContext.scaleCTM(ctx.scale.factor, ctx.scale.factor);
// fill the text into this temp context in white for use as a mask
setFillColor(maskContext, 0xFFFFFFFF);
ilayout.fill(maskContext, 0, 0, fillColor);
// now fill the gradient, using our temp context as a mask
bctx.saveGState();
bctx.clipToMask(new CGRect(x, y, width, height), maskContext.toImage());
gradient.fill(bctx);
bctx.restoreGState();
// finally free the temp context
maskContext.dispose();
}
isDirty = true;
return this;
}
@Override
public Canvas restore() {
states.removeFirst();
bctx.restoreGState();
return this;
}
@Override
public Canvas rotate(float radians) {
bctx.rotateCTM(radians);
return this;
}
@Override
public Canvas save() {
states.addFirst(new RoboCanvasState(currentState()));
bctx.saveGState();
return this;
}
@Override
public Canvas scale(float x, float y) {
bctx.scaleCTM(x, y);
return this;
}
@Override
public Canvas setAlpha(float alpha) {
bctx.setAlpha(alpha);
return this;
}
@Override
public Canvas setCompositeOperation(Composite composite) {
bctx.setBlendMode(compToBlend.get(composite));
return this;
}
@Override
public Canvas setFillColor(int color) {
this.fillColor = color;
currentState().gradient = null;
setFillColor(bctx, color);
return this;
}
@Override
public Canvas setFillGradient(Gradient gradient) {
currentState().gradient = (RoboGradient) gradient;
return this;
}
@Override
public Canvas setFillPattern(Pattern pattern) {
currentState().gradient = null;
// TODO: this anchors the fill pattern in the lower left; sigh
bctx.setFillColor(((RoboPattern) pattern).colorWithPattern);
return this;
}
@Override
public Canvas setLineCap(LineCap cap) {
bctx.setLineCap(decodeCap.get(cap));
return this;
}
@Override
public Canvas setLineJoin(LineJoin join) {
bctx.setLineJoin(decodeJoin.get(join));
return this;
}
@Override
public Canvas setMiterLimit(float miter) {
bctx.setMiterLimit(miter);
return this;
}
@Override
public Canvas setStrokeColor(int color) {
this.strokeColor = color;
setStrokeColor(bctx, color);
return this;
}
@Override
public Canvas setStrokeWidth(float strokeWidth) {
this.strokeWidth = strokeWidth;
bctx.setLineWidth(strokeWidth);
return this;
}
@Override
public Canvas strokeCircle(float x, float y, float radius) {
bctx.strokeEllipseInRect(new CGRect(x-radius, y-radius, 2*radius, 2*radius));
isDirty = true;
return this;
}
@Override
public Canvas strokePath(Path path) {
bctx.addPath(((RoboPath) path).cgPath);
bctx.strokePath();
isDirty = true;
return this;
}
@Override
public Canvas strokeRect(float x, float y, float width, float height) {
bctx.strokeRect(new CGRect(x, y, width, height));
isDirty = true;
return this;
}
@Override
public Canvas strokeRoundRect(float x, float y, float width, float height, float radius) {
addRoundRectPath(x, y, width, height, radius);
bctx.strokePath();
isDirty = true;
return this;
}
@Override
public Canvas strokeText(TextLayout layout, float x, float y) {
((RoboTextLayout) layout).stroke(bctx, x, y, strokeWidth, strokeColor);
isDirty = true;
return this;
}
@Override
public Canvas transform(float m11, float m12, float m21, float m22, float dx, float dy) {
bctx.concatCTM(new CGAffineTransform(m11, m12, m21, m22, dx, dy));
return this;
}
@Override
public Canvas translate(float x, float y) {
bctx.translateCTM(x, y);
return this;
}
@Override
protected void finalize() {
dispose(); // meh
}
@Override
protected CGBitmapContext gc() {
return bctx;
}
private void addRoundRectPath(float x, float y, float width, float height, float radius) {
float midx = x + width/2, midy = y + height/2, maxx = x + width, maxy = y + height;
bctx.beginPath();
bctx.moveToPoint(x, midy);
bctx.addArcToPoint(x, y, midx, y, radius);
bctx.addArcToPoint(maxx, y, maxx, midy, radius);
bctx.addArcToPoint(maxx, maxy, midx, maxy, radius);
bctx.addArcToPoint(x, maxy, x, midy, radius);
bctx.closePath();
}
private RoboCanvasState currentState() {
return states.peek();
}
static void setStrokeColor(CGBitmapContext bctx, int color) {
float blue = (color & 0xFF) / 255f;
color >>= 8;
float green = (color & 0xFF) / 255f;
color >>= 8;
float red = (color & 0xFF) / 255f;
color >>= 8;
float alpha = (color & 0xFF) / 255f;
bctx.setRGBStrokeColor(red, green, blue, alpha);
}
static void setFillColor(CGBitmapContext bctx, int color) {
float blue = (color & 0xFF) / 255f;
color >>= 8;
float green = (color & 0xFF) / 255f;
color >>= 8;
float red = (color & 0xFF) / 255f;
color >>= 8;
float alpha = (color & 0xFF) / 255f;
bctx.setRGBFillColor(red, green, blue, alpha);
}
private static Map<Composite,CGBlendMode> compToBlend = new HashMap<Composite,CGBlendMode>();
static {
compToBlend.put(Composite.SRC, CGBlendMode.Copy);
compToBlend.put(Composite.DST_ATOP, CGBlendMode.DestinationAtop);
compToBlend.put(Composite.SRC_OVER, CGBlendMode.Normal);
compToBlend.put(Composite.DST_OVER, CGBlendMode.DestinationOver);
compToBlend.put(Composite.SRC_IN, CGBlendMode.SourceIn);
compToBlend.put(Composite.DST_IN, CGBlendMode.DestinationIn);
compToBlend.put(Composite.SRC_OUT, CGBlendMode.SourceOut);
compToBlend.put(Composite.DST_OUT, CGBlendMode.DestinationOut);
compToBlend.put(Composite.SRC_ATOP, CGBlendMode.SourceAtop);
compToBlend.put(Composite.XOR, CGBlendMode.XOR);
compToBlend.put(Composite.MULTIPLY, CGBlendMode.Multiply);
}
private static Map<LineCap,CGLineCap> decodeCap = new HashMap<LineCap,CGLineCap>();
static {
decodeCap.put(LineCap.BUTT, CGLineCap.Butt);
decodeCap.put(LineCap.ROUND, CGLineCap.Round);
decodeCap.put(LineCap.SQUARE, CGLineCap.Square);
}
private static Map<LineJoin,CGLineJoin> decodeJoin = new HashMap<LineJoin,CGLineJoin>();
static {
decodeJoin.put(LineJoin.BEVEL, CGLineJoin.Bevel);
decodeJoin.put(LineJoin.MITER, CGLineJoin.Miter);
decodeJoin.put(LineJoin.ROUND, CGLineJoin.Round);
}
}
| threerings/playn | robovm/src/playn/robovm/RoboCanvas.java | 4,722 | /**
* Implements {@link Canvas}.
*/ | block_comment | nl | /**
* Copyright 2014 The PlayN 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 playn.robovm;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import org.robovm.apple.coregraphics.CGAffineTransform;
import org.robovm.apple.coregraphics.CGBitmapContext;
import org.robovm.apple.coregraphics.CGBlendMode;
import org.robovm.apple.coregraphics.CGImage;
import org.robovm.apple.coregraphics.CGInterpolationQuality;
import org.robovm.apple.coregraphics.CGLineCap;
import org.robovm.apple.coregraphics.CGLineJoin;
import org.robovm.apple.coregraphics.CGMutablePath;
import org.robovm.apple.coregraphics.CGRect;
import org.robovm.apple.coregraphics.CGTextEncoding;
import org.robovm.rt.bro.ptr.IntPtr;
import playn.core.Canvas;
import playn.core.Gradient;
import playn.core.Path;
import playn.core.Pattern;
import playn.core.TextLayout;
import playn.core.gl.AbstractCanvasGL;
/**
* Implements {@link Canvas}.<SUF>*/
public class RoboCanvas extends AbstractCanvasGL<CGBitmapContext> {
private final int texWidth, texHeight;
private float strokeWidth = 1;
private int strokeColor = 0xFF000000;
private int fillColor = 0xFF000000;
private CGBitmapContext bctx;
private final RoboGLContext ctx;
private LinkedList<RoboCanvasState> states = new LinkedList<RoboCanvasState>();
public RoboCanvas(RoboGLContext ctx, float width, float height, boolean interpolate) {
super(width, height);
// if our size is invalid, we'll fail below at CGBitmapContext, so fail here more usefully
if (width <= 0 || height <= 0) throw new IllegalArgumentException(
"Invalid size " + width + "x" + height);
states.addFirst(new RoboCanvasState());
this.ctx = ctx;
// create our raw image data
texWidth = ctx.scale.scaledCeil(width);
texHeight = ctx.scale.scaledCeil(height);
// create the bitmap context via which we'll render into it
bctx = RoboGraphics.createCGBitmap(texWidth, texHeight);
if (!interpolate) {
bctx.setInterpolationQuality(CGInterpolationQuality.None);
}
// clear the canvas before we scale our bitmap context to avoid artifacts
bctx.clearRect(new CGRect(0, 0, texWidth, texHeight));
// CG coordinate system is OpenGL-style (0,0 in lower left); so we flip it
bctx.translateCTM(0, ctx.scale.scaled(height));
bctx.scaleCTM(ctx.scale.factor, -ctx.scale.factor);
}
public IntPtr data() {
return bctx.getData();
}
public int texWidth() {
return texWidth;
}
public int texHeight() {
return texHeight;
}
public CGImage cgImage() {
// TODO: make sure the image created by this call doesn't require any manual resource
// releasing, other than being eventually garbage collected
return bctx.toImage();
}
public void dispose() {
if (bctx != null) {
bctx.dispose();
bctx = null;
}
}
@Override
public Canvas clear() {
bctx.clearRect(new CGRect(0, 0, texWidth, texHeight));
isDirty = true;
return this;
}
@Override
public Canvas clearRect(float x, float y, float width, float height) {
bctx.clearRect(new CGRect(x, y, width, height));
isDirty = true;
return this;
}
@Override
public Canvas clip(Path clipPath) {
bctx.addPath(((RoboPath) clipPath).cgPath);
bctx.clip();
return this;
}
@Override
public Canvas clipRect(float x, float y, float width, float height) {
bctx.clipToRect(new CGRect(x, y, width, height));
return this;
}
@Override
public Path createPath() {
return new RoboPath();
}
@Override
public Canvas drawLine(float x0, float y0, float x1, float y1) {
bctx.beginPath();
bctx.moveToPoint(x0, y0);
bctx.addLineToPoint(x1, y1);
bctx.strokePath();
isDirty = true;
return this;
}
@Override
public Canvas drawPoint(float x, float y) {
save();
setStrokeWidth(0.5f);
strokeRect(x + 0.25f, y + 0.25f, 0.5f, 0.5f);
restore();
return this;
}
@Override
public Canvas drawText(String text, float x, float y) {
bctx.saveGState();
bctx.translateCTM(x, y + RoboGraphics.defaultFont.ctFont.getDescent());
bctx.scaleCTM(1, -1);
bctx.selectFont(RoboGraphics.defaultFont.iosName(), RoboGraphics.defaultFont.size(),
CGTextEncoding.MacRoman);
bctx.showTextAtPoint(0, 0, text);
bctx.restoreGState();
isDirty = true;
return this;
}
@Override
public Canvas fillCircle(float x, float y, float radius) {
RoboGradient gradient = currentState().gradient;
if (gradient == null) {
bctx.fillEllipseInRect(new CGRect(x-radius, y-radius, 2*radius, 2*radius));
} else {
CGMutablePath cgPath = CGMutablePath.createMutable();
cgPath.addArc(null, x, y, radius, 0, 2*Math.PI, false);
bctx.addPath(cgPath);
bctx.clip();
gradient.fill(bctx);
}
isDirty = true;
return this;
}
@Override
public Canvas fillPath(Path path) {
bctx.addPath(((RoboPath) path).cgPath);
RoboGradient gradient = currentState().gradient;
if (gradient == null) {
bctx.fillPath();
} else {
bctx.clip();
gradient.fill(bctx);
}
isDirty = true;
return this;
}
@Override
public Canvas fillRect(float x, float y, float width, float height) {
RoboGradient gradient = currentState().gradient;
if (gradient == null) {
bctx.fillRect(new CGRect(x, y, width, height));
} else {
bctx.saveGState();
bctx.clipToRect(new CGRect(x, y, width, height));
gradient.fill(bctx);
bctx.restoreGState();
}
isDirty = true;
return this;
}
@Override
public Canvas fillRoundRect(float x, float y, float width, float height, float radius) {
addRoundRectPath(x, y, width, height, radius);
RoboGradient gradient = currentState().gradient;
if (gradient == null) {
bctx.fillPath();
} else {
bctx.clip();
gradient.fill(bctx);
}
isDirty = true;
return this;
}
@Override
public Canvas fillText(TextLayout layout, float x, float y) {
RoboGradient gradient = currentState().gradient;
RoboTextLayout ilayout = (RoboTextLayout) layout;
if (gradient == null) {
ilayout.fill(bctx, x, y, fillColor);
} else {
// draw our text into a fresh context so we can use it as a mask for the gradient
CGBitmapContext maskContext = RoboGraphics.createCGBitmap(texWidth, texHeight);
maskContext.clearRect(new CGRect(0, 0, texWidth, texHeight));
// scale the context based on our scale factor
maskContext.scaleCTM(ctx.scale.factor, ctx.scale.factor);
// fill the text into this temp context in white for use as a mask
setFillColor(maskContext, 0xFFFFFFFF);
ilayout.fill(maskContext, 0, 0, fillColor);
// now fill the gradient, using our temp context as a mask
bctx.saveGState();
bctx.clipToMask(new CGRect(x, y, width, height), maskContext.toImage());
gradient.fill(bctx);
bctx.restoreGState();
// finally free the temp context
maskContext.dispose();
}
isDirty = true;
return this;
}
@Override
public Canvas restore() {
states.removeFirst();
bctx.restoreGState();
return this;
}
@Override
public Canvas rotate(float radians) {
bctx.rotateCTM(radians);
return this;
}
@Override
public Canvas save() {
states.addFirst(new RoboCanvasState(currentState()));
bctx.saveGState();
return this;
}
@Override
public Canvas scale(float x, float y) {
bctx.scaleCTM(x, y);
return this;
}
@Override
public Canvas setAlpha(float alpha) {
bctx.setAlpha(alpha);
return this;
}
@Override
public Canvas setCompositeOperation(Composite composite) {
bctx.setBlendMode(compToBlend.get(composite));
return this;
}
@Override
public Canvas setFillColor(int color) {
this.fillColor = color;
currentState().gradient = null;
setFillColor(bctx, color);
return this;
}
@Override
public Canvas setFillGradient(Gradient gradient) {
currentState().gradient = (RoboGradient) gradient;
return this;
}
@Override
public Canvas setFillPattern(Pattern pattern) {
currentState().gradient = null;
// TODO: this anchors the fill pattern in the lower left; sigh
bctx.setFillColor(((RoboPattern) pattern).colorWithPattern);
return this;
}
@Override
public Canvas setLineCap(LineCap cap) {
bctx.setLineCap(decodeCap.get(cap));
return this;
}
@Override
public Canvas setLineJoin(LineJoin join) {
bctx.setLineJoin(decodeJoin.get(join));
return this;
}
@Override
public Canvas setMiterLimit(float miter) {
bctx.setMiterLimit(miter);
return this;
}
@Override
public Canvas setStrokeColor(int color) {
this.strokeColor = color;
setStrokeColor(bctx, color);
return this;
}
@Override
public Canvas setStrokeWidth(float strokeWidth) {
this.strokeWidth = strokeWidth;
bctx.setLineWidth(strokeWidth);
return this;
}
@Override
public Canvas strokeCircle(float x, float y, float radius) {
bctx.strokeEllipseInRect(new CGRect(x-radius, y-radius, 2*radius, 2*radius));
isDirty = true;
return this;
}
@Override
public Canvas strokePath(Path path) {
bctx.addPath(((RoboPath) path).cgPath);
bctx.strokePath();
isDirty = true;
return this;
}
@Override
public Canvas strokeRect(float x, float y, float width, float height) {
bctx.strokeRect(new CGRect(x, y, width, height));
isDirty = true;
return this;
}
@Override
public Canvas strokeRoundRect(float x, float y, float width, float height, float radius) {
addRoundRectPath(x, y, width, height, radius);
bctx.strokePath();
isDirty = true;
return this;
}
@Override
public Canvas strokeText(TextLayout layout, float x, float y) {
((RoboTextLayout) layout).stroke(bctx, x, y, strokeWidth, strokeColor);
isDirty = true;
return this;
}
@Override
public Canvas transform(float m11, float m12, float m21, float m22, float dx, float dy) {
bctx.concatCTM(new CGAffineTransform(m11, m12, m21, m22, dx, dy));
return this;
}
@Override
public Canvas translate(float x, float y) {
bctx.translateCTM(x, y);
return this;
}
@Override
protected void finalize() {
dispose(); // meh
}
@Override
protected CGBitmapContext gc() {
return bctx;
}
private void addRoundRectPath(float x, float y, float width, float height, float radius) {
float midx = x + width/2, midy = y + height/2, maxx = x + width, maxy = y + height;
bctx.beginPath();
bctx.moveToPoint(x, midy);
bctx.addArcToPoint(x, y, midx, y, radius);
bctx.addArcToPoint(maxx, y, maxx, midy, radius);
bctx.addArcToPoint(maxx, maxy, midx, maxy, radius);
bctx.addArcToPoint(x, maxy, x, midy, radius);
bctx.closePath();
}
private RoboCanvasState currentState() {
return states.peek();
}
static void setStrokeColor(CGBitmapContext bctx, int color) {
float blue = (color & 0xFF) / 255f;
color >>= 8;
float green = (color & 0xFF) / 255f;
color >>= 8;
float red = (color & 0xFF) / 255f;
color >>= 8;
float alpha = (color & 0xFF) / 255f;
bctx.setRGBStrokeColor(red, green, blue, alpha);
}
static void setFillColor(CGBitmapContext bctx, int color) {
float blue = (color & 0xFF) / 255f;
color >>= 8;
float green = (color & 0xFF) / 255f;
color >>= 8;
float red = (color & 0xFF) / 255f;
color >>= 8;
float alpha = (color & 0xFF) / 255f;
bctx.setRGBFillColor(red, green, blue, alpha);
}
private static Map<Composite,CGBlendMode> compToBlend = new HashMap<Composite,CGBlendMode>();
static {
compToBlend.put(Composite.SRC, CGBlendMode.Copy);
compToBlend.put(Composite.DST_ATOP, CGBlendMode.DestinationAtop);
compToBlend.put(Composite.SRC_OVER, CGBlendMode.Normal);
compToBlend.put(Composite.DST_OVER, CGBlendMode.DestinationOver);
compToBlend.put(Composite.SRC_IN, CGBlendMode.SourceIn);
compToBlend.put(Composite.DST_IN, CGBlendMode.DestinationIn);
compToBlend.put(Composite.SRC_OUT, CGBlendMode.SourceOut);
compToBlend.put(Composite.DST_OUT, CGBlendMode.DestinationOut);
compToBlend.put(Composite.SRC_ATOP, CGBlendMode.SourceAtop);
compToBlend.put(Composite.XOR, CGBlendMode.XOR);
compToBlend.put(Composite.MULTIPLY, CGBlendMode.Multiply);
}
private static Map<LineCap,CGLineCap> decodeCap = new HashMap<LineCap,CGLineCap>();
static {
decodeCap.put(LineCap.BUTT, CGLineCap.Butt);
decodeCap.put(LineCap.ROUND, CGLineCap.Round);
decodeCap.put(LineCap.SQUARE, CGLineCap.Square);
}
private static Map<LineJoin,CGLineJoin> decodeJoin = new HashMap<LineJoin,CGLineJoin>();
static {
decodeJoin.put(LineJoin.BEVEL, CGLineJoin.Bevel);
decodeJoin.put(LineJoin.MITER, CGLineJoin.Miter);
decodeJoin.put(LineJoin.ROUND, CGLineJoin.Round);
}
}
|
10426_10 | package model.datum;
import java.util.Date;
/**
*
* @author Isaak
*
*/
public class Datum {
private int dag;
private int maand;
private int jaar;
/**
* @throws Exception
*
*/
public Datum() throws Exception
{
HuidigeSysteemDatum();
}
/**
*
* @param Datum
* @throws Exception
*/
@SuppressWarnings("deprecation")
public Datum(Date datum) throws Exception
{
setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900);
}
/**
*
* @param datum
* @throws Exception
*/
public Datum(Datum datum) throws Exception
{
setDatum(datum.getDag(), datum.getMaand(), datum.getJaar());
}
/**
*
* @param dag
* @param maand
* @param jaar
* @throws Exception
*/
public Datum(int dag, int maand, int jaar) throws Exception
{
setDatum(dag, maand, jaar);
}
/**
* Datum als string DDMMJJJJ
* @param datum
* @throws Exception
* @throws NumberFormatException
*/
public Datum(String datum) throws NumberFormatException, Exception
{
String[] datumDelen = datum.split("/");
if (datumDelen.length != 3 || datumDelen[0].length() < 1 ||
datumDelen[1].length() != 2 || datumDelen[2].length() != 4)
{
throw new IllegalArgumentException("De gegeven datum is onjuist. "
+ "Geldig formaat: (D)D/MM/YYYY");
}
setDatum(Integer.parseInt(datumDelen[0]), Integer.parseInt(datumDelen[1]), Integer.parseInt(datumDelen[2]));
}
/**
* Stel de datumvariabelen in. Doe ook de validatie en werp exceptions indien nodig
*
* @param dag
* @param maand
* @param jaar
* @return
* @throws Exception
*/
public boolean setDatum(int dag, int maand, int jaar) throws Exception
{
// Eerst de basale controle
if (dag < 1 || dag > 31)
{
throw new Exception("Ongeldige dag gegeven");
}
if (maand < 1 || maand > 12)
{
throw new Exception("Ongeldige numerieke maand gegeven");
}
if (jaar < 0)
{
throw new Exception("Ongeldig jaar gegeven");
}
// Nu een precieze controle
switch (maand)
{
case 2:
// 1) Als het geen schrikkeljaar is, heeft februari max 28 dagen
// 2) Wel een schrikkeljaar? Max 29 dagen
if ((!Maanden.isSchrikkeljaar(jaar) && dag >= 29) || (Maanden.isSchrikkeljaar(jaar) &&
dag > 29))
{
throw new Exception("De dag is niet juist voor de gegeven maand februari");
}
break;
case 4:
case 6:
case 9:
case 11:
if (dag > 30)
{
throw new Exception("De dag is niet juist voor de gegeven maand " + Maanden.get(maand));
}
break;
}
// Alles is goed verlopen
this.dag = dag;
this.maand = maand;
this.jaar = jaar;
return true;
}
/**
*
* @return
*/
public String getDatumInAmerikaansFormaat()
{
return String.format("%04d/%02d/%02d", jaar, maand, dag);
}
/**
*
* @return
*/
public String getDatumInEuropeesFormaat()
{
return String.format("%02d/%02d/%04d", dag, maand, jaar);
}
/**
* Haal de dag van het Datum object op
* @return
*/
public int getDag()
{
return dag;
}
/**
* Haal de maand van het Datum object op
* @return
*/
public int getMaand()
{
return maand;
}
/**
* Haal het jaar van het Datum object op
* @return
*/
public int getJaar()
{
return jaar;
}
/**
* Is de gegeven datum kleiner dan het huidid datum object?
*
* @param datum
* @return
*/
public boolean kleinerDan(Datum datum)
{
return compareTo(datum) > 0;
}
/**
*
* @param datum
* @return
* @throws Exception
*/
public int verschilInJaren(Datum datum) throws Exception
{
return new DatumVerschil(this, datum).getJaren();
}
/**
*
* @param datum
* @return
* @throws Exception
*/
public int verschilInMaanden(Datum datum) throws Exception
{
return new DatumVerschil(this, datum).getMaanden();
}
/**
*
* @param aantalDagen
* @return
* @throws Exception
*/
public Datum veranderDatum(int aantalDagen) throws Exception
{
if (aantalDagen > 0)
{
while (aantalDagen + dag > Maanden.get(maand).aantalDagen(jaar))
{
aantalDagen -= Maanden.get(maand).aantalDagen(jaar) - dag + 1;
// Jaar verhogen
jaar += (maand == 12 ? 1 : 0);
// Maand verhogen
maand = (maand == 12 ? 1 : ++maand);
// We hebben een nieuwe maand, dus terug van 1 beginnen
dag = 1;
}
}
// Negatieve waarde, dus terug in de tijd gaan
else
{
while (-dag >= aantalDagen)
{
// Verminder met aantal dagen in huidige maand.
aantalDagen += dag;
// Verminder jaartal?
jaar -= (maand == 1 ? 1 : 0);
// Verminder maand
maand = (maand == 1 ? 12 : --maand);
// Zet als laatste dag van (vorige) maand
dag = Maanden.get(maand).aantalDagen(jaar);
}
}
return new Datum(dag += aantalDagen, maand, jaar);
}
/**
*
*/
@Override
public boolean equals(Object obj)
{
// Is het exact hetzelfde object?
if (this == obj)
{
return true;
}
// Is het hetzelfde type?
if (obj == null || !(obj instanceof Datum))
{
return false;
}
// Nu zien of de inhoud dezelfde is
return compareTo((Datum) obj) == 0;
}
/**
* Ik snap er de ballen van
*/
@Override
public int hashCode()
{
final int prime = 37;
int hash = 1;
hash = prime * hash + dag;
hash = prime * hash + maand;
hash = prime * hash + jaar;
return hash;
}
/**
* Vergelijk de onze datum met de nieuwe
*/
public int compareTo(Datum datum2)
{
if (jaar > datum2.jaar)
{
return 1;
}
else if (jaar < datum2.jaar)
{
return -1;
}
if (maand > datum2.maand)
{
return 1;
}
else if (maand < datum2.maand)
{
return -1;
}
if (dag > datum2.dag)
{
return 1;
}
else if (dag < datum2.dag)
{
return -1;
}
return 0;
}
/**
* Geef een string representatie terug van de datum
* @return Datum in string formaat
*/
public String toString()
{
return dag + " " + Maanden.get(maand) + " " + jaar;
}
/**
* Return de huidige datum van het systeem
* @return Date
* @throws Exception
*/
@SuppressWarnings("deprecation")
private void HuidigeSysteemDatum() throws Exception
{
Date datum = new Date();
setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900);
}
}
| thunder-tw/JavaPractOpdrachten | Opdracht 1/src/model/datum/Datum.java | 2,560 | // 2) Wel een schrikkeljaar? Max 29 dagen | line_comment | nl | package model.datum;
import java.util.Date;
/**
*
* @author Isaak
*
*/
public class Datum {
private int dag;
private int maand;
private int jaar;
/**
* @throws Exception
*
*/
public Datum() throws Exception
{
HuidigeSysteemDatum();
}
/**
*
* @param Datum
* @throws Exception
*/
@SuppressWarnings("deprecation")
public Datum(Date datum) throws Exception
{
setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900);
}
/**
*
* @param datum
* @throws Exception
*/
public Datum(Datum datum) throws Exception
{
setDatum(datum.getDag(), datum.getMaand(), datum.getJaar());
}
/**
*
* @param dag
* @param maand
* @param jaar
* @throws Exception
*/
public Datum(int dag, int maand, int jaar) throws Exception
{
setDatum(dag, maand, jaar);
}
/**
* Datum als string DDMMJJJJ
* @param datum
* @throws Exception
* @throws NumberFormatException
*/
public Datum(String datum) throws NumberFormatException, Exception
{
String[] datumDelen = datum.split("/");
if (datumDelen.length != 3 || datumDelen[0].length() < 1 ||
datumDelen[1].length() != 2 || datumDelen[2].length() != 4)
{
throw new IllegalArgumentException("De gegeven datum is onjuist. "
+ "Geldig formaat: (D)D/MM/YYYY");
}
setDatum(Integer.parseInt(datumDelen[0]), Integer.parseInt(datumDelen[1]), Integer.parseInt(datumDelen[2]));
}
/**
* Stel de datumvariabelen in. Doe ook de validatie en werp exceptions indien nodig
*
* @param dag
* @param maand
* @param jaar
* @return
* @throws Exception
*/
public boolean setDatum(int dag, int maand, int jaar) throws Exception
{
// Eerst de basale controle
if (dag < 1 || dag > 31)
{
throw new Exception("Ongeldige dag gegeven");
}
if (maand < 1 || maand > 12)
{
throw new Exception("Ongeldige numerieke maand gegeven");
}
if (jaar < 0)
{
throw new Exception("Ongeldig jaar gegeven");
}
// Nu een precieze controle
switch (maand)
{
case 2:
// 1) Als het geen schrikkeljaar is, heeft februari max 28 dagen
// 2) Wel<SUF>
if ((!Maanden.isSchrikkeljaar(jaar) && dag >= 29) || (Maanden.isSchrikkeljaar(jaar) &&
dag > 29))
{
throw new Exception("De dag is niet juist voor de gegeven maand februari");
}
break;
case 4:
case 6:
case 9:
case 11:
if (dag > 30)
{
throw new Exception("De dag is niet juist voor de gegeven maand " + Maanden.get(maand));
}
break;
}
// Alles is goed verlopen
this.dag = dag;
this.maand = maand;
this.jaar = jaar;
return true;
}
/**
*
* @return
*/
public String getDatumInAmerikaansFormaat()
{
return String.format("%04d/%02d/%02d", jaar, maand, dag);
}
/**
*
* @return
*/
public String getDatumInEuropeesFormaat()
{
return String.format("%02d/%02d/%04d", dag, maand, jaar);
}
/**
* Haal de dag van het Datum object op
* @return
*/
public int getDag()
{
return dag;
}
/**
* Haal de maand van het Datum object op
* @return
*/
public int getMaand()
{
return maand;
}
/**
* Haal het jaar van het Datum object op
* @return
*/
public int getJaar()
{
return jaar;
}
/**
* Is de gegeven datum kleiner dan het huidid datum object?
*
* @param datum
* @return
*/
public boolean kleinerDan(Datum datum)
{
return compareTo(datum) > 0;
}
/**
*
* @param datum
* @return
* @throws Exception
*/
public int verschilInJaren(Datum datum) throws Exception
{
return new DatumVerschil(this, datum).getJaren();
}
/**
*
* @param datum
* @return
* @throws Exception
*/
public int verschilInMaanden(Datum datum) throws Exception
{
return new DatumVerschil(this, datum).getMaanden();
}
/**
*
* @param aantalDagen
* @return
* @throws Exception
*/
public Datum veranderDatum(int aantalDagen) throws Exception
{
if (aantalDagen > 0)
{
while (aantalDagen + dag > Maanden.get(maand).aantalDagen(jaar))
{
aantalDagen -= Maanden.get(maand).aantalDagen(jaar) - dag + 1;
// Jaar verhogen
jaar += (maand == 12 ? 1 : 0);
// Maand verhogen
maand = (maand == 12 ? 1 : ++maand);
// We hebben een nieuwe maand, dus terug van 1 beginnen
dag = 1;
}
}
// Negatieve waarde, dus terug in de tijd gaan
else
{
while (-dag >= aantalDagen)
{
// Verminder met aantal dagen in huidige maand.
aantalDagen += dag;
// Verminder jaartal?
jaar -= (maand == 1 ? 1 : 0);
// Verminder maand
maand = (maand == 1 ? 12 : --maand);
// Zet als laatste dag van (vorige) maand
dag = Maanden.get(maand).aantalDagen(jaar);
}
}
return new Datum(dag += aantalDagen, maand, jaar);
}
/**
*
*/
@Override
public boolean equals(Object obj)
{
// Is het exact hetzelfde object?
if (this == obj)
{
return true;
}
// Is het hetzelfde type?
if (obj == null || !(obj instanceof Datum))
{
return false;
}
// Nu zien of de inhoud dezelfde is
return compareTo((Datum) obj) == 0;
}
/**
* Ik snap er de ballen van
*/
@Override
public int hashCode()
{
final int prime = 37;
int hash = 1;
hash = prime * hash + dag;
hash = prime * hash + maand;
hash = prime * hash + jaar;
return hash;
}
/**
* Vergelijk de onze datum met de nieuwe
*/
public int compareTo(Datum datum2)
{
if (jaar > datum2.jaar)
{
return 1;
}
else if (jaar < datum2.jaar)
{
return -1;
}
if (maand > datum2.maand)
{
return 1;
}
else if (maand < datum2.maand)
{
return -1;
}
if (dag > datum2.dag)
{
return 1;
}
else if (dag < datum2.dag)
{
return -1;
}
return 0;
}
/**
* Geef een string representatie terug van de datum
* @return Datum in string formaat
*/
public String toString()
{
return dag + " " + Maanden.get(maand) + " " + jaar;
}
/**
* Return de huidige datum van het systeem
* @return Date
* @throws Exception
*/
@SuppressWarnings("deprecation")
private void HuidigeSysteemDatum() throws Exception
{
Date datum = new Date();
setDatum(datum.getDate(), datum.getMonth() + 1, datum.getYear() + 1900);
}
}
|
18571_1 | /*
* Copyright (C) 2014-2015 Dominik Schürmann <[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 org.openintents.openpgp.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicInteger;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.ParcelFileDescriptor;
import org.openintents.openpgp.IOpenPgpService2;
import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.util.ParcelFileDescriptorUtil.DataSinkTransferThread;
import org.openintents.openpgp.util.ParcelFileDescriptorUtil.DataSourceTransferThread;
import timber.log.Timber;
public class OpenPgpApi {
public static final String SERVICE_INTENT_2 = "org.openintents.openpgp.IOpenPgpService2";
/**
* see CHANGELOG.md
*/
public static final int API_VERSION = 12;
/**
* General extras
* --------------
*
* required extras:
* int EXTRA_API_VERSION (always required)
*
* returned extras:
* int RESULT_CODE (RESULT_CODE_ERROR, RESULT_CODE_SUCCESS or RESULT_CODE_USER_INTERACTION_REQUIRED)
* OpenPgpError RESULT_ERROR (if RESULT_CODE == RESULT_CODE_ERROR)
* PendingIntent RESULT_INTENT (if RESULT_CODE == RESULT_CODE_USER_INTERACTION_REQUIRED)
*/
/**
* This action performs no operation, but can be used to check if the App has permission
* to access the API in general, returning a user interaction PendingIntent otherwise.
* This can be used to trigger the permission dialog explicitly.
*
* This action uses no extras.
*/
public static final String ACTION_CHECK_PERMISSION = "org.openintents.openpgp.action.CHECK_PERMISSION";
@Deprecated
public static final String ACTION_SIGN = "org.openintents.openpgp.action.SIGN";
/**
* Sign text resulting in a cleartext signature
* Some magic pre-processing of the text is done to convert it to a format usable for
* cleartext signatures per RFC 4880 before the text is actually signed:
* - end cleartext with newline
* - remove whitespaces on line endings
*
* required extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
*
* optional extras:
* char[] EXTRA_PASSPHRASE (key passphrase)
*/
public static final String ACTION_CLEARTEXT_SIGN = "org.openintents.openpgp.action.CLEARTEXT_SIGN";
/**
* Sign text or binary data resulting in a detached signature.
* No OutputStream necessary for ACTION_DETACHED_SIGN (No magic pre-processing like in ACTION_CLEARTEXT_SIGN)!
* The detached signature is returned separately in RESULT_DETACHED_SIGNATURE.
*
* required extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
*
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for detached signature)
* char[] EXTRA_PASSPHRASE (key passphrase)
*
* returned extras:
* byte[] RESULT_DETACHED_SIGNATURE
* String RESULT_SIGNATURE_MICALG (contains the name of the used signature algorithm as a string)
*/
public static final String ACTION_DETACHED_SIGN = "org.openintents.openpgp.action.DETACHED_SIGN";
/**
* Encrypt
*
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
*
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
* char[] EXTRA_PASSPHRASE (key passphrase)
* String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
* boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true)
*/
public static final String ACTION_ENCRYPT = "org.openintents.openpgp.action.ENCRYPT";
/**
* Sign and encrypt
*
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
*
* optional extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
* char[] EXTRA_PASSPHRASE (key passphrase)
* String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
* boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true)
*/
public static final String ACTION_SIGN_AND_ENCRYPT = "org.openintents.openpgp.action.SIGN_AND_ENCRYPT";
public static final String ACTION_QUERY_AUTOCRYPT_STATUS = "org.openintents.openpgp.action.QUERY_AUTOCRYPT_STATUS";
/**
* Decrypts and verifies given input stream. This methods handles encrypted-only, signed-and-encrypted,
* and also signed-only input.
* OutputStream is optional, e.g., for verifying detached signatures!
*
* If OpenPgpSignatureResult.getResult() == OpenPgpSignatureResult.RESULT_KEY_MISSING
* in addition a PendingIntent is returned via RESULT_INTENT to download missing keys.
* On all other status, in addition a PendingIntent is returned via RESULT_INTENT to open
* the key view in OpenKeychain.
*
* optional extras:
* byte[] EXTRA_DETACHED_SIGNATURE (detached signature)
*
* returned extras:
* OpenPgpSignatureResult RESULT_SIGNATURE
* OpenPgpDecryptionResult RESULT_DECRYPTION
* OpenPgpDecryptMetadata RESULT_METADATA
* String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any)
*/
public static final String ACTION_DECRYPT_VERIFY = "org.openintents.openpgp.action.DECRYPT_VERIFY";
/**
* Decrypts the header of an encrypted file to retrieve metadata such as original filename.
*
* This does not decrypt the actual content of the file.
*
* returned extras:
* OpenPgpDecryptMetadata RESULT_METADATA
* String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any)
*/
public static final String ACTION_DECRYPT_METADATA = "org.openintents.openpgp.action.DECRYPT_METADATA";
/**
* Select key id for signing
*
* optional extras:
* String EXTRA_USER_ID
*
* returned extras:
* long EXTRA_SIGN_KEY_ID
*/
public static final String ACTION_GET_SIGN_KEY_ID = "org.openintents.openpgp.action.GET_SIGN_KEY_ID";
/**
* Get key ids based on given user ids (=emails)
*
* required extras:
* String[] EXTRA_USER_IDS
*
* returned extras:
* long[] RESULT_KEY_IDS
*/
public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS";
/**
* This action returns RESULT_CODE_SUCCESS if the OpenPGP Provider already has the key
* corresponding to the given key id in its database.
*
* It returns RESULT_CODE_USER_INTERACTION_REQUIRED if the Provider does not have the key.
* The PendingIntent from RESULT_INTENT can be used to retrieve those from a keyserver.
*
* If an Output stream has been defined the whole public key is returned.
* required extras:
* long EXTRA_KEY_ID
*
* optional extras:
* String EXTRA_REQUEST_ASCII_ARMOR (request that the returned key is encoded in ASCII Armor)
*/
public static final String ACTION_GET_KEY = "org.openintents.openpgp.action.GET_KEY";
/**
* Backup all keys given by EXTRA_KEY_IDS and if requested their secret parts.
* The encrypted backup will be written to the OutputStream.
* The client app has no access to the backup code used to encrypt the backup!
* This operation always requires user interaction with RESULT_CODE_USER_INTERACTION_REQUIRED!
*
* required extras:
* long[] EXTRA_KEY_IDS (keys that should be included in the backup)
* boolean EXTRA_BACKUP_SECRET (also backup secret keys)
*/
public static final String ACTION_BACKUP = "org.openintents.openpgp.action.BACKUP";
/**
* Update the status of some Autocrypt peer, identified by their peer id.
*
* required extras:
* String EXTRA_AUTOCRYPT_PEER_ID (autocrypt peer id to update)
* AutocryptPeerUpdate EXTRA_AUTOCRYPT_PEER_UPDATE (actual peer update)
*/
public static final String ACTION_UPDATE_AUTOCRYPT_PEER = "org.openintents.openpgp.action.UPDATE_AUTOCRYPT_PEER";
/* Intent extras */
public static final String EXTRA_API_VERSION = "api_version";
// ACTION_DETACHED_SIGN, ENCRYPT, SIGN_AND_ENCRYPT, DECRYPT_VERIFY
// request ASCII Armor for output
// OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53)
public static final String EXTRA_REQUEST_ASCII_ARMOR = "ascii_armor";
// ACTION_DETACHED_SIGN
public static final String RESULT_DETACHED_SIGNATURE = "detached_signature";
public static final String RESULT_SIGNATURE_MICALG = "signature_micalg";
// ENCRYPT, SIGN_AND_ENCRYPT, QUERY_AUTOCRYPT_STATUS
public static final String EXTRA_USER_IDS = "user_ids";
public static final String EXTRA_KEY_IDS = "key_ids";
public static final String EXTRA_KEY_IDS_SELECTED = "key_ids_selected";
public static final String EXTRA_SIGN_KEY_ID = "sign_key_id";
public static final String RESULT_KEYS_CONFIRMED = "keys_confirmed";
public static final String RESULT_AUTOCRYPT_STATUS = "autocrypt_status";
public static final int AUTOCRYPT_STATUS_UNAVAILABLE = 0;
public static final int AUTOCRYPT_STATUS_DISCOURAGE = 1;
public static final int AUTOCRYPT_STATUS_AVAILABLE = 2;
public static final int AUTOCRYPT_STATUS_MUTUAL = 3;
// optional extras:
public static final String EXTRA_PASSPHRASE = "passphrase";
public static final String EXTRA_ORIGINAL_FILENAME = "original_filename";
public static final String EXTRA_ENABLE_COMPRESSION = "enable_compression";
public static final String EXTRA_OPPORTUNISTIC_ENCRYPTION = "opportunistic";
// GET_SIGN_KEY_ID
public static final String EXTRA_USER_ID = "user_id";
public static final String EXTRA_PRESELECT_KEY_ID = "preselect_key_id";
public static final String EXTRA_SHOW_AUTOCRYPT_HINT = "show_autocrypt_hint";
// GET_KEY
public static final String EXTRA_KEY_ID = "key_id";
public static final String EXTRA_MINIMIZE = "minimize";
public static final String EXTRA_MINIMIZE_USER_ID = "minimize_user_id";
public static final String RESULT_KEY_IDS = "key_ids";
// AUTOCRYPT_KEY_TRANSFER
public static final String ACTION_AUTOCRYPT_KEY_TRANSFER = "autocrypt_key_transfer";
// BACKUP
public static final String EXTRA_BACKUP_SECRET = "backup_secret";
/* Service Intent returns */
public static final String RESULT_CODE = "result_code";
// get actual error object from RESULT_ERROR
public static final int RESULT_CODE_ERROR = 0;
// success!
public static final int RESULT_CODE_SUCCESS = 1;
// get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult,
// and execute service method again in onActivityResult
public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2;
public static final String RESULT_ERROR = "error";
public static final String RESULT_INTENT = "intent";
// DECRYPT_VERIFY
public static final String EXTRA_DETACHED_SIGNATURE = "detached_signature";
public static final String EXTRA_PROGRESS_MESSENGER = "progress_messenger";
public static final String EXTRA_DATA_LENGTH = "data_length";
public static final String EXTRA_DECRYPTION_RESULT = "decryption_result";
public static final String EXTRA_SENDER_ADDRESS = "sender_address";
public static final String EXTRA_SUPPORT_OVERRIDE_CRYPTO_WARNING = "support_override_crpto_warning";
public static final String RESULT_SIGNATURE = "signature";
public static final String RESULT_DECRYPTION = "decryption";
public static final String RESULT_METADATA = "metadata";
public static final String RESULT_INSECURE_DETAIL_INTENT = "insecure_detail_intent";
public static final String RESULT_OVERRIDE_CRYPTO_WARNING = "override_crypto_warning";
// This will be the charset which was specified in the headers of ascii armored input, if any
public static final String RESULT_CHARSET = "charset";
// UPDATE_AUTOCRYPT_PEER
public static final String EXTRA_AUTOCRYPT_PEER_ID = "autocrypt_peer_id";
public static final String EXTRA_AUTOCRYPT_PEER_UPDATE = "autocrypt_peer_update";
public static final String EXTRA_AUTOCRYPT_PEER_GOSSIP_UPDATES = "autocrypt_peer_gossip_updates";
// INTERNAL, must not be used
public static final String EXTRA_CALL_UUID1 = "call_uuid1";
public static final String EXTRA_CALL_UUID2 = "call_uuid2";
IOpenPgpService2 mService;
Context mContext;
final AtomicInteger mPipeIdGen = new AtomicInteger();
public OpenPgpApi(Context context, IOpenPgpService2 service) {
this.mContext = context;
this.mService = service;
}
public interface IOpenPgpCallback {
void onReturn(final Intent result);
}
public interface IOpenPgpSinkResultCallback<T> {
void onProgress(int current, int max);
void onReturn(final Intent result, T sinkResult);
}
public interface CancelableBackgroundOperation {
void cancelOperation();
}
private class OpenPgpSourceSinkAsyncTask<T> extends AsyncTask<Void, Integer, OpenPgpDataResult<T>>
implements CancelableBackgroundOperation {
Intent data;
OpenPgpDataSource dataSource;
OpenPgpDataSink<T> dataSink;
IOpenPgpSinkResultCallback<T> callback;
private OpenPgpSourceSinkAsyncTask(Intent data, OpenPgpDataSource dataSource,
OpenPgpDataSink<T> dataSink, IOpenPgpSinkResultCallback<T> callback) {
this.data = data;
this.dataSource = dataSource;
this.dataSink = dataSink;
this.callback = callback;
}
@Override
protected OpenPgpDataResult<T> doInBackground(Void... unused) {
return executeApi(data, dataSource, dataSink);
}
protected void onPostExecute(OpenPgpDataResult<T> result) {
callback.onReturn(result.apiResult, result.sinkResult);
}
@Override
public void cancelOperation() {
cancel(true);
if (dataSource != null) {
dataSource.cancel();
}
}
}
class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> {
Intent data;
InputStream is;
OutputStream os;
IOpenPgpCallback callback;
private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
this.data = data;
this.is = is;
this.os = os;
this.callback = callback;
}
@Override
protected Intent doInBackground(Void... unused) {
return executeApi(data, is, os);
}
protected void onPostExecute(Intent result) {
callback.onReturn(result);
}
}
public <T> CancelableBackgroundOperation executeApiAsync(Intent data, OpenPgpDataSource dataSource,
OpenPgpDataSink<T> dataSink, final IOpenPgpSinkResultCallback<T> callback) {
Messenger messenger = new Messenger(new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
callback.onProgress(message.arg1, message.arg2);
return true;
}
}));
data.putExtra(EXTRA_PROGRESS_MESSENGER, messenger);
OpenPgpSourceSinkAsyncTask<T> task = new OpenPgpSourceSinkAsyncTask<>(data, dataSource, dataSink, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
return task;
}
public AsyncTask executeApiAsync(Intent data, OpenPgpDataSource dataSource, IOpenPgpSinkResultCallback<Void> callback) {
OpenPgpSourceSinkAsyncTask<Void> task = new OpenPgpSourceSinkAsyncTask<>(data, dataSource, null, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
return task;
}
public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
}
public static class OpenPgpDataResult<T> {
Intent apiResult;
T sinkResult;
public OpenPgpDataResult(Intent apiResult, T sinkResult) {
this.apiResult = apiResult;
this.sinkResult = sinkResult;
}
}
public <T> OpenPgpDataResult<T> executeApi(Intent data, OpenPgpDataSource dataSource, OpenPgpDataSink<T> dataSink) {
ParcelFileDescriptor input = null;
ParcelFileDescriptor output = null;
try {
if (dataSource != null) {
Long expectedSize = dataSource.getSizeForProgress();
if (expectedSize != null) {
data.putExtra(EXTRA_DATA_LENGTH, (long) expectedSize);
} else {
data.removeExtra(EXTRA_PROGRESS_MESSENGER);
}
input = dataSource.startPumpThread();
}
DataSinkTransferThread<T> pumpThread = null;
int outputPipeId = 0;
if (dataSink != null) {
outputPipeId = mPipeIdGen.incrementAndGet();
output = mService.createOutputPipe(outputPipeId);
pumpThread = ParcelFileDescriptorUtil.asyncPipeToDataSink(dataSink, output);
}
Intent result = executeApi(data, input, outputPipeId);
if (pumpThread == null) {
return new OpenPgpDataResult<>(result, null);
}
// wait for ALL data being pumped from remote side
pumpThread.join();
return new OpenPgpDataResult<>(result, pumpThread.getResult());
} catch (Exception e) {
Timber.e(e, "Exception in executeApi call");
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return new OpenPgpDataResult<>(result, null);
} finally {
closeLoudly(output);
}
}
public Intent executeApi(Intent data, InputStream is, OutputStream os) {
ParcelFileDescriptor input = null;
ParcelFileDescriptor output = null;
try {
if (is != null) {
input = ParcelFileDescriptorUtil.pipeFrom(is);
}
Thread pumpThread = null;
int outputPipeId = 0;
if (os != null) {
outputPipeId = mPipeIdGen.incrementAndGet();
output = mService.createOutputPipe(outputPipeId);
pumpThread = ParcelFileDescriptorUtil.pipeTo(os, output);
}
Intent result = executeApi(data, input, outputPipeId);
// wait for ALL data being pumped from remote side
if (pumpThread != null) {
pumpThread.join();
}
return result;
} catch (Exception e) {
Timber.e(e, "Exception in executeApi call");
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
} finally {
closeLoudly(output);
}
}
public static abstract class OpenPgpDataSource {
private boolean isCancelled;
private ParcelFileDescriptor writeSidePfd;
public abstract void writeTo(OutputStream os) throws IOException;
public Long getSizeForProgress() {
return null;
}
public boolean isCancelled() {
return isCancelled;
}
public ParcelFileDescriptor startPumpThread() throws IOException {
if (writeSidePfd != null) {
throw new IllegalStateException("startPumpThread() must only be called once!");
}
ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
ParcelFileDescriptor readSidePfd = pipe[0];
writeSidePfd = pipe[1];
new DataSourceTransferThread(this, new ParcelFileDescriptor.AutoCloseOutputStream(writeSidePfd)).start();
return readSidePfd;
}
private void cancel() {
isCancelled = true;
try {
writeSidePfd.close();
} catch (IOException e) {
// this is fine
}
}
}
public interface OpenPgpDataSink<T> {
T processData(InputStream is) throws IOException;
}
public Intent executeApi(Intent data, OpenPgpDataSource dataSource, OutputStream os) {
ParcelFileDescriptor input = null;
ParcelFileDescriptor output;
try {
if (dataSource != null) {
Long expectedSize = dataSource.getSizeForProgress();
if (expectedSize != null) {
data.putExtra(EXTRA_DATA_LENGTH, (long) expectedSize);
} else {
data.removeExtra(EXTRA_PROGRESS_MESSENGER);
}
input = dataSource.startPumpThread();
}
Thread pumpThread = null;
int outputPipeId = 0;
if (os != null) {
outputPipeId = mPipeIdGen.incrementAndGet();
output = mService.createOutputPipe(outputPipeId);
pumpThread = ParcelFileDescriptorUtil.pipeTo(os, output);
}
Intent result = executeApi(data, input, outputPipeId);
// wait for ALL data being pumped from remote side
if (pumpThread != null) {
pumpThread.join();
}
return result;
} catch (Exception e) {
Timber.e(e, "Exception in executeApi call");
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
}
}
/**
* InputStream and OutputStreams are always closed after operating on them!
*/
private Intent executeApi(Intent data, ParcelFileDescriptor input, int outputPipeId) {
try {
// always send version from client
data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
Intent result;
// blocks until result is ready
result = mService.execute(data, input, outputPipeId);
// set class loader to current context to allow unparcelling
// of OpenPgpError and OpenPgpSignatureResult
// http://stackoverflow.com/a/3806769
result.setExtrasClassLoader(mContext.getClassLoader());
return result;
} catch (Exception e) {
Timber.e(e, "Exception in executeApi call");
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
} finally {
// close() is required to halt the TransferThread
closeLoudly(input);
}
}
private static void closeLoudly(ParcelFileDescriptor input) {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Timber.e(e, "IOException when closing ParcelFileDescriptor!");
}
}
}
public interface PermissionPingCallback {
void onPgpPermissionCheckResult(Intent result);
}
public void checkPermissionPing(final PermissionPingCallback permissionPingCallback) {
Intent intent = new Intent(OpenPgpApi.ACTION_CHECK_PERMISSION);
executeApiAsync(intent, null, null, new IOpenPgpCallback() {
@Override
public void onReturn(Intent result) {
permissionPingCallback.onPgpPermissionCheckResult(result);
}
});
}
}
| thunderbird/thunderbird-android | plugins/openpgp-api-lib/openpgp-api/src/main/java/org/openintents/openpgp/util/OpenPgpApi.java | 7,770 | /**
* see CHANGELOG.md
*/ | block_comment | nl | /*
* Copyright (C) 2014-2015 Dominik Schürmann <[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 org.openintents.openpgp.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicInteger;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.ParcelFileDescriptor;
import org.openintents.openpgp.IOpenPgpService2;
import org.openintents.openpgp.OpenPgpError;
import org.openintents.openpgp.util.ParcelFileDescriptorUtil.DataSinkTransferThread;
import org.openintents.openpgp.util.ParcelFileDescriptorUtil.DataSourceTransferThread;
import timber.log.Timber;
public class OpenPgpApi {
public static final String SERVICE_INTENT_2 = "org.openintents.openpgp.IOpenPgpService2";
/**
* see CHANGELOG.md
<SUF>*/
public static final int API_VERSION = 12;
/**
* General extras
* --------------
*
* required extras:
* int EXTRA_API_VERSION (always required)
*
* returned extras:
* int RESULT_CODE (RESULT_CODE_ERROR, RESULT_CODE_SUCCESS or RESULT_CODE_USER_INTERACTION_REQUIRED)
* OpenPgpError RESULT_ERROR (if RESULT_CODE == RESULT_CODE_ERROR)
* PendingIntent RESULT_INTENT (if RESULT_CODE == RESULT_CODE_USER_INTERACTION_REQUIRED)
*/
/**
* This action performs no operation, but can be used to check if the App has permission
* to access the API in general, returning a user interaction PendingIntent otherwise.
* This can be used to trigger the permission dialog explicitly.
*
* This action uses no extras.
*/
public static final String ACTION_CHECK_PERMISSION = "org.openintents.openpgp.action.CHECK_PERMISSION";
@Deprecated
public static final String ACTION_SIGN = "org.openintents.openpgp.action.SIGN";
/**
* Sign text resulting in a cleartext signature
* Some magic pre-processing of the text is done to convert it to a format usable for
* cleartext signatures per RFC 4880 before the text is actually signed:
* - end cleartext with newline
* - remove whitespaces on line endings
*
* required extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
*
* optional extras:
* char[] EXTRA_PASSPHRASE (key passphrase)
*/
public static final String ACTION_CLEARTEXT_SIGN = "org.openintents.openpgp.action.CLEARTEXT_SIGN";
/**
* Sign text or binary data resulting in a detached signature.
* No OutputStream necessary for ACTION_DETACHED_SIGN (No magic pre-processing like in ACTION_CLEARTEXT_SIGN)!
* The detached signature is returned separately in RESULT_DETACHED_SIGNATURE.
*
* required extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
*
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for detached signature)
* char[] EXTRA_PASSPHRASE (key passphrase)
*
* returned extras:
* byte[] RESULT_DETACHED_SIGNATURE
* String RESULT_SIGNATURE_MICALG (contains the name of the used signature algorithm as a string)
*/
public static final String ACTION_DETACHED_SIGN = "org.openintents.openpgp.action.DETACHED_SIGN";
/**
* Encrypt
*
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
*
* optional extras:
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
* char[] EXTRA_PASSPHRASE (key passphrase)
* String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
* boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true)
*/
public static final String ACTION_ENCRYPT = "org.openintents.openpgp.action.ENCRYPT";
/**
* Sign and encrypt
*
* required extras:
* String[] EXTRA_USER_IDS (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
* or
* long[] EXTRA_KEY_IDS
*
* optional extras:
* long EXTRA_SIGN_KEY_ID (key id of signing key)
* boolean EXTRA_REQUEST_ASCII_ARMOR (request ascii armor for output)
* char[] EXTRA_PASSPHRASE (key passphrase)
* String EXTRA_ORIGINAL_FILENAME (original filename to be encrypted as metadata)
* boolean EXTRA_ENABLE_COMPRESSION (enable ZLIB compression, default ist true)
*/
public static final String ACTION_SIGN_AND_ENCRYPT = "org.openintents.openpgp.action.SIGN_AND_ENCRYPT";
public static final String ACTION_QUERY_AUTOCRYPT_STATUS = "org.openintents.openpgp.action.QUERY_AUTOCRYPT_STATUS";
/**
* Decrypts and verifies given input stream. This methods handles encrypted-only, signed-and-encrypted,
* and also signed-only input.
* OutputStream is optional, e.g., for verifying detached signatures!
*
* If OpenPgpSignatureResult.getResult() == OpenPgpSignatureResult.RESULT_KEY_MISSING
* in addition a PendingIntent is returned via RESULT_INTENT to download missing keys.
* On all other status, in addition a PendingIntent is returned via RESULT_INTENT to open
* the key view in OpenKeychain.
*
* optional extras:
* byte[] EXTRA_DETACHED_SIGNATURE (detached signature)
*
* returned extras:
* OpenPgpSignatureResult RESULT_SIGNATURE
* OpenPgpDecryptionResult RESULT_DECRYPTION
* OpenPgpDecryptMetadata RESULT_METADATA
* String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any)
*/
public static final String ACTION_DECRYPT_VERIFY = "org.openintents.openpgp.action.DECRYPT_VERIFY";
/**
* Decrypts the header of an encrypted file to retrieve metadata such as original filename.
*
* This does not decrypt the actual content of the file.
*
* returned extras:
* OpenPgpDecryptMetadata RESULT_METADATA
* String RESULT_CHARSET (charset which was specified in the headers of ascii armored input, if any)
*/
public static final String ACTION_DECRYPT_METADATA = "org.openintents.openpgp.action.DECRYPT_METADATA";
/**
* Select key id for signing
*
* optional extras:
* String EXTRA_USER_ID
*
* returned extras:
* long EXTRA_SIGN_KEY_ID
*/
public static final String ACTION_GET_SIGN_KEY_ID = "org.openintents.openpgp.action.GET_SIGN_KEY_ID";
/**
* Get key ids based on given user ids (=emails)
*
* required extras:
* String[] EXTRA_USER_IDS
*
* returned extras:
* long[] RESULT_KEY_IDS
*/
public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS";
/**
* This action returns RESULT_CODE_SUCCESS if the OpenPGP Provider already has the key
* corresponding to the given key id in its database.
*
* It returns RESULT_CODE_USER_INTERACTION_REQUIRED if the Provider does not have the key.
* The PendingIntent from RESULT_INTENT can be used to retrieve those from a keyserver.
*
* If an Output stream has been defined the whole public key is returned.
* required extras:
* long EXTRA_KEY_ID
*
* optional extras:
* String EXTRA_REQUEST_ASCII_ARMOR (request that the returned key is encoded in ASCII Armor)
*/
public static final String ACTION_GET_KEY = "org.openintents.openpgp.action.GET_KEY";
/**
* Backup all keys given by EXTRA_KEY_IDS and if requested their secret parts.
* The encrypted backup will be written to the OutputStream.
* The client app has no access to the backup code used to encrypt the backup!
* This operation always requires user interaction with RESULT_CODE_USER_INTERACTION_REQUIRED!
*
* required extras:
* long[] EXTRA_KEY_IDS (keys that should be included in the backup)
* boolean EXTRA_BACKUP_SECRET (also backup secret keys)
*/
public static final String ACTION_BACKUP = "org.openintents.openpgp.action.BACKUP";
/**
* Update the status of some Autocrypt peer, identified by their peer id.
*
* required extras:
* String EXTRA_AUTOCRYPT_PEER_ID (autocrypt peer id to update)
* AutocryptPeerUpdate EXTRA_AUTOCRYPT_PEER_UPDATE (actual peer update)
*/
public static final String ACTION_UPDATE_AUTOCRYPT_PEER = "org.openintents.openpgp.action.UPDATE_AUTOCRYPT_PEER";
/* Intent extras */
public static final String EXTRA_API_VERSION = "api_version";
// ACTION_DETACHED_SIGN, ENCRYPT, SIGN_AND_ENCRYPT, DECRYPT_VERIFY
// request ASCII Armor for output
// OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53)
public static final String EXTRA_REQUEST_ASCII_ARMOR = "ascii_armor";
// ACTION_DETACHED_SIGN
public static final String RESULT_DETACHED_SIGNATURE = "detached_signature";
public static final String RESULT_SIGNATURE_MICALG = "signature_micalg";
// ENCRYPT, SIGN_AND_ENCRYPT, QUERY_AUTOCRYPT_STATUS
public static final String EXTRA_USER_IDS = "user_ids";
public static final String EXTRA_KEY_IDS = "key_ids";
public static final String EXTRA_KEY_IDS_SELECTED = "key_ids_selected";
public static final String EXTRA_SIGN_KEY_ID = "sign_key_id";
public static final String RESULT_KEYS_CONFIRMED = "keys_confirmed";
public static final String RESULT_AUTOCRYPT_STATUS = "autocrypt_status";
public static final int AUTOCRYPT_STATUS_UNAVAILABLE = 0;
public static final int AUTOCRYPT_STATUS_DISCOURAGE = 1;
public static final int AUTOCRYPT_STATUS_AVAILABLE = 2;
public static final int AUTOCRYPT_STATUS_MUTUAL = 3;
// optional extras:
public static final String EXTRA_PASSPHRASE = "passphrase";
public static final String EXTRA_ORIGINAL_FILENAME = "original_filename";
public static final String EXTRA_ENABLE_COMPRESSION = "enable_compression";
public static final String EXTRA_OPPORTUNISTIC_ENCRYPTION = "opportunistic";
// GET_SIGN_KEY_ID
public static final String EXTRA_USER_ID = "user_id";
public static final String EXTRA_PRESELECT_KEY_ID = "preselect_key_id";
public static final String EXTRA_SHOW_AUTOCRYPT_HINT = "show_autocrypt_hint";
// GET_KEY
public static final String EXTRA_KEY_ID = "key_id";
public static final String EXTRA_MINIMIZE = "minimize";
public static final String EXTRA_MINIMIZE_USER_ID = "minimize_user_id";
public static final String RESULT_KEY_IDS = "key_ids";
// AUTOCRYPT_KEY_TRANSFER
public static final String ACTION_AUTOCRYPT_KEY_TRANSFER = "autocrypt_key_transfer";
// BACKUP
public static final String EXTRA_BACKUP_SECRET = "backup_secret";
/* Service Intent returns */
public static final String RESULT_CODE = "result_code";
// get actual error object from RESULT_ERROR
public static final int RESULT_CODE_ERROR = 0;
// success!
public static final int RESULT_CODE_SUCCESS = 1;
// get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult,
// and execute service method again in onActivityResult
public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2;
public static final String RESULT_ERROR = "error";
public static final String RESULT_INTENT = "intent";
// DECRYPT_VERIFY
public static final String EXTRA_DETACHED_SIGNATURE = "detached_signature";
public static final String EXTRA_PROGRESS_MESSENGER = "progress_messenger";
public static final String EXTRA_DATA_LENGTH = "data_length";
public static final String EXTRA_DECRYPTION_RESULT = "decryption_result";
public static final String EXTRA_SENDER_ADDRESS = "sender_address";
public static final String EXTRA_SUPPORT_OVERRIDE_CRYPTO_WARNING = "support_override_crpto_warning";
public static final String RESULT_SIGNATURE = "signature";
public static final String RESULT_DECRYPTION = "decryption";
public static final String RESULT_METADATA = "metadata";
public static final String RESULT_INSECURE_DETAIL_INTENT = "insecure_detail_intent";
public static final String RESULT_OVERRIDE_CRYPTO_WARNING = "override_crypto_warning";
// This will be the charset which was specified in the headers of ascii armored input, if any
public static final String RESULT_CHARSET = "charset";
// UPDATE_AUTOCRYPT_PEER
public static final String EXTRA_AUTOCRYPT_PEER_ID = "autocrypt_peer_id";
public static final String EXTRA_AUTOCRYPT_PEER_UPDATE = "autocrypt_peer_update";
public static final String EXTRA_AUTOCRYPT_PEER_GOSSIP_UPDATES = "autocrypt_peer_gossip_updates";
// INTERNAL, must not be used
public static final String EXTRA_CALL_UUID1 = "call_uuid1";
public static final String EXTRA_CALL_UUID2 = "call_uuid2";
IOpenPgpService2 mService;
Context mContext;
final AtomicInteger mPipeIdGen = new AtomicInteger();
public OpenPgpApi(Context context, IOpenPgpService2 service) {
this.mContext = context;
this.mService = service;
}
public interface IOpenPgpCallback {
void onReturn(final Intent result);
}
public interface IOpenPgpSinkResultCallback<T> {
void onProgress(int current, int max);
void onReturn(final Intent result, T sinkResult);
}
public interface CancelableBackgroundOperation {
void cancelOperation();
}
private class OpenPgpSourceSinkAsyncTask<T> extends AsyncTask<Void, Integer, OpenPgpDataResult<T>>
implements CancelableBackgroundOperation {
Intent data;
OpenPgpDataSource dataSource;
OpenPgpDataSink<T> dataSink;
IOpenPgpSinkResultCallback<T> callback;
private OpenPgpSourceSinkAsyncTask(Intent data, OpenPgpDataSource dataSource,
OpenPgpDataSink<T> dataSink, IOpenPgpSinkResultCallback<T> callback) {
this.data = data;
this.dataSource = dataSource;
this.dataSink = dataSink;
this.callback = callback;
}
@Override
protected OpenPgpDataResult<T> doInBackground(Void... unused) {
return executeApi(data, dataSource, dataSink);
}
protected void onPostExecute(OpenPgpDataResult<T> result) {
callback.onReturn(result.apiResult, result.sinkResult);
}
@Override
public void cancelOperation() {
cancel(true);
if (dataSource != null) {
dataSource.cancel();
}
}
}
class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> {
Intent data;
InputStream is;
OutputStream os;
IOpenPgpCallback callback;
private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
this.data = data;
this.is = is;
this.os = os;
this.callback = callback;
}
@Override
protected Intent doInBackground(Void... unused) {
return executeApi(data, is, os);
}
protected void onPostExecute(Intent result) {
callback.onReturn(result);
}
}
public <T> CancelableBackgroundOperation executeApiAsync(Intent data, OpenPgpDataSource dataSource,
OpenPgpDataSink<T> dataSink, final IOpenPgpSinkResultCallback<T> callback) {
Messenger messenger = new Messenger(new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
callback.onProgress(message.arg1, message.arg2);
return true;
}
}));
data.putExtra(EXTRA_PROGRESS_MESSENGER, messenger);
OpenPgpSourceSinkAsyncTask<T> task = new OpenPgpSourceSinkAsyncTask<>(data, dataSource, dataSink, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
return task;
}
public AsyncTask executeApiAsync(Intent data, OpenPgpDataSource dataSource, IOpenPgpSinkResultCallback<Void> callback) {
OpenPgpSourceSinkAsyncTask<Void> task = new OpenPgpSourceSinkAsyncTask<>(data, dataSource, null, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
return task;
}
public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback);
// don't serialize async tasks!
// http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
}
public static class OpenPgpDataResult<T> {
Intent apiResult;
T sinkResult;
public OpenPgpDataResult(Intent apiResult, T sinkResult) {
this.apiResult = apiResult;
this.sinkResult = sinkResult;
}
}
public <T> OpenPgpDataResult<T> executeApi(Intent data, OpenPgpDataSource dataSource, OpenPgpDataSink<T> dataSink) {
ParcelFileDescriptor input = null;
ParcelFileDescriptor output = null;
try {
if (dataSource != null) {
Long expectedSize = dataSource.getSizeForProgress();
if (expectedSize != null) {
data.putExtra(EXTRA_DATA_LENGTH, (long) expectedSize);
} else {
data.removeExtra(EXTRA_PROGRESS_MESSENGER);
}
input = dataSource.startPumpThread();
}
DataSinkTransferThread<T> pumpThread = null;
int outputPipeId = 0;
if (dataSink != null) {
outputPipeId = mPipeIdGen.incrementAndGet();
output = mService.createOutputPipe(outputPipeId);
pumpThread = ParcelFileDescriptorUtil.asyncPipeToDataSink(dataSink, output);
}
Intent result = executeApi(data, input, outputPipeId);
if (pumpThread == null) {
return new OpenPgpDataResult<>(result, null);
}
// wait for ALL data being pumped from remote side
pumpThread.join();
return new OpenPgpDataResult<>(result, pumpThread.getResult());
} catch (Exception e) {
Timber.e(e, "Exception in executeApi call");
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return new OpenPgpDataResult<>(result, null);
} finally {
closeLoudly(output);
}
}
public Intent executeApi(Intent data, InputStream is, OutputStream os) {
ParcelFileDescriptor input = null;
ParcelFileDescriptor output = null;
try {
if (is != null) {
input = ParcelFileDescriptorUtil.pipeFrom(is);
}
Thread pumpThread = null;
int outputPipeId = 0;
if (os != null) {
outputPipeId = mPipeIdGen.incrementAndGet();
output = mService.createOutputPipe(outputPipeId);
pumpThread = ParcelFileDescriptorUtil.pipeTo(os, output);
}
Intent result = executeApi(data, input, outputPipeId);
// wait for ALL data being pumped from remote side
if (pumpThread != null) {
pumpThread.join();
}
return result;
} catch (Exception e) {
Timber.e(e, "Exception in executeApi call");
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
} finally {
closeLoudly(output);
}
}
public static abstract class OpenPgpDataSource {
private boolean isCancelled;
private ParcelFileDescriptor writeSidePfd;
public abstract void writeTo(OutputStream os) throws IOException;
public Long getSizeForProgress() {
return null;
}
public boolean isCancelled() {
return isCancelled;
}
public ParcelFileDescriptor startPumpThread() throws IOException {
if (writeSidePfd != null) {
throw new IllegalStateException("startPumpThread() must only be called once!");
}
ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
ParcelFileDescriptor readSidePfd = pipe[0];
writeSidePfd = pipe[1];
new DataSourceTransferThread(this, new ParcelFileDescriptor.AutoCloseOutputStream(writeSidePfd)).start();
return readSidePfd;
}
private void cancel() {
isCancelled = true;
try {
writeSidePfd.close();
} catch (IOException e) {
// this is fine
}
}
}
public interface OpenPgpDataSink<T> {
T processData(InputStream is) throws IOException;
}
public Intent executeApi(Intent data, OpenPgpDataSource dataSource, OutputStream os) {
ParcelFileDescriptor input = null;
ParcelFileDescriptor output;
try {
if (dataSource != null) {
Long expectedSize = dataSource.getSizeForProgress();
if (expectedSize != null) {
data.putExtra(EXTRA_DATA_LENGTH, (long) expectedSize);
} else {
data.removeExtra(EXTRA_PROGRESS_MESSENGER);
}
input = dataSource.startPumpThread();
}
Thread pumpThread = null;
int outputPipeId = 0;
if (os != null) {
outputPipeId = mPipeIdGen.incrementAndGet();
output = mService.createOutputPipe(outputPipeId);
pumpThread = ParcelFileDescriptorUtil.pipeTo(os, output);
}
Intent result = executeApi(data, input, outputPipeId);
// wait for ALL data being pumped from remote side
if (pumpThread != null) {
pumpThread.join();
}
return result;
} catch (Exception e) {
Timber.e(e, "Exception in executeApi call");
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
}
}
/**
* InputStream and OutputStreams are always closed after operating on them!
*/
private Intent executeApi(Intent data, ParcelFileDescriptor input, int outputPipeId) {
try {
// always send version from client
data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
Intent result;
// blocks until result is ready
result = mService.execute(data, input, outputPipeId);
// set class loader to current context to allow unparcelling
// of OpenPgpError and OpenPgpSignatureResult
// http://stackoverflow.com/a/3806769
result.setExtrasClassLoader(mContext.getClassLoader());
return result;
} catch (Exception e) {
Timber.e(e, "Exception in executeApi call");
Intent result = new Intent();
result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
result.putExtra(RESULT_ERROR,
new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
return result;
} finally {
// close() is required to halt the TransferThread
closeLoudly(input);
}
}
private static void closeLoudly(ParcelFileDescriptor input) {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Timber.e(e, "IOException when closing ParcelFileDescriptor!");
}
}
}
public interface PermissionPingCallback {
void onPgpPermissionCheckResult(Intent result);
}
public void checkPermissionPing(final PermissionPingCallback permissionPingCallback) {
Intent intent = new Intent(OpenPgpApi.ACTION_CHECK_PERMISSION);
executeApiAsync(intent, null, null, new IOpenPgpCallback() {
@Override
public void onReturn(Intent result) {
permissionPingCallback.onPgpPermissionCheckResult(result);
}
});
}
}
|
38801_7 | package com.taobao.rigel.rap.auto.generate.contract;
import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.GeneratorType;
import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.TargetObjectType;
import com.taobao.rigel.rap.project.bo.Project.STAGE_TYPE;
/**
* generator interface, all generator class should
* implement this interface
*
* @author Bosn
*/
public interface Generator {
/**
* is available on specific stage
*
* @param stage
* @return
*/
boolean isAvailable(STAGE_TYPE stage);
/**
* get generator type
*
* @return
*/
GeneratorType getGeneratorType();
/**
* get author
*
* @return author
*/
String getAuthor();
/**
* get introduction of generator
*
* @return
*/
String getIntroduction();
/**
* get target object type
*
* @return
*/
TargetObjectType getTargetObjectType();
/**
* this method will be invoked automatically
* by RAP before using, the type of Object is
* decided by the return value of
* getTargetObjectType() method, eg. if
* result PROJECT, RAP will pass the proper
* Project object automatically.
*
* @param project
*/
void setObject(Object obj);
/**
* do generate
*
* @return generated result
*/
String doGenerate();
}
| thx/RAP | src/main/java/com/taobao/rigel/rap/auto/generate/contract/Generator.java | 399 | /**
* do generate
*
* @return generated result
*/ | block_comment | nl | package com.taobao.rigel.rap.auto.generate.contract;
import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.GeneratorType;
import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.TargetObjectType;
import com.taobao.rigel.rap.project.bo.Project.STAGE_TYPE;
/**
* generator interface, all generator class should
* implement this interface
*
* @author Bosn
*/
public interface Generator {
/**
* is available on specific stage
*
* @param stage
* @return
*/
boolean isAvailable(STAGE_TYPE stage);
/**
* get generator type
*
* @return
*/
GeneratorType getGeneratorType();
/**
* get author
*
* @return author
*/
String getAuthor();
/**
* get introduction of generator
*
* @return
*/
String getIntroduction();
/**
* get target object type
*
* @return
*/
TargetObjectType getTargetObjectType();
/**
* this method will be invoked automatically
* by RAP before using, the type of Object is
* decided by the return value of
* getTargetObjectType() method, eg. if
* result PROJECT, RAP will pass the proper
* Project object automatically.
*
* @param project
*/
void setObject(Object obj);
/**
* do generate
<SUF>*/
String doGenerate();
}
|
191252_14 | /*
* @(#)MathConstants.java 2.1.1-1 2016-01-07
*
* You may use this software under the condition of "Simplified BSD License"
*
* Copyright 2010-2016 MARIUSZ GROMADA. 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.
*
* THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``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 <COPYRIGHT HOLDER> OR
* 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of MARIUSZ GROMADA.
*
* If you have any questions/bugs feel free to contact:
*
* Mariusz Gromada
* [email protected]
* http://mathspace.pl/
* http://mathparser.org/
* http://github.com/mariuszgromada/MathParser.org-mXparser
* http://mariuszgromada.github.io/MathParser.org-mXparser/
* http://mxparser.sourceforge.net/
* http://bitbucket.org/mariuszgromada/mxparser/
* http://mxparser.codeplex.com/
*
* Asked if he believes in one God, a mathematician answered:
* "Yes, up to isomorphism."
*/
package org.mariuszgromada.math.mxparser.mathcollection;
/**
* MathConstants - class representing the most important math constants.
*
* @author <b>Mariusz Gromada</b><br/>
* <a href="mailto:[email protected]">[email protected]</a><br>
* <a href="http://mathspace.pl/" target="_blank">MathSpace.pl</a><br>
* <a href="http://mathparser.org/" target="_blank">MathParser.org - mXparser project page</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
* <a href="http://mariuszgromada.github.io/MathParser.org-mXparser/" target="_blank">mXparser on GitHub pages</a><br>
* <a href="http://mxparser.sourceforge.net/" target="_blank">mXparser on SourceForge/</a><br>
* <a href="http://bitbucket.org/mariuszgromada/mxparser/" target="_blank">mXparser on Bitbucket/</a><br>
* <a href="http://mxparser.codeplex.com/" target="_blank">mXparser on CodePlex/</a><br>
*
* @version 2.1.1-1
*/
public final class MathConstants {
/**
* Pi, Archimedes' constant or Ludolph's number
*/
public static final double PI = 3.14159265358979323846264338327950288;
/**
* Napier's constant, or Euler's number, base of Natural logarithm
*/
public static final double E = 2.71828182845904523536028747135266249;
/**
* Euler-Mascheroni constant
*/
public static final double EULER_MASCHERONI = 0.57721566490153286060651209008240243;
/**
* Golden ratio
*/
public static final double GOLDEN_RATIO = 1.61803398874989484820458683436563811;
/**
* Plastic constant
*/
public static final double PLASTIC = 1.32471795724474602596090885447809734;
/**
* Embree-Trefethen constant
*/
public static final double EMBREE_TREFETHEN = 0.70258;
/**
* Feigenbaum constant
*/
public static final double FEIGENBAUM_DELTA = 4.66920160910299067185320382046620161;
/**
* Feigenbaum constant
*/
public static final double FEIGENBAUM_ALFA = 2.50290787509589282228390287321821578;
/**
* Feigenbaum constant
*/
public static final double TWIN_PRIME = 0.66016181584686957392781211001455577;
/**
* Meissel-Mertens constant
*/
public static final double MEISSEL_MERTEENS = 0.26149721284764278375542683860869585;
/**
* Brun's constant for twin primes
*/
public static final double BRAUN_TWIN_PRIME = 1.9021605823;
/**
* Brun's constant for prime quadruplets
*/
public static final double BRAUN_PRIME_QUADR = 0.8705883800;
/**
* de Bruijn-Newman constant
*/
public static final double BRUIJN_NEWMAN = -2.7E-9;
/**
* Catalan's constant
*/
public static final double CATALAN = 0.91596559417721901505460351493238411;
/**
* Landau-Ramanujan constant
*/
public static final double LANDAU_RAMANUJAN = 0.76422365358922066299069873125009232;
/**
* Viswanath's constant
*/
public static final double VISWANATH = 1.13198824;
/**
* Legendre's constant
*/
public static final double LEGENDRE = 1.0;
/**
* Ramanujan-Soldner constant
*/
public static final double RAMANUJAN_SOLDNER = 1.45136923488338105028396848589202744;
/**
* Erdos-Borwein constant
*/
public static final double ERDOS_BORWEIN = 1.60669515241529176378330152319092458;
/**
* Bernstein's constant
*/
public static final double BERNSTEIN = 0.28016949902386913303;
/**
* Gauss-Kuzmin-Wirsing constant
*/
public static final double GAUSS_KUZMIN_WIRSING = 0.30366300289873265859744812190155623;
/**
* Hafner-Sarnak-McCurley constant
*/
public static final double HAFNER_SARNAK_MCCURLEY = 0.35323637185499598454;
/**
* Golomb-Dickman constant
*/
public static final double GOLOMB_DICKMAN = 0.62432998854355087099293638310083724;
/**
* Cahen's constant
*/
public static final double CAHEN = 0.6434105463;
/**
* Laplace limit
*/
public static final double LAPLACE_LIMIT = 0.66274341934918158097474209710925290;
/**
* Alladi-Grinstead constant
*/
public static final double ALLADI_GRINSTEAD = 0.8093940205;
/**
* Lengyel's constant
*/
public static final double LENGYEL = 1.0986858055;
/**
* Levy's constant
*/
public static final double LEVY = 3.27582291872181115978768188245384386;
/**
* Apery's constant
*/
public static final double APERY = 1.20205690315959428539973816151144999;
/**
* Mills' constant
*/
public static final double MILLS = 1.30637788386308069046861449260260571;
/**
* Backhouse's constant
*/
public static final double BACKHOUSE = 1.45607494858268967139959535111654356;
/**
* Porter's constant
*/
public static final double PORTER = 1.4670780794;
/**
* Porter's constant
*/
public static final double LIEB_QUARE_ICE = 1.5396007178;
/**
* Niven's constant
*/
public static final double NIVEN = 1.70521114010536776428855145343450816;
/**
* Sierpiński's constant
*/
public static final double SIERPINSKI = 2.58498175957925321706589358738317116;
/**
* Khinchin's constant
*/
public static final double KHINCHIN = 2.68545200106530644530971483548179569;
/**
* Fransén-Robinson constant
*/
public static final double FRANSEN_ROBINSON = 2.80777024202851936522150118655777293;
/**
* Landau's constant
*/
public static final double LANDAU = 0.5;
/**
* Parabolic constant
*/
public static final double PARABOLIC = 2.29558714939263807403429804918949039;
/**
* Omega constant
*/
public static final double OMEGA = 0.56714329040978387299996866221035555;
/**
* MRB constant
*/
public static final double MRB = 0.187859;
} | tiagogoncalves/MathParser.org-mXparser | STABLE/2.2.0/java/src/org/mariuszgromada/math/mxparser/mathcollection/MathConstants.java | 2,801 | /**
* de Bruijn-Newman constant
*/ | block_comment | nl | /*
* @(#)MathConstants.java 2.1.1-1 2016-01-07
*
* You may use this software under the condition of "Simplified BSD License"
*
* Copyright 2010-2016 MARIUSZ GROMADA. 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.
*
* THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``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 <COPYRIGHT HOLDER> OR
* 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of MARIUSZ GROMADA.
*
* If you have any questions/bugs feel free to contact:
*
* Mariusz Gromada
* [email protected]
* http://mathspace.pl/
* http://mathparser.org/
* http://github.com/mariuszgromada/MathParser.org-mXparser
* http://mariuszgromada.github.io/MathParser.org-mXparser/
* http://mxparser.sourceforge.net/
* http://bitbucket.org/mariuszgromada/mxparser/
* http://mxparser.codeplex.com/
*
* Asked if he believes in one God, a mathematician answered:
* "Yes, up to isomorphism."
*/
package org.mariuszgromada.math.mxparser.mathcollection;
/**
* MathConstants - class representing the most important math constants.
*
* @author <b>Mariusz Gromada</b><br/>
* <a href="mailto:[email protected]">[email protected]</a><br>
* <a href="http://mathspace.pl/" target="_blank">MathSpace.pl</a><br>
* <a href="http://mathparser.org/" target="_blank">MathParser.org - mXparser project page</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
* <a href="http://mariuszgromada.github.io/MathParser.org-mXparser/" target="_blank">mXparser on GitHub pages</a><br>
* <a href="http://mxparser.sourceforge.net/" target="_blank">mXparser on SourceForge/</a><br>
* <a href="http://bitbucket.org/mariuszgromada/mxparser/" target="_blank">mXparser on Bitbucket/</a><br>
* <a href="http://mxparser.codeplex.com/" target="_blank">mXparser on CodePlex/</a><br>
*
* @version 2.1.1-1
*/
public final class MathConstants {
/**
* Pi, Archimedes' constant or Ludolph's number
*/
public static final double PI = 3.14159265358979323846264338327950288;
/**
* Napier's constant, or Euler's number, base of Natural logarithm
*/
public static final double E = 2.71828182845904523536028747135266249;
/**
* Euler-Mascheroni constant
*/
public static final double EULER_MASCHERONI = 0.57721566490153286060651209008240243;
/**
* Golden ratio
*/
public static final double GOLDEN_RATIO = 1.61803398874989484820458683436563811;
/**
* Plastic constant
*/
public static final double PLASTIC = 1.32471795724474602596090885447809734;
/**
* Embree-Trefethen constant
*/
public static final double EMBREE_TREFETHEN = 0.70258;
/**
* Feigenbaum constant
*/
public static final double FEIGENBAUM_DELTA = 4.66920160910299067185320382046620161;
/**
* Feigenbaum constant
*/
public static final double FEIGENBAUM_ALFA = 2.50290787509589282228390287321821578;
/**
* Feigenbaum constant
*/
public static final double TWIN_PRIME = 0.66016181584686957392781211001455577;
/**
* Meissel-Mertens constant
*/
public static final double MEISSEL_MERTEENS = 0.26149721284764278375542683860869585;
/**
* Brun's constant for twin primes
*/
public static final double BRAUN_TWIN_PRIME = 1.9021605823;
/**
* Brun's constant for prime quadruplets
*/
public static final double BRAUN_PRIME_QUADR = 0.8705883800;
/**
* de Bruijn-Newman constant<SUF>*/
public static final double BRUIJN_NEWMAN = -2.7E-9;
/**
* Catalan's constant
*/
public static final double CATALAN = 0.91596559417721901505460351493238411;
/**
* Landau-Ramanujan constant
*/
public static final double LANDAU_RAMANUJAN = 0.76422365358922066299069873125009232;
/**
* Viswanath's constant
*/
public static final double VISWANATH = 1.13198824;
/**
* Legendre's constant
*/
public static final double LEGENDRE = 1.0;
/**
* Ramanujan-Soldner constant
*/
public static final double RAMANUJAN_SOLDNER = 1.45136923488338105028396848589202744;
/**
* Erdos-Borwein constant
*/
public static final double ERDOS_BORWEIN = 1.60669515241529176378330152319092458;
/**
* Bernstein's constant
*/
public static final double BERNSTEIN = 0.28016949902386913303;
/**
* Gauss-Kuzmin-Wirsing constant
*/
public static final double GAUSS_KUZMIN_WIRSING = 0.30366300289873265859744812190155623;
/**
* Hafner-Sarnak-McCurley constant
*/
public static final double HAFNER_SARNAK_MCCURLEY = 0.35323637185499598454;
/**
* Golomb-Dickman constant
*/
public static final double GOLOMB_DICKMAN = 0.62432998854355087099293638310083724;
/**
* Cahen's constant
*/
public static final double CAHEN = 0.6434105463;
/**
* Laplace limit
*/
public static final double LAPLACE_LIMIT = 0.66274341934918158097474209710925290;
/**
* Alladi-Grinstead constant
*/
public static final double ALLADI_GRINSTEAD = 0.8093940205;
/**
* Lengyel's constant
*/
public static final double LENGYEL = 1.0986858055;
/**
* Levy's constant
*/
public static final double LEVY = 3.27582291872181115978768188245384386;
/**
* Apery's constant
*/
public static final double APERY = 1.20205690315959428539973816151144999;
/**
* Mills' constant
*/
public static final double MILLS = 1.30637788386308069046861449260260571;
/**
* Backhouse's constant
*/
public static final double BACKHOUSE = 1.45607494858268967139959535111654356;
/**
* Porter's constant
*/
public static final double PORTER = 1.4670780794;
/**
* Porter's constant
*/
public static final double LIEB_QUARE_ICE = 1.5396007178;
/**
* Niven's constant
*/
public static final double NIVEN = 1.70521114010536776428855145343450816;
/**
* Sierpiński's constant
*/
public static final double SIERPINSKI = 2.58498175957925321706589358738317116;
/**
* Khinchin's constant
*/
public static final double KHINCHIN = 2.68545200106530644530971483548179569;
/**
* Fransén-Robinson constant
*/
public static final double FRANSEN_ROBINSON = 2.80777024202851936522150118655777293;
/**
* Landau's constant
*/
public static final double LANDAU = 0.5;
/**
* Parabolic constant
*/
public static final double PARABOLIC = 2.29558714939263807403429804918949039;
/**
* Omega constant
*/
public static final double OMEGA = 0.56714329040978387299996866221035555;
/**
* MRB constant
*/
public static final double MRB = 0.187859;
} |
90037_1 | package com.fengdu.entity;
import java.io.Serializable;
import java.util.List;
/**
* 部门管理
*
* @author liepngjun
* @email [email protected]
* @date 2017-09-17 23:58:47
*/
public class SysDeptEntity implements Serializable {
private static final long serialVersionUID = 1L;
//部门ID
private Long deptId;
//上级部门ID,一级部门为0
private Long parentId;
//部门名称
private String name;
//上级部门名称
private String parentName;
//排序
private Integer orderNum;
/**
* ztree属性
*/
private Boolean open;
private List<?> list;
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
public Long getDeptId() {
return deptId;
}
/**
* 设置:上级部门ID,一级部门为0
*/
public void setParentId(Long parentId) {
this.parentId = parentId;
}
/**
* 获取:上级部门ID,一级部门为0
*/
public Long getParentId() {
return parentId;
}
/**
* 设置:部门名称
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取:部门名称
*/
public String getName() {
return name;
}
/**
* 设置:排序
*/
public void setOrderNum(Integer orderNum) {
this.orderNum = orderNum;
}
/**
* 获取:排序
*/
public Integer getOrderNum() {
return orderNum;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Boolean getOpen() {
return open;
}
public void setOpen(Boolean open) {
this.open = open;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
| tiankong0310/my-shop | my-shop-common/src/main/java/com/fengdu/entity/SysDeptEntity.java | 593 | /**
* ztree属性
*/ | block_comment | nl | package com.fengdu.entity;
import java.io.Serializable;
import java.util.List;
/**
* 部门管理
*
* @author liepngjun
* @email [email protected]
* @date 2017-09-17 23:58:47
*/
public class SysDeptEntity implements Serializable {
private static final long serialVersionUID = 1L;
//部门ID
private Long deptId;
//上级部门ID,一级部门为0
private Long parentId;
//部门名称
private String name;
//上级部门名称
private String parentName;
//排序
private Integer orderNum;
/**
* ztree属性
<SUF>*/
private Boolean open;
private List<?> list;
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
public Long getDeptId() {
return deptId;
}
/**
* 设置:上级部门ID,一级部门为0
*/
public void setParentId(Long parentId) {
this.parentId = parentId;
}
/**
* 获取:上级部门ID,一级部门为0
*/
public Long getParentId() {
return parentId;
}
/**
* 设置:部门名称
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取:部门名称
*/
public String getName() {
return name;
}
/**
* 设置:排序
*/
public void setOrderNum(Integer orderNum) {
this.orderNum = orderNum;
}
/**
* 获取:排序
*/
public Integer getOrderNum() {
return orderNum;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Boolean getOpen() {
return open;
}
public void setOpen(Boolean open) {
this.open = open;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
|
120079_2 | //Tibo Vanheule
package timetable.about;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import timetable.config.Config;
import java.util.Properties;
/**
* Class to display information about creator and program
*
* @author Tibo Vanheule
*/
public class AboutController extends Application {
@FXML
private Label text;
private Stage stage;
private Properties properties;
/**
* get stage to use later
*/
public void setStageAndSetupListeners(Stage stage) {
//krijgen van de stage
this.stage = stage;
}
/**
* set the text, read from the properties
*/
public void initialize() {
Config config = new Config();
this.properties = config.getproperties();
//bewust alle tekst in 1 veld gestoken
//kleinere fxml en tekst staat dan ook altijd mooi onder elkaar, dankzij de new-line
text.setText("Version: " + properties.getProperty("program.version") +
"\nCopyright: " + properties.getProperty("programmer.name") +
"\nEmail: " + properties.getProperty("programmer.email") +
"\nLayout (Collorpallet) based on: \n" + properties.getProperty("layout.basedOn") +
"\nWeather icons from:\n" + properties.getProperty("layout.weather.icons") +
"\nDocumentation,manual and a mysql-version can be found here: " +
"\n" + properties.getProperty("programmer.site") + "/artifacts/"
);
}
/**
* Close the stage
*/
public void close() {
stage.close();
}
/**
* Show the manual in browser
*/
public void manual() {
getHostServices().showDocument("http://www.tibovanheule.space/artifacts/manual.pdf");
}
/**
* Opens the javadoc in browser
*/
public void javadoc() {
getHostServices().showDocument("http://www.tibovanheule.space/artifacts/javadoc");
}
/**
* opens github project in browser
*/
public void github() {
getHostServices().showDocument(properties.getProperty("program.github"));
}
/**
* Just so we can extend Application and use it in other methods
*/
@Override
public void start(Stage primaryStage) {
}
} | tibovanheule/Lessenrooster | Project/src/timetable/about/AboutController.java | 662 | //krijgen van de stage | line_comment | nl | //Tibo Vanheule
package timetable.about;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import timetable.config.Config;
import java.util.Properties;
/**
* Class to display information about creator and program
*
* @author Tibo Vanheule
*/
public class AboutController extends Application {
@FXML
private Label text;
private Stage stage;
private Properties properties;
/**
* get stage to use later
*/
public void setStageAndSetupListeners(Stage stage) {
//krijgen van<SUF>
this.stage = stage;
}
/**
* set the text, read from the properties
*/
public void initialize() {
Config config = new Config();
this.properties = config.getproperties();
//bewust alle tekst in 1 veld gestoken
//kleinere fxml en tekst staat dan ook altijd mooi onder elkaar, dankzij de new-line
text.setText("Version: " + properties.getProperty("program.version") +
"\nCopyright: " + properties.getProperty("programmer.name") +
"\nEmail: " + properties.getProperty("programmer.email") +
"\nLayout (Collorpallet) based on: \n" + properties.getProperty("layout.basedOn") +
"\nWeather icons from:\n" + properties.getProperty("layout.weather.icons") +
"\nDocumentation,manual and a mysql-version can be found here: " +
"\n" + properties.getProperty("programmer.site") + "/artifacts/"
);
}
/**
* Close the stage
*/
public void close() {
stage.close();
}
/**
* Show the manual in browser
*/
public void manual() {
getHostServices().showDocument("http://www.tibovanheule.space/artifacts/manual.pdf");
}
/**
* Opens the javadoc in browser
*/
public void javadoc() {
getHostServices().showDocument("http://www.tibovanheule.space/artifacts/javadoc");
}
/**
* opens github project in browser
*/
public void github() {
getHostServices().showDocument(properties.getProperty("program.github"));
}
/**
* Just so we can extend Application and use it in other methods
*/
@Override
public void start(Stage primaryStage) {
}
} |
150480_5 | package ti.map;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.clustering.ClusterManager;
import com.google.maps.android.clustering.view.DefaultClusterRenderer;
import java.util.HashMap;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiBlob;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import org.appcelerator.titanium.TiPoint;
import org.appcelerator.titanium.view.TiDrawableReference;
public class TiClusterRenderer extends DefaultClusterRenderer<TiMarker>
{
private static final String TAG = "ClusterRender";
private static final String defaultIconImageHeight = "40dip"; //The height of the default marker icon
private static final String defaultIconImageWidth = "36dip"; //The width of the default marker icon
private int iconImageHeight = 0;
private int iconImageWidth = 0;
public TiClusterRenderer(Context context, GoogleMap map, ClusterManager<TiMarker> clusterManager)
{
super(context, map, clusterManager);
}
@Override
protected void onBeforeClusterItemRendered(TiMarker clusterItem, MarkerOptions markerOptions)
{
AnnotationProxy anno = clusterItem.getProxy();
if (anno != null) {
if (anno.hasProperty(TiC.PROPERTY_IMAGE)) {
handleImage(anno, markerOptions, anno.getProperty(TiC.PROPERTY_IMAGE));
}
if (anno.hasProperty(MapModule.PROPERTY_CENTER_OFFSET)) {
HashMap centerOffsetProperty = (HashMap) anno.getProperty(MapModule.PROPERTY_CENTER_OFFSET);
TiPoint centerOffset = new TiPoint(centerOffsetProperty, 0.0, 0.0);
float offsetX = 0.5f - ((float) centerOffset.getX().getValue() / (float) iconImageWidth);
float offsetY = 0.5f - ((float) centerOffset.getY().getValue() / (float) iconImageHeight);
markerOptions.anchor(offsetX, offsetY);
}
}
}
private void handleImage(AnnotationProxy anno, MarkerOptions markerOptions, Object image)
{
// Image path
if (image instanceof String) {
TiDrawableReference imageref =
TiDrawableReference.fromUrl(anno, (String) anno.getProperty(TiC.PROPERTY_IMAGE));
Bitmap bitmap = imageref.getBitmap();
if (bitmap != null) {
try {
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap));
setIconImageDimensions(bitmap.getWidth(), bitmap.getHeight());
} catch (Exception e) {
}
return;
}
}
// Image blob
if (image instanceof TiBlob) {
Bitmap bitmap = ((TiBlob) image).getImage();
if (bitmap != null) {
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap));
setIconImageDimensions(bitmap.getWidth(), bitmap.getHeight());
return;
}
}
Log.w(TAG, "Unable to get the image from the path: " + image);
setIconImageDimensions(-1, -1);
}
@Override
protected void onClusterItemRendered(TiMarker clusterItem, Marker marker)
{
super.onClusterItemRendered(clusterItem, marker);
clusterItem.setMarker(marker);
}
protected void onClusterItemUpdated(TiMarker item, Marker marker)
{
boolean changed = false;
// Update marker text if the item text changed - same logic as adding marker in CreateMarkerTask.perform()
if (item.getTitle() != null && item.getSnippet() != null) {
if (!item.getTitle().equals(marker.getTitle())) {
marker.setTitle(item.getTitle());
changed = true;
}
if (!item.getSnippet().equals(marker.getSnippet())) {
marker.setSnippet(item.getSnippet());
changed = true;
}
} else if (item.getSnippet() != null && !item.getSnippet().equals(marker.getTitle())) {
marker.setTitle(item.getSnippet());
changed = true;
} else if (item.getTitle() != null && !item.getTitle().equals(marker.getTitle())) {
marker.setTitle(item.getTitle());
changed = true;
}
// Update marker position if the item changed position
if (!marker.getPosition().equals(item.getPosition())) {
if (item.getPosition() != null) {
marker.setPosition(item.getPosition());
}
changed = true;
}
if (changed && marker.isInfoWindowShown()) {
// Force a refresh of marker info window contents
marker.showInfoWindow();
}
}
public void setIconImageDimensions(int w, int h)
{
if (w >= 0 && h >= 0) {
iconImageWidth = w;
iconImageHeight = h;
} else { // default maker icon
TiDimension widthDimension = new TiDimension(defaultIconImageWidth, TiDimension.TYPE_UNDEFINED);
TiDimension heightDimension = new TiDimension(defaultIconImageHeight, TiDimension.TYPE_UNDEFINED);
View view = TiApplication.getAppCurrentActivity().getWindow().getDecorView();
iconImageWidth = widthDimension.getAsPixels(view);
iconImageHeight = heightDimension.getAsPixels(view);
}
}
}
| tidev/ti.map | android/src/ti/map/TiClusterRenderer.java | 1,576 | // default maker icon | line_comment | nl | package ti.map;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.maps.android.clustering.ClusterManager;
import com.google.maps.android.clustering.view.DefaultClusterRenderer;
import java.util.HashMap;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiBlob;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import org.appcelerator.titanium.TiPoint;
import org.appcelerator.titanium.view.TiDrawableReference;
public class TiClusterRenderer extends DefaultClusterRenderer<TiMarker>
{
private static final String TAG = "ClusterRender";
private static final String defaultIconImageHeight = "40dip"; //The height of the default marker icon
private static final String defaultIconImageWidth = "36dip"; //The width of the default marker icon
private int iconImageHeight = 0;
private int iconImageWidth = 0;
public TiClusterRenderer(Context context, GoogleMap map, ClusterManager<TiMarker> clusterManager)
{
super(context, map, clusterManager);
}
@Override
protected void onBeforeClusterItemRendered(TiMarker clusterItem, MarkerOptions markerOptions)
{
AnnotationProxy anno = clusterItem.getProxy();
if (anno != null) {
if (anno.hasProperty(TiC.PROPERTY_IMAGE)) {
handleImage(anno, markerOptions, anno.getProperty(TiC.PROPERTY_IMAGE));
}
if (anno.hasProperty(MapModule.PROPERTY_CENTER_OFFSET)) {
HashMap centerOffsetProperty = (HashMap) anno.getProperty(MapModule.PROPERTY_CENTER_OFFSET);
TiPoint centerOffset = new TiPoint(centerOffsetProperty, 0.0, 0.0);
float offsetX = 0.5f - ((float) centerOffset.getX().getValue() / (float) iconImageWidth);
float offsetY = 0.5f - ((float) centerOffset.getY().getValue() / (float) iconImageHeight);
markerOptions.anchor(offsetX, offsetY);
}
}
}
private void handleImage(AnnotationProxy anno, MarkerOptions markerOptions, Object image)
{
// Image path
if (image instanceof String) {
TiDrawableReference imageref =
TiDrawableReference.fromUrl(anno, (String) anno.getProperty(TiC.PROPERTY_IMAGE));
Bitmap bitmap = imageref.getBitmap();
if (bitmap != null) {
try {
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap));
setIconImageDimensions(bitmap.getWidth(), bitmap.getHeight());
} catch (Exception e) {
}
return;
}
}
// Image blob
if (image instanceof TiBlob) {
Bitmap bitmap = ((TiBlob) image).getImage();
if (bitmap != null) {
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap));
setIconImageDimensions(bitmap.getWidth(), bitmap.getHeight());
return;
}
}
Log.w(TAG, "Unable to get the image from the path: " + image);
setIconImageDimensions(-1, -1);
}
@Override
protected void onClusterItemRendered(TiMarker clusterItem, Marker marker)
{
super.onClusterItemRendered(clusterItem, marker);
clusterItem.setMarker(marker);
}
protected void onClusterItemUpdated(TiMarker item, Marker marker)
{
boolean changed = false;
// Update marker text if the item text changed - same logic as adding marker in CreateMarkerTask.perform()
if (item.getTitle() != null && item.getSnippet() != null) {
if (!item.getTitle().equals(marker.getTitle())) {
marker.setTitle(item.getTitle());
changed = true;
}
if (!item.getSnippet().equals(marker.getSnippet())) {
marker.setSnippet(item.getSnippet());
changed = true;
}
} else if (item.getSnippet() != null && !item.getSnippet().equals(marker.getTitle())) {
marker.setTitle(item.getSnippet());
changed = true;
} else if (item.getTitle() != null && !item.getTitle().equals(marker.getTitle())) {
marker.setTitle(item.getTitle());
changed = true;
}
// Update marker position if the item changed position
if (!marker.getPosition().equals(item.getPosition())) {
if (item.getPosition() != null) {
marker.setPosition(item.getPosition());
}
changed = true;
}
if (changed && marker.isInfoWindowShown()) {
// Force a refresh of marker info window contents
marker.showInfoWindow();
}
}
public void setIconImageDimensions(int w, int h)
{
if (w >= 0 && h >= 0) {
iconImageWidth = w;
iconImageHeight = h;
} else { // default maker<SUF>
TiDimension widthDimension = new TiDimension(defaultIconImageWidth, TiDimension.TYPE_UNDEFINED);
TiDimension heightDimension = new TiDimension(defaultIconImageHeight, TiDimension.TYPE_UNDEFINED);
View view = TiApplication.getAppCurrentActivity().getWindow().getDecorView();
iconImageWidth = widthDimension.getAsPixels(view);
iconImageHeight = heightDimension.getAsPixels(view);
}
}
}
|
28508_12 | package com.tontine.app.service;
import com.tontine.app.domain.ChiTietHui;
import com.tontine.app.domain.Hui;
import com.tontine.app.repository.ChiTietHuiRepository;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service Implementation for managing {@link ChiTietHui}.
*/
@Service
@Transactional
public class ChiTietHuiService {
private final Logger log = LoggerFactory.getLogger(ChiTietHuiService.class);
private final ChiTietHuiRepository chiTietHuiRepository;
private final HuiService huiService;
// private final CacheManager cacheManager;
public ChiTietHuiService(ChiTietHuiRepository chiTietHuiRepository, HuiService huiService, CacheManager cacheManager) {
this.chiTietHuiRepository = chiTietHuiRepository;
this.huiService = huiService;
// this.cacheManager = cacheManager;
}
/**
* Save a chiTietHui.
*
* @param chiTietHui the entity to save.
* @return the persisted entity.
*/
public ChiTietHui save(ChiTietHui chiTietHui) {
log.debug("Request to save ChiTietHui : {}", chiTietHui);
chiTietHui.setTienHot(HuiHelper.calculateTienHotHui(chiTietHui));
return chiTietHuiRepository.save(chiTietHui);
}
/**
* Update a chiTietHui.
*
* @param chiTietHui the entity to save.
* @return the persisted entity.
*/
public synchronized ChiTietHui update(final ChiTietHui chiTietHui) {
log.debug("Request to update ChiTietHui : {}", chiTietHui);
Optional<ChiTietHui> chiTietHuiDb = chiTietHuiRepository.findById(chiTietHui.getId());
Optional<Hui> hui = huiService.findOne(chiTietHui.getHui().getId());
if (chiTietHuiDb.isPresent() && hui.isPresent() && chiTietHui.getThamKeu() != null) {
long tongSoKiHienTai = hui.get().getChiTietHuis().stream().filter(e -> e.getKy() != null).count();
// Tham keu = 0 => clear thong tin hot hui
List<ChiTietHui> listKiGreater;
if (chiTietHui.getThamKeu() < 0) {
// Re-calculate ki number
listKiGreater =
chiTietHuiRepository.findChiTietHuisByKyGreaterThanAndHuiId(chiTietHui.getKy(), chiTietHui.getHui().getId());
listKiGreater.forEach(cth -> cth.setKy(cth.getKy() - 1));
chiTietHuiRepository.saveAll(listKiGreater);
ChiTietHui chiTietHuiDbUpdated = chiTietHuiDb.get();
chiTietHuiDbUpdated.setKy(null);
chiTietHuiDbUpdated.ngayKhui(null);
chiTietHuiDbUpdated.setThamKeu(null);
chiTietHuiDbUpdated.setTienHot(null);
return chiTietHuiRepository.save(chiTietHuiDbUpdated);
}
if (chiTietHuiDb.get().getKy() == null) {
chiTietHui.setKy((int) tongSoKiHienTai + 1);
}
chiTietHui.setTienHot(HuiHelper.calculateTienHotHui(chiTietHui));
}
return chiTietHuiRepository.save(chiTietHui);
}
/**
* Partially update a chiTietHui.
*
* @param chiTietHui the entity to update partially.
* @return the persisted entity.
*/
public Optional<ChiTietHui> partialUpdate(ChiTietHui chiTietHui) {
log.debug("Request to partially update ChiTietHui : {}", chiTietHui);
return chiTietHuiRepository
.findById(chiTietHui.getId())
.map(existingChiTietHui -> {
if (chiTietHui.getThamKeu() != null) {
existingChiTietHui.setThamKeu(chiTietHui.getThamKeu());
}
if (chiTietHui.getNgayKhui() != null) {
existingChiTietHui.setNgayKhui(chiTietHui.getNgayKhui());
}
if (chiTietHui.getKy() != null) {
existingChiTietHui.setKy(chiTietHui.getKy());
}
if (chiTietHui.getTienHot() != null) {
existingChiTietHui.setTienHot(chiTietHui.getTienHot());
}
if (chiTietHui.getNickNameHuiVien() != null) {
existingChiTietHui.setNickNameHuiVien(chiTietHui.getNickNameHuiVien());
}
return existingChiTietHui;
})
.map(chiTietHuiRepository::save);
}
/**
* Get all the chiTietHuis.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
@Transactional(readOnly = true)
public Page<ChiTietHui> findAll(Pageable pageable) {
log.debug("Request to get all ChiTietHuis");
return chiTietHuiRepository.findAll(pageable);
}
/**
* Get one chiTietHui by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Transactional(readOnly = true)
public Optional<ChiTietHui> findOne(Long id) {
log.debug("Request to get ChiTietHui : {}", id);
// ChiTietHui cacheChiTietHui = Objects
// .requireNonNull(cacheManager.getCache(chiTietHuiRepository.CHI_TIET_HUI_BY_ID))
// .get(id, ChiTietHui.class);
// if (cacheChiTietHui != null) {
// log.debug("Cache chi tiet hui: {}", cacheChiTietHui);
// return Optional.of(cacheChiTietHui);
// }
return chiTietHuiRepository.findById(id);
}
/**
* Delete the chiTietHui by id.
*
* @param id the id of the entity.
*/
public void delete(Long id) {
log.debug("Request to delete ChiTietHui : {}", id);
chiTietHuiRepository.deleteById(id);
}
}
| tienduoc/tontine | src/main/java/com/tontine/app/service/ChiTietHuiService.java | 2,040 | // log.debug("Cache chi tiet hui: {}", cacheChiTietHui); | line_comment | nl | package com.tontine.app.service;
import com.tontine.app.domain.ChiTietHui;
import com.tontine.app.domain.Hui;
import com.tontine.app.repository.ChiTietHuiRepository;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service Implementation for managing {@link ChiTietHui}.
*/
@Service
@Transactional
public class ChiTietHuiService {
private final Logger log = LoggerFactory.getLogger(ChiTietHuiService.class);
private final ChiTietHuiRepository chiTietHuiRepository;
private final HuiService huiService;
// private final CacheManager cacheManager;
public ChiTietHuiService(ChiTietHuiRepository chiTietHuiRepository, HuiService huiService, CacheManager cacheManager) {
this.chiTietHuiRepository = chiTietHuiRepository;
this.huiService = huiService;
// this.cacheManager = cacheManager;
}
/**
* Save a chiTietHui.
*
* @param chiTietHui the entity to save.
* @return the persisted entity.
*/
public ChiTietHui save(ChiTietHui chiTietHui) {
log.debug("Request to save ChiTietHui : {}", chiTietHui);
chiTietHui.setTienHot(HuiHelper.calculateTienHotHui(chiTietHui));
return chiTietHuiRepository.save(chiTietHui);
}
/**
* Update a chiTietHui.
*
* @param chiTietHui the entity to save.
* @return the persisted entity.
*/
public synchronized ChiTietHui update(final ChiTietHui chiTietHui) {
log.debug("Request to update ChiTietHui : {}", chiTietHui);
Optional<ChiTietHui> chiTietHuiDb = chiTietHuiRepository.findById(chiTietHui.getId());
Optional<Hui> hui = huiService.findOne(chiTietHui.getHui().getId());
if (chiTietHuiDb.isPresent() && hui.isPresent() && chiTietHui.getThamKeu() != null) {
long tongSoKiHienTai = hui.get().getChiTietHuis().stream().filter(e -> e.getKy() != null).count();
// Tham keu = 0 => clear thong tin hot hui
List<ChiTietHui> listKiGreater;
if (chiTietHui.getThamKeu() < 0) {
// Re-calculate ki number
listKiGreater =
chiTietHuiRepository.findChiTietHuisByKyGreaterThanAndHuiId(chiTietHui.getKy(), chiTietHui.getHui().getId());
listKiGreater.forEach(cth -> cth.setKy(cth.getKy() - 1));
chiTietHuiRepository.saveAll(listKiGreater);
ChiTietHui chiTietHuiDbUpdated = chiTietHuiDb.get();
chiTietHuiDbUpdated.setKy(null);
chiTietHuiDbUpdated.ngayKhui(null);
chiTietHuiDbUpdated.setThamKeu(null);
chiTietHuiDbUpdated.setTienHot(null);
return chiTietHuiRepository.save(chiTietHuiDbUpdated);
}
if (chiTietHuiDb.get().getKy() == null) {
chiTietHui.setKy((int) tongSoKiHienTai + 1);
}
chiTietHui.setTienHot(HuiHelper.calculateTienHotHui(chiTietHui));
}
return chiTietHuiRepository.save(chiTietHui);
}
/**
* Partially update a chiTietHui.
*
* @param chiTietHui the entity to update partially.
* @return the persisted entity.
*/
public Optional<ChiTietHui> partialUpdate(ChiTietHui chiTietHui) {
log.debug("Request to partially update ChiTietHui : {}", chiTietHui);
return chiTietHuiRepository
.findById(chiTietHui.getId())
.map(existingChiTietHui -> {
if (chiTietHui.getThamKeu() != null) {
existingChiTietHui.setThamKeu(chiTietHui.getThamKeu());
}
if (chiTietHui.getNgayKhui() != null) {
existingChiTietHui.setNgayKhui(chiTietHui.getNgayKhui());
}
if (chiTietHui.getKy() != null) {
existingChiTietHui.setKy(chiTietHui.getKy());
}
if (chiTietHui.getTienHot() != null) {
existingChiTietHui.setTienHot(chiTietHui.getTienHot());
}
if (chiTietHui.getNickNameHuiVien() != null) {
existingChiTietHui.setNickNameHuiVien(chiTietHui.getNickNameHuiVien());
}
return existingChiTietHui;
})
.map(chiTietHuiRepository::save);
}
/**
* Get all the chiTietHuis.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
@Transactional(readOnly = true)
public Page<ChiTietHui> findAll(Pageable pageable) {
log.debug("Request to get all ChiTietHuis");
return chiTietHuiRepository.findAll(pageable);
}
/**
* Get one chiTietHui by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Transactional(readOnly = true)
public Optional<ChiTietHui> findOne(Long id) {
log.debug("Request to get ChiTietHui : {}", id);
// ChiTietHui cacheChiTietHui = Objects
// .requireNonNull(cacheManager.getCache(chiTietHuiRepository.CHI_TIET_HUI_BY_ID))
// .get(id, ChiTietHui.class);
// if (cacheChiTietHui != null) {
// log.debug("Cache chi<SUF>
// return Optional.of(cacheChiTietHui);
// }
return chiTietHuiRepository.findById(id);
}
/**
* Delete the chiTietHui by id.
*
* @param id the id of the entity.
*/
public void delete(Long id) {
log.debug("Request to delete ChiTietHui : {}", id);
chiTietHuiRepository.deleteById(id);
}
}
|
69081_0 | package nl.hu.dp.ovchip;
import nl.hu.dp.ovchip.domein.Adres;
import nl.hu.dp.ovchip.domein.OVChipkaart;
import nl.hu.dp.ovchip.domein.Product;
import nl.hu.dp.ovchip.domein.Reiziger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import java.sql.SQLException;
import java.util.List;
/**
* Testklasse - deze klasse test alle andere klassen in deze package.
*
* System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions).
*
* @author [email protected]
*/
public class Main {
// Creëer een factory voor Hibernate sessions.
private static final SessionFactory factory;
static {
try {
// Create a Hibernate session factory
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
/**
* Retouneer een Hibernate session.
*
* @return Hibernate session
* @throws HibernateException
*/
private static Session getSession() throws HibernateException {
return factory.openSession();
}
public static void main(String[] args) throws SQLException {
testFetchAll();
}
/**
* P6. Haal alle (geannoteerde) entiteiten uit de database.
*/
private static void testFetchAll() {
Session session = getSession();
try {
Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
Query query = session.createQuery("from " + entityType.getName());
System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:");
for (Object o : query.list()) {
System.out.println(" " + o);
}
System.out.println();
}
} finally {
session.close();
}
}
}
| tijmenjoppe/DataPersistency-student | practicum/OV-chipkaart_Hibernate/src/nl/hu/dp/ovchip/Main.java | 662 | /**
* Testklasse - deze klasse test alle andere klassen in deze package.
*
* System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions).
*
* @author [email protected]
*/ | block_comment | nl | package nl.hu.dp.ovchip;
import nl.hu.dp.ovchip.domein.Adres;
import nl.hu.dp.ovchip.domein.OVChipkaart;
import nl.hu.dp.ovchip.domein.Product;
import nl.hu.dp.ovchip.domein.Reiziger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import java.sql.SQLException;
import java.util.List;
/**
* Testklasse - deze<SUF>*/
public class Main {
// Creëer een factory voor Hibernate sessions.
private static final SessionFactory factory;
static {
try {
// Create a Hibernate session factory
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
/**
* Retouneer een Hibernate session.
*
* @return Hibernate session
* @throws HibernateException
*/
private static Session getSession() throws HibernateException {
return factory.openSession();
}
public static void main(String[] args) throws SQLException {
testFetchAll();
}
/**
* P6. Haal alle (geannoteerde) entiteiten uit de database.
*/
private static void testFetchAll() {
Session session = getSession();
try {
Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
Query query = session.createQuery("from " + entityType.getName());
System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:");
for (Object o : query.list()) {
System.out.println(" " + o);
}
System.out.println();
}
} finally {
session.close();
}
}
}
|
106314_4 | package com.oracle.javaee7.samples.batch.simple;
import javax.batch.operations.JobOperator;
import javax.batch.runtime.BatchRuntime;
import javax.batch.runtime.JobExecution;
import javax.enterprise.context.Dependent;
import javax.inject.Named;
import java.util.Properties;
@Named @Dependent
public class JobReceiverBean
{
// private static final String JOBNAME = "PayrollJob";
//
// public void startbatch(String movements, String insertDate)
// {
// if (movements == null || insertDate == null)
// {
// return;
// }
//
// ////////////////////// TODO FIX ////////////////////////////////////
// //movements="/home/tijs/Downloads/verpl_systeem/verplaatsingen_20110209_small.xml";
// //movements="/home/tijs/Dropbox/S6Project/PTS ESD/SUMO-OSM files/generated files Tijs/movement_vehicle_gen_t0.xml";
// Properties props = new Properties();
// props.setProperty("inputfile", movements);
// props.setProperty("basedate", insertDate);
// //insertDate
// ////////////////////////////////////////////////////////////////////
// try
// {
// JobOperator jobOperator = BatchRuntime.getJobOperator();
//
// for (String job : jobOperator.getJobNames())
// {
// System.out.println("EXISTING JOB: " + job);
// }
//
// System.out.println("Starting batch via servlet");
// long executionID = jobOperator.start(JOBNAME, props);
//
// Thread.sleep(300);
//
// System.out.println("Job with ID " + executionID + " started");
// JobExecution jobExec = jobOperator.getJobExecution(executionID);
// String status = jobExec.getBatchStatus().toString();
// System.out.println("Job status: " + status);
// }
// catch (Exception ex)
// {
// ex.printStackTrace();
// }
// }
}
| tijsmaas/ROAD | MovementMapper/src/main/java/com/oracle/javaee7/samples/batch/simple/JobReceiverBean.java | 537 | // //movements="/home/tijs/Dropbox/S6Project/PTS ESD/SUMO-OSM files/generated files Tijs/movement_vehicle_gen_t0.xml"; | line_comment | nl | package com.oracle.javaee7.samples.batch.simple;
import javax.batch.operations.JobOperator;
import javax.batch.runtime.BatchRuntime;
import javax.batch.runtime.JobExecution;
import javax.enterprise.context.Dependent;
import javax.inject.Named;
import java.util.Properties;
@Named @Dependent
public class JobReceiverBean
{
// private static final String JOBNAME = "PayrollJob";
//
// public void startbatch(String movements, String insertDate)
// {
// if (movements == null || insertDate == null)
// {
// return;
// }
//
// ////////////////////// TODO FIX ////////////////////////////////////
// //movements="/home/tijs/Downloads/verpl_systeem/verplaatsingen_20110209_small.xml";
// //movements="/home/tijs/Dropbox/S6Project/PTS ESD/SUMO-OSM<SUF>
// Properties props = new Properties();
// props.setProperty("inputfile", movements);
// props.setProperty("basedate", insertDate);
// //insertDate
// ////////////////////////////////////////////////////////////////////
// try
// {
// JobOperator jobOperator = BatchRuntime.getJobOperator();
//
// for (String job : jobOperator.getJobNames())
// {
// System.out.println("EXISTING JOB: " + job);
// }
//
// System.out.println("Starting batch via servlet");
// long executionID = jobOperator.start(JOBNAME, props);
//
// Thread.sleep(300);
//
// System.out.println("Job with ID " + executionID + " started");
// JobExecution jobExec = jobOperator.getJobExecution(executionID);
// String status = jobExec.getBatchStatus().toString();
// System.out.println("Job status: " + status);
// }
// catch (Exception ex)
// {
// ex.printStackTrace();
// }
// }
}
|
40846_21 | /*
* regain - A file search engine providing plenty of formats
* Copyright (C) 2004 Til Schneider
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: Til Schneider, [email protected]
*/
package net.sf.regain.crawler.config;
import java.util.Properties;
/**
* Stellt alle zu konfigurierenden Einstellungen hardcodiert zur Verfügung.
*
* @author Til Schneider, www.murfman.de
*/
public class DummyCrawlerConfig implements CrawlerConfig {
/**
* Returns the flag for enabling/disabling the content-preview
*
* @return boolean true if content preview is enabled and the whole content should be
* stored in the index
*/
@Override
public boolean getStoreContentForPreview(){
return true;
}
/**
* Gibt den Host-Namen des Proxy-Servers zur�ck. Wenn kein Host konfiguriert
* wurde, wird <CODE>null</CODE> zur�ckgegeben.
*
* @return Der Host-Namen des Proxy-Servers.
*/
@Override
public String getProxyHost() {
return "idatmpsrv";
}
/**
* Returns the maximum count of equal occurences of path-parts in an URI.
*
* @return MaxCycleCount
*/
@Override
public int getMaxCycleCount() {
return -1;
}
/**
* Gibt den Port des Proxy-Servers zur�ck. Wenn kein Port konfiguriert wurde,
* wird <CODE>null</CODE> zur�ckgegeben.
*
* @return Der Port des Proxy-Servers.
*/
@Override
public String getProxyPort() {
return "3128";
}
/**
* Gibt den Benutzernamen f�r die Anmeldung beim Proxy-Server zur�ck. Wenn
* kein Benutzernamen konfiguriert wurde, wird <CODE>null</CODE> zur�ckgegeben.
*
* @return Der Benutzernamen f�r die Anmeldung beim Proxy-Server.
*/
@Override
public String getProxyUser() {
return null;
}
/**
* Gibt das Passwort f�r die Anmeldung beim Proxy-Server zur�ck. Wenn kein
* Passwort konfiguriert wurde, wird <CODE>null</CODE> zur�ckgegeben.
*
* @return Das Passwort f�r die Anmeldung beim Proxy-Server.
*/
@Override
public String getProxyPassword() {
return null;
}
// overridden
@Override
public String getUserAgent() {
return null;
}
/**
* Gibt den Timeout f�r HTTP-Downloads zur�ck. Dieser Wert bestimmt die
* maximale Zeit in Sekunden, die ein HTTP-Download insgesamt dauern darf.
*
* @return Den Timeout f�r HTTP-Downloads
*/
@Override
public int getHttpTimeoutSecs() {
return 180;
}
/**
* Gibt zur�ck, ob URLs geladen werden sollen, die weder durchsucht noch
* indiziert werden.
*
* @return Ob URLs geladen werden sollen, die weder durchsucht noch indiziert
* werden.
*/
@Override
public boolean getLoadUnparsedUrls() {
return false;
}
/**
* Gibt zur�ck, ob ein Suchindex erstellt werden soll.
*
* @return Ob ein Suchindex erstellt werden soll.
*/
@Override
public boolean getBuildIndex() {
return true;
}
/**
* Gibt das Verzeichnis zur�ck, in dem der stehen soll.
*
* @return Das Verzeichnis, in dem der Suchindex stehen soll.
*/
@Override
public String getIndexDir() {
return "c:\\Temp\\searchIndex";
}
/**
* Gibt den zu verwendenden Analyzer-Typ zur�ck.
*
* @return en zu verwendenden Analyzer-Typ
*/
@Override
public String getAnalyzerType() {
return "german";
}
// overridden
public int getMaxFieldLength() {
return -1;
}
/**
* Gibt alle Worte zur�ck, die nicht indiziert werden sollen.
*
* @return Alle Worte, die nicht indiziert werden sollen.
*/
public String[] getStopWordList() {
return null;
}
/**
* Gibt alle Worte zur�ck, die bei der Indizierung nicht vom Analyzer
* ver�ndert werden sollen.
*
* @return Alle Worte, die bei der Indizierung nicht vom Analyzer
* ver�ndert werden sollen.
*/
public String[] getExclusionList() {
return null;
}
/**
* Gibt zur�ck, ob Analyse-Deteien geschrieben werden sollen.
* <p>
* Diese Dateien helfen, die Qualit�t der Index-Erstellung zu Prüfen und
* werden in einem Unterverzeichnis im Index-Verzeichnis angelegt.
*
* @return Ob Analyse-Deteien geschrieben werden sollen.
*/
public boolean getWriteAnalysisFiles() {
return true;
}
/**
* Returns the interval between two breakpoint in minutes. If set to 0, no
* breakpoints will be created.
*
* @return the interval between two breakpoint in minutes.
*/
public int getBreakpointInterval() {
return 10;
}
/**
* Gibt den maximalen Prozentsatz von gescheiterten Dokumenten zur�ck. (0..1)
* <p>
* Ist das Verh�lnis von gescheiterten Dokumenten zur Gesamtzahl von
* Dokumenten gr��er als dieser Prozentsatz, so wird der Index verworfen.
* <p>
* Gescheiterte Dokumente sind Dokumente die es entweder nicht gibt (Deadlink)
* oder die nicht ausgelesen werden konnten.
*
* @return Den maximalen Prozentsatz von gescheiterten Dokumenten zur�ck.
*/
public double getMaxFailedDocuments() {
return 0.1;
}
/**
* Gibt den Namen der Kontrolldatei f�r erfolgreiche Indexerstellung zur�ck.
* <p>
* Diese Datei wird erzeugt, wenn der Index erstellt wurde, ohne dass
* fatale Fehler aufgetreten sind.
* <p>
* Wenn keine Kontrolldatei erzeugt werden soll, dann wird <code>null</code>
* zur�ckgegeben.
*
* @return Der Name der Kontrolldatei f�r erfolgreiche Indexerstellung
*/
public String getFinishedWithoutFatalsFileName() {
return null;
}
/**
* Gibt den Namen der Kontrolldatei f�r fehlerhafte Indexerstellung zur�ck.
* <p>
* Diese Datei wird erzeugt, wenn der Index erstellt wurde, wobei
* fatale Fehler aufgetreten sind.
* <p>
* Wenn keine Kontrolldatei erzeugt werden soll, dann wird <code>null</code>
* zur�ckgegeben.
*
* @return Der Name der Kontrolldatei f�r fehlerhafte Indexerstellung
*/
public String getFinishedWithFatalsFileName() {
return null;
}
/**
* Gibt die StartUrls zur�ck, bei denen der Crawler-Proze� beginnen soll.
*
* @return Die StartUrls.
*/
public StartUrl[] getStartUrls() {
return new StartUrl[] {
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/Home/", true, true),
/*
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,2098,0-15-X,00.html", true, true),
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,1651,0-16-X,00.html", true, true),
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,1651,0-17-X,00.html", true, true),
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,1651,0-18-X,00.html", true, true),
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,1651,0-19-X,00.html", true, true),
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,1651,0-173-X,00.html", true, true)
*/
};
}
/**
* Gibt die UrlPattern zur�ck, die der HTML-Parser nutzen soll, um URLs zu
* identifizieren.
*
* @return Die UrlPattern f�r den HTML-Parser.
*/
public UrlPattern[] getHtmlParserUrlPatterns() {
return new UrlPattern[] {
new UrlPattern("=\"([^\"]*\\.html)\"", 1, true, true),
new UrlPattern("=\"([^\"]*\\.(pdf|xls|doc|rtf|ppt))\"", 1, false, true),
new UrlPattern("=\"([^\"]*\\.(js|css|jpg|gif|png))\"", 1, false, false)
};
}
/**
* Gets the black list.
* <p>
* The black list is an array of UrlMatchers, a URLs <i>must not</i> match to,
* in order to be processed.
*
* @return The black list.
*/
public UrlMatcher[] getBlackList() {
return new UrlMatcher[0];
}
/**
* Gets the white list.
* <p>
* The black list is an array of WhiteListEntry, a URLs <i>must</i> match to,
* in order to be processed.
*
* @return Die Wei�e Liste
*/
public WhiteListEntry[] getWhiteList() {
return new WhiteListEntry[] {
new WhiteListEntry(new PrefixUrlMatcher("file://",true,true), null)
};
}
// overridden
public String[] getValuePrefetchFields() {
return null;
}
/**
* Gibt die regul�ren Ausdr�cke zur�ck, auf die die URL eines Dokuments passen
* muss, damit anstatt des wirklichen Dokumententitels der Text des Links, der
* auf das Dokument gezeigt hat, als Dokumententitel genutzt wird.
*
* @return Die regul�ren Ausdr�cke, die Dokumente bestimmen, f�r die der
* Linktext als Titel genommen werden soll.
*/
public String[] getUseLinkTextAsTitleRegexList() {
return null;
}
/**
* Gets the list with the preparator settings.
*
* @return The list with the preparator settings.
*/
public PreparatorSettings[] getPreparatorSettingsList() {
return new PreparatorSettings[] {
new PreparatorSettings(true, 0, "net.sf.regain.crawler.document.HtmlPreparator", null, new PreparatorConfig()),
new PreparatorSettings(true, 0, "net.sf.regain.crawler.document.XmlPreparator", null, new PreparatorConfig())
};
}
/**
* Gets the list with the crawler plugin settings.
*
* @return The list with the crawler plugin settings.
*/
public PreparatorSettings[] getCrawlerPluginSettingsList() {
return new PreparatorSettings[] {
};
}
/**
* Gets the list of the auxiliary fields.
*
* @return The list of the auxiliary fields. May be null.
*/
public AuxiliaryField[] getAuxiliaryFieldList() {
return null;
}
/**
* Gets the class name of the
* {@link net.sf.regain.crawler.access.CrawlerAccessController} to use.
* Returns <code>null</code> if no CrawlerAccessController should be used.
*
* @return The class name of the CrawlerAccessController.
*/
public String getCrawlerAccessControllerClass() {
return null;
}
/**
* Gets the name of jar file to load the
* {@link net.sf.regain.crawler.access.CrawlerAccessController} from.
* Returns <code>null</code> if the CrawlerAccessController already is in the
* classpath.
*
* @return The name of jar file to load the CrawlerAccessController from.
*/
public String getCrawlerAccessControllerJar() {
return null;
}
/**
* Gets the configuration of the
* {@link net.sf.regain.crawler.access.CrawlerAccessController}. May be
* <code>null</code>.
*
* @return The the configuration of the CrawlerAccessController.
*/
public Properties getCrawlerAccessControllerConfig() {
return null;
}
/**
* Returns the names of the fields that shouldn't be tokenized.
*
* @return The names of the fields that shouldn't be tokenized.
*/
@Override
public String[] getUntokenizedFieldNames(){
return null;
}
/**
* Returns maximum amount of characters which will be copied from content to summary
*
* @return MaxSummaryLength
*/
@Override
public int getMaxSummaryLength(){
return 250000;
}
/**
* {@inheritDoc }
*
*/
@Override
public String[] getURLCleaners() {
return new String[]{"PHPSESSID=[0-9a-z]{5,}"};
}
}
| til-schneider/regain | src/net/sf/regain/crawler/config/DummyCrawlerConfig.java | 3,950 | //www.dm-drogeriemarkt.de/CDA/Home/", true, true), | line_comment | nl | /*
* regain - A file search engine providing plenty of formats
* Copyright (C) 2004 Til Schneider
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: Til Schneider, [email protected]
*/
package net.sf.regain.crawler.config;
import java.util.Properties;
/**
* Stellt alle zu konfigurierenden Einstellungen hardcodiert zur Verfügung.
*
* @author Til Schneider, www.murfman.de
*/
public class DummyCrawlerConfig implements CrawlerConfig {
/**
* Returns the flag for enabling/disabling the content-preview
*
* @return boolean true if content preview is enabled and the whole content should be
* stored in the index
*/
@Override
public boolean getStoreContentForPreview(){
return true;
}
/**
* Gibt den Host-Namen des Proxy-Servers zur�ck. Wenn kein Host konfiguriert
* wurde, wird <CODE>null</CODE> zur�ckgegeben.
*
* @return Der Host-Namen des Proxy-Servers.
*/
@Override
public String getProxyHost() {
return "idatmpsrv";
}
/**
* Returns the maximum count of equal occurences of path-parts in an URI.
*
* @return MaxCycleCount
*/
@Override
public int getMaxCycleCount() {
return -1;
}
/**
* Gibt den Port des Proxy-Servers zur�ck. Wenn kein Port konfiguriert wurde,
* wird <CODE>null</CODE> zur�ckgegeben.
*
* @return Der Port des Proxy-Servers.
*/
@Override
public String getProxyPort() {
return "3128";
}
/**
* Gibt den Benutzernamen f�r die Anmeldung beim Proxy-Server zur�ck. Wenn
* kein Benutzernamen konfiguriert wurde, wird <CODE>null</CODE> zur�ckgegeben.
*
* @return Der Benutzernamen f�r die Anmeldung beim Proxy-Server.
*/
@Override
public String getProxyUser() {
return null;
}
/**
* Gibt das Passwort f�r die Anmeldung beim Proxy-Server zur�ck. Wenn kein
* Passwort konfiguriert wurde, wird <CODE>null</CODE> zur�ckgegeben.
*
* @return Das Passwort f�r die Anmeldung beim Proxy-Server.
*/
@Override
public String getProxyPassword() {
return null;
}
// overridden
@Override
public String getUserAgent() {
return null;
}
/**
* Gibt den Timeout f�r HTTP-Downloads zur�ck. Dieser Wert bestimmt die
* maximale Zeit in Sekunden, die ein HTTP-Download insgesamt dauern darf.
*
* @return Den Timeout f�r HTTP-Downloads
*/
@Override
public int getHttpTimeoutSecs() {
return 180;
}
/**
* Gibt zur�ck, ob URLs geladen werden sollen, die weder durchsucht noch
* indiziert werden.
*
* @return Ob URLs geladen werden sollen, die weder durchsucht noch indiziert
* werden.
*/
@Override
public boolean getLoadUnparsedUrls() {
return false;
}
/**
* Gibt zur�ck, ob ein Suchindex erstellt werden soll.
*
* @return Ob ein Suchindex erstellt werden soll.
*/
@Override
public boolean getBuildIndex() {
return true;
}
/**
* Gibt das Verzeichnis zur�ck, in dem der stehen soll.
*
* @return Das Verzeichnis, in dem der Suchindex stehen soll.
*/
@Override
public String getIndexDir() {
return "c:\\Temp\\searchIndex";
}
/**
* Gibt den zu verwendenden Analyzer-Typ zur�ck.
*
* @return en zu verwendenden Analyzer-Typ
*/
@Override
public String getAnalyzerType() {
return "german";
}
// overridden
public int getMaxFieldLength() {
return -1;
}
/**
* Gibt alle Worte zur�ck, die nicht indiziert werden sollen.
*
* @return Alle Worte, die nicht indiziert werden sollen.
*/
public String[] getStopWordList() {
return null;
}
/**
* Gibt alle Worte zur�ck, die bei der Indizierung nicht vom Analyzer
* ver�ndert werden sollen.
*
* @return Alle Worte, die bei der Indizierung nicht vom Analyzer
* ver�ndert werden sollen.
*/
public String[] getExclusionList() {
return null;
}
/**
* Gibt zur�ck, ob Analyse-Deteien geschrieben werden sollen.
* <p>
* Diese Dateien helfen, die Qualit�t der Index-Erstellung zu Prüfen und
* werden in einem Unterverzeichnis im Index-Verzeichnis angelegt.
*
* @return Ob Analyse-Deteien geschrieben werden sollen.
*/
public boolean getWriteAnalysisFiles() {
return true;
}
/**
* Returns the interval between two breakpoint in minutes. If set to 0, no
* breakpoints will be created.
*
* @return the interval between two breakpoint in minutes.
*/
public int getBreakpointInterval() {
return 10;
}
/**
* Gibt den maximalen Prozentsatz von gescheiterten Dokumenten zur�ck. (0..1)
* <p>
* Ist das Verh�lnis von gescheiterten Dokumenten zur Gesamtzahl von
* Dokumenten gr��er als dieser Prozentsatz, so wird der Index verworfen.
* <p>
* Gescheiterte Dokumente sind Dokumente die es entweder nicht gibt (Deadlink)
* oder die nicht ausgelesen werden konnten.
*
* @return Den maximalen Prozentsatz von gescheiterten Dokumenten zur�ck.
*/
public double getMaxFailedDocuments() {
return 0.1;
}
/**
* Gibt den Namen der Kontrolldatei f�r erfolgreiche Indexerstellung zur�ck.
* <p>
* Diese Datei wird erzeugt, wenn der Index erstellt wurde, ohne dass
* fatale Fehler aufgetreten sind.
* <p>
* Wenn keine Kontrolldatei erzeugt werden soll, dann wird <code>null</code>
* zur�ckgegeben.
*
* @return Der Name der Kontrolldatei f�r erfolgreiche Indexerstellung
*/
public String getFinishedWithoutFatalsFileName() {
return null;
}
/**
* Gibt den Namen der Kontrolldatei f�r fehlerhafte Indexerstellung zur�ck.
* <p>
* Diese Datei wird erzeugt, wenn der Index erstellt wurde, wobei
* fatale Fehler aufgetreten sind.
* <p>
* Wenn keine Kontrolldatei erzeugt werden soll, dann wird <code>null</code>
* zur�ckgegeben.
*
* @return Der Name der Kontrolldatei f�r fehlerhafte Indexerstellung
*/
public String getFinishedWithFatalsFileName() {
return null;
}
/**
* Gibt die StartUrls zur�ck, bei denen der Crawler-Proze� beginnen soll.
*
* @return Die StartUrls.
*/
public StartUrl[] getStartUrls() {
return new StartUrl[] {
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/Home/", true,<SUF>
/*
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,2098,0-15-X,00.html", true, true),
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,1651,0-16-X,00.html", true, true),
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,1651,0-17-X,00.html", true, true),
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,1651,0-18-X,00.html", true, true),
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,1651,0-19-X,00.html", true, true),
new StartUrl("http://www.dm-drogeriemarkt.de/CDA/verteilerseite/0,1651,0-173-X,00.html", true, true)
*/
};
}
/**
* Gibt die UrlPattern zur�ck, die der HTML-Parser nutzen soll, um URLs zu
* identifizieren.
*
* @return Die UrlPattern f�r den HTML-Parser.
*/
public UrlPattern[] getHtmlParserUrlPatterns() {
return new UrlPattern[] {
new UrlPattern("=\"([^\"]*\\.html)\"", 1, true, true),
new UrlPattern("=\"([^\"]*\\.(pdf|xls|doc|rtf|ppt))\"", 1, false, true),
new UrlPattern("=\"([^\"]*\\.(js|css|jpg|gif|png))\"", 1, false, false)
};
}
/**
* Gets the black list.
* <p>
* The black list is an array of UrlMatchers, a URLs <i>must not</i> match to,
* in order to be processed.
*
* @return The black list.
*/
public UrlMatcher[] getBlackList() {
return new UrlMatcher[0];
}
/**
* Gets the white list.
* <p>
* The black list is an array of WhiteListEntry, a URLs <i>must</i> match to,
* in order to be processed.
*
* @return Die Wei�e Liste
*/
public WhiteListEntry[] getWhiteList() {
return new WhiteListEntry[] {
new WhiteListEntry(new PrefixUrlMatcher("file://",true,true), null)
};
}
// overridden
public String[] getValuePrefetchFields() {
return null;
}
/**
* Gibt die regul�ren Ausdr�cke zur�ck, auf die die URL eines Dokuments passen
* muss, damit anstatt des wirklichen Dokumententitels der Text des Links, der
* auf das Dokument gezeigt hat, als Dokumententitel genutzt wird.
*
* @return Die regul�ren Ausdr�cke, die Dokumente bestimmen, f�r die der
* Linktext als Titel genommen werden soll.
*/
public String[] getUseLinkTextAsTitleRegexList() {
return null;
}
/**
* Gets the list with the preparator settings.
*
* @return The list with the preparator settings.
*/
public PreparatorSettings[] getPreparatorSettingsList() {
return new PreparatorSettings[] {
new PreparatorSettings(true, 0, "net.sf.regain.crawler.document.HtmlPreparator", null, new PreparatorConfig()),
new PreparatorSettings(true, 0, "net.sf.regain.crawler.document.XmlPreparator", null, new PreparatorConfig())
};
}
/**
* Gets the list with the crawler plugin settings.
*
* @return The list with the crawler plugin settings.
*/
public PreparatorSettings[] getCrawlerPluginSettingsList() {
return new PreparatorSettings[] {
};
}
/**
* Gets the list of the auxiliary fields.
*
* @return The list of the auxiliary fields. May be null.
*/
public AuxiliaryField[] getAuxiliaryFieldList() {
return null;
}
/**
* Gets the class name of the
* {@link net.sf.regain.crawler.access.CrawlerAccessController} to use.
* Returns <code>null</code> if no CrawlerAccessController should be used.
*
* @return The class name of the CrawlerAccessController.
*/
public String getCrawlerAccessControllerClass() {
return null;
}
/**
* Gets the name of jar file to load the
* {@link net.sf.regain.crawler.access.CrawlerAccessController} from.
* Returns <code>null</code> if the CrawlerAccessController already is in the
* classpath.
*
* @return The name of jar file to load the CrawlerAccessController from.
*/
public String getCrawlerAccessControllerJar() {
return null;
}
/**
* Gets the configuration of the
* {@link net.sf.regain.crawler.access.CrawlerAccessController}. May be
* <code>null</code>.
*
* @return The the configuration of the CrawlerAccessController.
*/
public Properties getCrawlerAccessControllerConfig() {
return null;
}
/**
* Returns the names of the fields that shouldn't be tokenized.
*
* @return The names of the fields that shouldn't be tokenized.
*/
@Override
public String[] getUntokenizedFieldNames(){
return null;
}
/**
* Returns maximum amount of characters which will be copied from content to summary
*
* @return MaxSummaryLength
*/
@Override
public int getMaxSummaryLength(){
return 250000;
}
/**
* {@inheritDoc }
*
*/
@Override
public String[] getURLCleaners() {
return new String[]{"PHPSESSID=[0-9a-z]{5,}"};
}
}
|
190190_19 | /**
* Copyright (C) 2016 X Gemeente
* X Amsterdam
* X Onderzoek, Informatie en Statistiek
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
package com.amsterdam.marktbureau.makkelijkemarkt.api.model;
import android.content.ContentValues;
import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author marcolangebeeke
*/
public class ApiDagvergunning {
private int id;
private String dag;
private int totaleLengte;
private int totaleLengteVast;
private String erkenningsnummer;
private String erkenningsnummerInvoerMethode;
private String aanwezig;
private String notitie;
private String status;
private String registratieDatumtijd;
private List<Float> registratieGeolocatie = new ArrayList<>();
private String aanmaakDatumtijd;
private boolean doorgehaald;
private int aantal3MeterKramen;
private int aantal4MeterKramen;
private int extraMeters;
private int aantalElektra;
private int afvaleiland;
private boolean krachtstroom;
private boolean reiniging;
private boolean eenmaligElektra;
private int aantal3meterKramenVast;
private int aantal4meterKramenVast;
private int aantalExtraMetersVast;
private int aantalElektraVast;
private int afvaleilandVast;
private boolean krachtstroomVast;
private boolean reinigingVast;
private boolean eenmaligElektraVast;
private ApiAccount registratieAccount;
private ApiMarkt markt;
private ApiKoopman koopman;
private ApiKoopman vervanger;
private ApiSollicitatie sollicitatie;
/**
* @return
*/
public int getId() {
return id;
}
/**
* @param id
*/
public void setId(int id) {
this.id = id;
}
/**
* @return
*/
public String getDag() {
return dag;
}
/**
* @param dag
*/
public void setDag(String dag) {
this.dag = dag;
}
/**
* @return
*/
public int getAantal3MeterKramen() {
return aantal3MeterKramen;
}
/**
* @param aantal3MeterKramen
*/
public void setAantal3MeterKramen(int aantal3MeterKramen) {
this.aantal3MeterKramen = aantal3MeterKramen;
}
/**
* @return
*/
public int getAantal4MeterKramen() {
return aantal4MeterKramen;
}
/**
* @param aantal4MeterKramen
*/
public void setAantal4MeterKramen(int aantal4MeterKramen) {
this.aantal4MeterKramen = aantal4MeterKramen;
}
/**
* @return
*/
public int getExtraMeters() {
return extraMeters;
}
/**
* @param extraMeters
*/
public void setExtraMeters(int extraMeters) {
this.extraMeters = extraMeters;
}
/**
* @return
*/
public int getTotaleLengte() {
return totaleLengte;
}
/**
* @param totaleLengte
*/
public void setTotaleLengte(int totaleLengte) {
this.totaleLengte = totaleLengte;
}
/**
* @return
*/
public int getAantalElektra() {
return aantalElektra;
}
/**
* @param aantalElektra
*/
public void setAantalElektra(int aantalElektra) {
this.aantalElektra = aantalElektra;
}
/**
* @return
*/
public int getAfvaleiland() {
return afvaleiland;
}
/**
* @param afvaleiland
*/
public void setAfvaleiland(int afvaleiland) {
this.afvaleiland = afvaleiland;
}
/**
* @return
*/
public boolean getKrachtstroom() {
return krachtstroom;
}
/**
* @param krachtstroom
*/
public void setKrachtstroom(boolean krachtstroom) {
this.krachtstroom = krachtstroom;
}
/**
* @return
*/
public boolean getReiniging() {
return reiniging;
}
/**
* @param reiniging
*/
public void setReiniging(boolean reiniging) {
this.reiniging = reiniging;
}
/**
* @return
*/
public boolean getEenmaligElektra() {
return eenmaligElektra;
}
/**
* @param eenmaligElektra
*/
public void setEenmaligElektra(boolean eenmaligElektra) {
this.eenmaligElektra = eenmaligElektra;
}
/**
* @return
*/
public boolean getReinigingVast() {
return reinigingVast;
}
/**
* @param reinigingVast
*/
public void setReinigingVast(boolean reinigingVast) {
this.reinigingVast = reinigingVast;
}
/**
* @return
*/
public boolean getEenmaligElektraVast() {
return eenmaligElektraVast;
}
/**
* @param eenmaligElektraVast
*/
public void setEenmaligElektraVast(boolean eenmaligElektraVast) {
this.eenmaligElektraVast = eenmaligElektraVast;
}
/**
* @return
*/
public boolean getKrachtstroomVast() {
return krachtstroomVast;
}
/**
* @param krachtstroomVast
*/
public void setKrachtstroomVast(boolean krachtstroomVast) {
this.krachtstroomVast = krachtstroomVast;
}
/**
* @return
*/
public String getErkenningsnummer() {
return erkenningsnummer;
}
/**
* @param erkenningsnummer
*/
public void setErkenningsnummer(String erkenningsnummer) {
this.erkenningsnummer = erkenningsnummer;
}
/**
* @return
*/
public String getErkenningsnummerInvoerMethode() {
return erkenningsnummerInvoerMethode;
}
/**
* @param erkenningsnummerInvoerMethode
*/
public void setErkenningsnummerInvoerMethode(String erkenningsnummerInvoerMethode) {
this.erkenningsnummerInvoerMethode = erkenningsnummerInvoerMethode;
}
/**
* @return
*/
public String getAanwezig() {
return aanwezig;
}
/**
* @param aanwezig
*/
public void setAanwezig(String aanwezig) {
this.aanwezig = aanwezig;
}
/**
* @return
*/
public String getNotitie() {
return notitie;
}
/**
* @param notitie
*/
public void setNotitie(String notitie) {
this.notitie = notitie;
}
/**
* @return
*/
public int getAantal3meterKramenVast() {
return aantal3meterKramenVast;
}
/**
* @param aantal3meterKramenVast
*/
public void setAantal3meterKramenVast(int aantal3meterKramenVast) {
this.aantal3meterKramenVast = aantal3meterKramenVast;
}
/**
* @return
*/
public int getAantal4meterKramenVast() {
return aantal4meterKramenVast;
}
/**
* @param aantal4meterKramenVast
*/
public void setAantal4meterKramenVast(int aantal4meterKramenVast) {
this.aantal4meterKramenVast = aantal4meterKramenVast;
}
/**
* @return
*/
public int getAantalExtraMetersVast() {
return aantalExtraMetersVast;
}
/**
* @param aantalExtraMetersVast
*/
public void setAantalExtraMetersVast(int aantalExtraMetersVast) {
this.aantalExtraMetersVast = aantalExtraMetersVast;
}
/**
* @return
*/
public int getTotaleLengteVast() {
return totaleLengteVast;
}
/**
* @param totaleLengteVast
*/
public void setTotaleLengteVast(int totaleLengteVast) {
this.totaleLengteVast = totaleLengteVast;
}
/**
* @return
*/
public int getAantalElektraVast() {
return aantalElektraVast;
}
/**
* @param aantalElektraVast
*/
public void setAantalElektraVast(int aantalElektraVast) {
this.aantalElektraVast = aantalElektraVast;
}
/**
* @return
*/
public int getAfvaleilandVast() {
return afvaleilandVast;
}
/**
* @param afvaleilandVast
*/
public void setAfvaleilandVast(int afvaleilandVast) {
this.afvaleilandVast = afvaleilandVast;
}
/**
* @return
*/
public String getStatus() {
return status;
}
/**
* @param status
*/
public void setStatus(String status) {
this.status = status;
}
/**
* @return
*/
public String getRegistratieDatumtijd() {
return registratieDatumtijd;
}
/**
* @param registratieDatumtijd
*/
public void setRegistratieDatumtijd(String registratieDatumtijd) {
this.registratieDatumtijd = registratieDatumtijd;
}
/**
* @return
*/
public List<Float> getRegistratieGeolocatie() {
return registratieGeolocatie;
}
/**
* @param registratieGeolocatie
*/
public void setRegistratieGeolocatie(List<Float> registratieGeolocatie) {
this.registratieGeolocatie = registratieGeolocatie;
}
/**
* @return
*/
public String getAanmaakDatumtijd() {
return aanmaakDatumtijd;
}
/**
* @param aanmaakDatumtijd
*/
public void setAanmaakDatumtijd(String aanmaakDatumtijd) {
this.aanmaakDatumtijd = aanmaakDatumtijd;
}
/**
* @return
*/
public boolean isDoorgehaald() {
return doorgehaald;
}
/**
* @param doorgehaald
*/
public void setDoorgehaald(boolean doorgehaald) {
this.doorgehaald = doorgehaald;
}
/**
* @return
*/
public ApiKoopman getKoopman() {
return koopman;
}
/**
* @param koopman
*/
public void setKoopman(ApiKoopman koopman) {
this.koopman = koopman;
}
/**
* @return
*/
public ApiKoopman getVervanger() {
return vervanger;
}
/**
* @param vervanger
*/
public void setVervanger(ApiKoopman vervanger) {
this.vervanger = vervanger;
}
/**
* @return
*/
public ApiAccount getRegistratieAccount() {
return registratieAccount;
}
/**
* @param registratieAccount
*/
public void setRegistratieAccount(ApiAccount registratieAccount) {
this.registratieAccount = registratieAccount;
}
/**
* @return
*/
public ApiMarkt getMarkt() {
return markt;
}
/**
* @param markt
*/
public void setMarkt(ApiMarkt markt) {
this.markt = markt;
}
/**
* @return
*/
public ApiSollicitatie getSollicitatie() {
return sollicitatie;
}
/**
* @param sollicitatie
*/
public void setSollicitatie(ApiSollicitatie sollicitatie) {
this.sollicitatie = sollicitatie;
}
/**
* Convert object to type contentvalues
* @return contentvalues object containing the objects name value pairs
*/
public ContentValues toContentValues() {
ContentValues dagvergunningValues = new ContentValues();
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_ID, getId());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_DAG, getDag());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_TOTALE_LENGTE, getTotaleLengte());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_TOTALE_LENGTE_VAST, getTotaleLengteVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE, getErkenningsnummer());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_METHODE, getErkenningsnummerInvoerMethode());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANWEZIG, getAanwezig());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_NOTITIE, getNotitie());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_STATUS_SOLLICITATIE, getStatus());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_DATUMTIJD, getRegistratieDatumtijd());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANMAAK_DATUMTIJD, getAanmaakDatumtijd());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_DOORGEHAALD, isDoorgehaald());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_3METER_KRAMEN, getAantal3MeterKramen());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_4METER_KRAMEN, getAantal4MeterKramen());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_EXTRA_METERS, getExtraMeters());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_ELEKTRA, getAantalElektra());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AFVALEILAND, getAfvaleiland());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_KRACHTSTROOM, getKrachtstroom());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REINIGING, getReiniging());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_EENMALIG_ELEKTRA, getEenmaligElektra());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_3METER_KRAMEN_VAST, getAantal3meterKramenVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_4METER_KRAMEN_VAST, getAantal4meterKramenVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_EXTRA_METERS_VAST, getAantalExtraMetersVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_ELEKTRA_VAST, getAantalElektraVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AFVALEILAND_VAST, getAfvaleilandVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_KRACHTSTROOM_VAST, getKrachtstroomVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REINIGING_VAST, getReinigingVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_EENMALIG_ELEKTRA_VAST, getEenmaligElektraVast());
if (getRegistratieGeolocatie() != null && getRegistratieGeolocatie().size() > 1) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_GEOLOCATIE_LAT, getRegistratieGeolocatie().get(0));
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_GEOLOCATIE_LONG, getRegistratieGeolocatie().get(1));
}
if (getRegistratieAccount() != null) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_ACCOUNT_ID, getRegistratieAccount().getId());
}
if (getMarkt() != null) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID,getMarkt().getId());
}
if (getKoopman() != null) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_KOOPMAN_ID, getKoopman().getId());
}
if (getVervanger() != null) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_VERVANGER_ID, getVervanger().getId());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_VERVANGER_ERKENNINGSNUMMER, getVervanger().getErkenningsnummer());
}
if (getSollicitatie() != null) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_SOLLICITATIE_ID, getSollicitatie().getId());
}
return dagvergunningValues;
}
} | tiltshiftnl/makkelijkemarkt-androidapp | app/src/main/java/com/amsterdam/marktbureau/makkelijkemarkt/api/model/ApiDagvergunning.java | 5,576 | /**
* @param krachtstroom
*/ | block_comment | nl | /**
* Copyright (C) 2016 X Gemeente
* X Amsterdam
* X Onderzoek, Informatie en Statistiek
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
package com.amsterdam.marktbureau.makkelijkemarkt.api.model;
import android.content.ContentValues;
import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author marcolangebeeke
*/
public class ApiDagvergunning {
private int id;
private String dag;
private int totaleLengte;
private int totaleLengteVast;
private String erkenningsnummer;
private String erkenningsnummerInvoerMethode;
private String aanwezig;
private String notitie;
private String status;
private String registratieDatumtijd;
private List<Float> registratieGeolocatie = new ArrayList<>();
private String aanmaakDatumtijd;
private boolean doorgehaald;
private int aantal3MeterKramen;
private int aantal4MeterKramen;
private int extraMeters;
private int aantalElektra;
private int afvaleiland;
private boolean krachtstroom;
private boolean reiniging;
private boolean eenmaligElektra;
private int aantal3meterKramenVast;
private int aantal4meterKramenVast;
private int aantalExtraMetersVast;
private int aantalElektraVast;
private int afvaleilandVast;
private boolean krachtstroomVast;
private boolean reinigingVast;
private boolean eenmaligElektraVast;
private ApiAccount registratieAccount;
private ApiMarkt markt;
private ApiKoopman koopman;
private ApiKoopman vervanger;
private ApiSollicitatie sollicitatie;
/**
* @return
*/
public int getId() {
return id;
}
/**
* @param id
*/
public void setId(int id) {
this.id = id;
}
/**
* @return
*/
public String getDag() {
return dag;
}
/**
* @param dag
*/
public void setDag(String dag) {
this.dag = dag;
}
/**
* @return
*/
public int getAantal3MeterKramen() {
return aantal3MeterKramen;
}
/**
* @param aantal3MeterKramen
*/
public void setAantal3MeterKramen(int aantal3MeterKramen) {
this.aantal3MeterKramen = aantal3MeterKramen;
}
/**
* @return
*/
public int getAantal4MeterKramen() {
return aantal4MeterKramen;
}
/**
* @param aantal4MeterKramen
*/
public void setAantal4MeterKramen(int aantal4MeterKramen) {
this.aantal4MeterKramen = aantal4MeterKramen;
}
/**
* @return
*/
public int getExtraMeters() {
return extraMeters;
}
/**
* @param extraMeters
*/
public void setExtraMeters(int extraMeters) {
this.extraMeters = extraMeters;
}
/**
* @return
*/
public int getTotaleLengte() {
return totaleLengte;
}
/**
* @param totaleLengte
*/
public void setTotaleLengte(int totaleLengte) {
this.totaleLengte = totaleLengte;
}
/**
* @return
*/
public int getAantalElektra() {
return aantalElektra;
}
/**
* @param aantalElektra
*/
public void setAantalElektra(int aantalElektra) {
this.aantalElektra = aantalElektra;
}
/**
* @return
*/
public int getAfvaleiland() {
return afvaleiland;
}
/**
* @param afvaleiland
*/
public void setAfvaleiland(int afvaleiland) {
this.afvaleiland = afvaleiland;
}
/**
* @return
*/
public boolean getKrachtstroom() {
return krachtstroom;
}
/**
* @param krachtstroom
<SUF>*/
public void setKrachtstroom(boolean krachtstroom) {
this.krachtstroom = krachtstroom;
}
/**
* @return
*/
public boolean getReiniging() {
return reiniging;
}
/**
* @param reiniging
*/
public void setReiniging(boolean reiniging) {
this.reiniging = reiniging;
}
/**
* @return
*/
public boolean getEenmaligElektra() {
return eenmaligElektra;
}
/**
* @param eenmaligElektra
*/
public void setEenmaligElektra(boolean eenmaligElektra) {
this.eenmaligElektra = eenmaligElektra;
}
/**
* @return
*/
public boolean getReinigingVast() {
return reinigingVast;
}
/**
* @param reinigingVast
*/
public void setReinigingVast(boolean reinigingVast) {
this.reinigingVast = reinigingVast;
}
/**
* @return
*/
public boolean getEenmaligElektraVast() {
return eenmaligElektraVast;
}
/**
* @param eenmaligElektraVast
*/
public void setEenmaligElektraVast(boolean eenmaligElektraVast) {
this.eenmaligElektraVast = eenmaligElektraVast;
}
/**
* @return
*/
public boolean getKrachtstroomVast() {
return krachtstroomVast;
}
/**
* @param krachtstroomVast
*/
public void setKrachtstroomVast(boolean krachtstroomVast) {
this.krachtstroomVast = krachtstroomVast;
}
/**
* @return
*/
public String getErkenningsnummer() {
return erkenningsnummer;
}
/**
* @param erkenningsnummer
*/
public void setErkenningsnummer(String erkenningsnummer) {
this.erkenningsnummer = erkenningsnummer;
}
/**
* @return
*/
public String getErkenningsnummerInvoerMethode() {
return erkenningsnummerInvoerMethode;
}
/**
* @param erkenningsnummerInvoerMethode
*/
public void setErkenningsnummerInvoerMethode(String erkenningsnummerInvoerMethode) {
this.erkenningsnummerInvoerMethode = erkenningsnummerInvoerMethode;
}
/**
* @return
*/
public String getAanwezig() {
return aanwezig;
}
/**
* @param aanwezig
*/
public void setAanwezig(String aanwezig) {
this.aanwezig = aanwezig;
}
/**
* @return
*/
public String getNotitie() {
return notitie;
}
/**
* @param notitie
*/
public void setNotitie(String notitie) {
this.notitie = notitie;
}
/**
* @return
*/
public int getAantal3meterKramenVast() {
return aantal3meterKramenVast;
}
/**
* @param aantal3meterKramenVast
*/
public void setAantal3meterKramenVast(int aantal3meterKramenVast) {
this.aantal3meterKramenVast = aantal3meterKramenVast;
}
/**
* @return
*/
public int getAantal4meterKramenVast() {
return aantal4meterKramenVast;
}
/**
* @param aantal4meterKramenVast
*/
public void setAantal4meterKramenVast(int aantal4meterKramenVast) {
this.aantal4meterKramenVast = aantal4meterKramenVast;
}
/**
* @return
*/
public int getAantalExtraMetersVast() {
return aantalExtraMetersVast;
}
/**
* @param aantalExtraMetersVast
*/
public void setAantalExtraMetersVast(int aantalExtraMetersVast) {
this.aantalExtraMetersVast = aantalExtraMetersVast;
}
/**
* @return
*/
public int getTotaleLengteVast() {
return totaleLengteVast;
}
/**
* @param totaleLengteVast
*/
public void setTotaleLengteVast(int totaleLengteVast) {
this.totaleLengteVast = totaleLengteVast;
}
/**
* @return
*/
public int getAantalElektraVast() {
return aantalElektraVast;
}
/**
* @param aantalElektraVast
*/
public void setAantalElektraVast(int aantalElektraVast) {
this.aantalElektraVast = aantalElektraVast;
}
/**
* @return
*/
public int getAfvaleilandVast() {
return afvaleilandVast;
}
/**
* @param afvaleilandVast
*/
public void setAfvaleilandVast(int afvaleilandVast) {
this.afvaleilandVast = afvaleilandVast;
}
/**
* @return
*/
public String getStatus() {
return status;
}
/**
* @param status
*/
public void setStatus(String status) {
this.status = status;
}
/**
* @return
*/
public String getRegistratieDatumtijd() {
return registratieDatumtijd;
}
/**
* @param registratieDatumtijd
*/
public void setRegistratieDatumtijd(String registratieDatumtijd) {
this.registratieDatumtijd = registratieDatumtijd;
}
/**
* @return
*/
public List<Float> getRegistratieGeolocatie() {
return registratieGeolocatie;
}
/**
* @param registratieGeolocatie
*/
public void setRegistratieGeolocatie(List<Float> registratieGeolocatie) {
this.registratieGeolocatie = registratieGeolocatie;
}
/**
* @return
*/
public String getAanmaakDatumtijd() {
return aanmaakDatumtijd;
}
/**
* @param aanmaakDatumtijd
*/
public void setAanmaakDatumtijd(String aanmaakDatumtijd) {
this.aanmaakDatumtijd = aanmaakDatumtijd;
}
/**
* @return
*/
public boolean isDoorgehaald() {
return doorgehaald;
}
/**
* @param doorgehaald
*/
public void setDoorgehaald(boolean doorgehaald) {
this.doorgehaald = doorgehaald;
}
/**
* @return
*/
public ApiKoopman getKoopman() {
return koopman;
}
/**
* @param koopman
*/
public void setKoopman(ApiKoopman koopman) {
this.koopman = koopman;
}
/**
* @return
*/
public ApiKoopman getVervanger() {
return vervanger;
}
/**
* @param vervanger
*/
public void setVervanger(ApiKoopman vervanger) {
this.vervanger = vervanger;
}
/**
* @return
*/
public ApiAccount getRegistratieAccount() {
return registratieAccount;
}
/**
* @param registratieAccount
*/
public void setRegistratieAccount(ApiAccount registratieAccount) {
this.registratieAccount = registratieAccount;
}
/**
* @return
*/
public ApiMarkt getMarkt() {
return markt;
}
/**
* @param markt
*/
public void setMarkt(ApiMarkt markt) {
this.markt = markt;
}
/**
* @return
*/
public ApiSollicitatie getSollicitatie() {
return sollicitatie;
}
/**
* @param sollicitatie
*/
public void setSollicitatie(ApiSollicitatie sollicitatie) {
this.sollicitatie = sollicitatie;
}
/**
* Convert object to type contentvalues
* @return contentvalues object containing the objects name value pairs
*/
public ContentValues toContentValues() {
ContentValues dagvergunningValues = new ContentValues();
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_ID, getId());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_DAG, getDag());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_TOTALE_LENGTE, getTotaleLengte());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_TOTALE_LENGTE_VAST, getTotaleLengteVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE, getErkenningsnummer());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_METHODE, getErkenningsnummerInvoerMethode());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANWEZIG, getAanwezig());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_NOTITIE, getNotitie());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_STATUS_SOLLICITATIE, getStatus());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_DATUMTIJD, getRegistratieDatumtijd());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANMAAK_DATUMTIJD, getAanmaakDatumtijd());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_DOORGEHAALD, isDoorgehaald());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_3METER_KRAMEN, getAantal3MeterKramen());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_4METER_KRAMEN, getAantal4MeterKramen());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_EXTRA_METERS, getExtraMeters());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_ELEKTRA, getAantalElektra());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AFVALEILAND, getAfvaleiland());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_KRACHTSTROOM, getKrachtstroom());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REINIGING, getReiniging());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_EENMALIG_ELEKTRA, getEenmaligElektra());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_3METER_KRAMEN_VAST, getAantal3meterKramenVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_4METER_KRAMEN_VAST, getAantal4meterKramenVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_EXTRA_METERS_VAST, getAantalExtraMetersVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AANTAL_ELEKTRA_VAST, getAantalElektraVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_AFVALEILAND_VAST, getAfvaleilandVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_KRACHTSTROOM_VAST, getKrachtstroomVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REINIGING_VAST, getReinigingVast());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_EENMALIG_ELEKTRA_VAST, getEenmaligElektraVast());
if (getRegistratieGeolocatie() != null && getRegistratieGeolocatie().size() > 1) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_GEOLOCATIE_LAT, getRegistratieGeolocatie().get(0));
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_GEOLOCATIE_LONG, getRegistratieGeolocatie().get(1));
}
if (getRegistratieAccount() != null) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_REGISTRATIE_ACCOUNT_ID, getRegistratieAccount().getId());
}
if (getMarkt() != null) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID,getMarkt().getId());
}
if (getKoopman() != null) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_KOOPMAN_ID, getKoopman().getId());
}
if (getVervanger() != null) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_VERVANGER_ID, getVervanger().getId());
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_VERVANGER_ERKENNINGSNUMMER, getVervanger().getErkenningsnummer());
}
if (getSollicitatie() != null) {
dagvergunningValues.put(MakkelijkeMarktProvider.Dagvergunning.COL_SOLLICITATIE_ID, getSollicitatie().getId());
}
return dagvergunningValues;
}
} |
28190_5 | package nl.vpro.io.prepr.domain;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import java.time.Duration;
import java.time.Instant;
import org.checkerframework.checker.nullness.qual.NonNull;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.collect.Range;
import nl.vpro.jackson2.DurationToJsonTimestamp;
/**
* @author Michiel Meeuwissen
* @since 0.1
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
public abstract class PreprAbstractMedia extends PreprAsset {
@JsonSerialize(using = DurationToJsonTimestamp.Serializer.class)
@JsonDeserialize(using = DurationToJsonTimestamp.Deserializer.class)
Duration duration;
//2019-0-16: Not yet documented on Prepr.
Instant started_on;
Instant ended_on;
public boolean isSegment(@NonNull Range<Instant> schedule) {
return isSegment(schedule, Duration.ofMinutes(5));
}
public boolean isSegment(@NonNull Range<Instant> schedule, @NonNull Duration slack) {
// TODO: Segmenten worden eigenlijk niet goed ondersteund in Prepr?
// Je kunt in de user interface allerlei filmpjes uploaden, het is in het geheel niet gezegd dat dat correspondeert met de uitzending.
// Ze hebben echter wel een absolute 'started_on' tijd en 'duration' (of eventueel een ended_on?)
// We gaan er nu vanuit dat een filmpje een 'segment' is, als het 'enclosed' is in het uur waarmee het geassocieerd is
if (getStarted_on() == null) {
log.debug("Asset {} is not a segment because it has not started_on", this);
return false;
}
Range<Instant> range;
if (getDuration() != null) {
range = Range.closedOpen(getStarted_on(), getStarted_on().plus(getDuration()));
} else if (getEnded_on() != null) {
range = Range.closedOpen(getStarted_on(), getEnded_on());
} else {
return false;
}
Range<Instant> extendedRange = Range.closedOpen(schedule.lowerEndpoint().minus(slack), schedule.upperEndpoint().plus(slack));
return extendedRange.encloses(range);
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"duration='" + duration + '\'' +
", name='" + name + '\'' +
", body='" + body + '\'' +
", source_file=" + source_file +
", reference_id=" + reference_id +
", id=" + id +
'}';
}
}
| tim-hanssen/prepr | src/main/java/nl/vpro/io/prepr/domain/PreprAbstractMedia.java | 792 | // We gaan er nu vanuit dat een filmpje een 'segment' is, als het 'enclosed' is in het uur waarmee het geassocieerd is | line_comment | nl | package nl.vpro.io.prepr.domain;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import java.time.Duration;
import java.time.Instant;
import org.checkerframework.checker.nullness.qual.NonNull;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.google.common.collect.Range;
import nl.vpro.jackson2.DurationToJsonTimestamp;
/**
* @author Michiel Meeuwissen
* @since 0.1
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
public abstract class PreprAbstractMedia extends PreprAsset {
@JsonSerialize(using = DurationToJsonTimestamp.Serializer.class)
@JsonDeserialize(using = DurationToJsonTimestamp.Deserializer.class)
Duration duration;
//2019-0-16: Not yet documented on Prepr.
Instant started_on;
Instant ended_on;
public boolean isSegment(@NonNull Range<Instant> schedule) {
return isSegment(schedule, Duration.ofMinutes(5));
}
public boolean isSegment(@NonNull Range<Instant> schedule, @NonNull Duration slack) {
// TODO: Segmenten worden eigenlijk niet goed ondersteund in Prepr?
// Je kunt in de user interface allerlei filmpjes uploaden, het is in het geheel niet gezegd dat dat correspondeert met de uitzending.
// Ze hebben echter wel een absolute 'started_on' tijd en 'duration' (of eventueel een ended_on?)
// We gaan<SUF>
if (getStarted_on() == null) {
log.debug("Asset {} is not a segment because it has not started_on", this);
return false;
}
Range<Instant> range;
if (getDuration() != null) {
range = Range.closedOpen(getStarted_on(), getStarted_on().plus(getDuration()));
} else if (getEnded_on() != null) {
range = Range.closedOpen(getStarted_on(), getEnded_on());
} else {
return false;
}
Range<Instant> extendedRange = Range.closedOpen(schedule.lowerEndpoint().minus(slack), schedule.upperEndpoint().plus(slack));
return extendedRange.encloses(range);
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"duration='" + duration + '\'' +
", name='" + name + '\'' +
", body='" + body + '\'' +
", source_file=" + source_file +
", reference_id=" + reference_id +
", id=" + id +
'}';
}
}
|
147808_16 | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
/*
Bad ones
Model 1 = 93,119,
Model 2 = 67,98,
Classifier MP_ED acc =0.45555555555555555
Model 1 = 84,118,
Model 2 = 66,109,
*/
package statistics.simulators;
import fileIO.OutFile;
import java.util.*;
import java.io.*;
import statistics.distributions.NormalDistribution;
import statistics.simulators.DictionaryModel.ShapeType;
import static statistics.simulators.Model.rand;
import statistics.simulators.ShapeletModel.Shape;
public class MatrixProfileModelVersion1 extends Model {
private int nosLocations=2; //
private int shapeLength=29;
public static double MINBASE=-2;
public static double MINAMP=2;
public static double MAXBASE=2;
public static double MAXAMP=4;
DictionaryModel.Shape shape;//Will change for each series
private static int GLOBALSERIESLENGTH=500;
private int seriesLength; // Need to set intervals, maybe allow different lengths?
private int base=-1;
private int amplitude=2;
private int shapeCount=0;
private boolean invert=false;
boolean discord=false;
double[] shapeVals;
ArrayList<Integer> locations;
public static int getGlobalLength(){ return GLOBALSERIESLENGTH;}
public MatrixProfileModelVersion1(){
shapeCount=0;//rand.nextInt(ShapeType.values().length);
seriesLength=GLOBALSERIESLENGTH;
locations=new ArrayList<>();
setNonOverlappingIntervals();
shapeVals=new double[shapeLength];
generateRandomShapeVals();
}
public MatrixProfileModelVersion1(boolean d){
shapeCount=0;//rand.nextInt(ShapeType.values().length);
discord=d;
if(discord)
nosLocations=1;
seriesLength=GLOBALSERIESLENGTH;
locations=new ArrayList<>();
setNonOverlappingIntervals();
shapeVals=new double[shapeLength];
generateRandomShapeVals();
}
private void generateRandomShapeVals(){
for(int i=0;i<shapeLength;i++)
shapeVals[i]=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
}
public void setSeriesLength(int n){
seriesLength=n;
}
public static void setGlobalSeriesLength(int n){
GLOBALSERIESLENGTH=n;
}
public void setNonOverlappingIntervals(){
//Use Aarons way
ArrayList<Integer> startPoints=new ArrayList<>();
for(int i=shapeLength+1;i<seriesLength-shapeLength;i++)
startPoints.add(i);
for(int i=0;i<nosLocations;i++){
int pos=rand.nextInt(startPoints.size());
int l=startPoints.get(pos);
locations.add(l);
//+/- windowSize/2
if(pos<shapeLength)
pos=0;
else
pos=pos-shapeLength;
for(int j=0;startPoints.size()>pos && j<(3*shapeLength);j++)
startPoints.remove(pos);
/*
//Me giving up and just randomly placing the shapes until they are all non overlapping
for(int i=0;i<nosLocations;i++){
boolean ok=false;
int l=shapeLength/2;
while(!ok){
ok=true;
//Search mid points to level the distribution up somewhat
// System.out.println("Series length ="+seriesLength);
do{
l=rand.nextInt(seriesLength-shapeLength)+shapeLength/2;
}
while((l+shapeLength/2)>=seriesLength-shapeLength);
for(int in:locations){
//I think this is setting them too big
if((l>=in-shapeLength && l<in+shapeLength) //l inside ins
||(l<in-shapeLength && l+shapeLength>in) ){ //ins inside l
ok=false;
// System.out.println(l+" overlaps with "+in);
break;
}
}
}
*/
// System.out.println("Adding "+l);
}
/*//Revert to start points
for(int i=0;i<locations.size();i++){
int val=locations.get(i);
locations.set(i, val-shapeLength/2);
}
*/ Collections.sort(locations);
// System.out.println("MODEL START POINTS =");
// for(int i=0;i<locations.size();i++)
// System.out.println(locations.get(i));
}
@Override
public void setParameters(double[] p) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void setLocations(ArrayList<Integer> l, int length){
locations=new ArrayList<>(l);
shapeLength=length;
}
public ArrayList<Integer> getIntervals(){return locations;}
public int getShapeLength(){ return shapeLength;}
public void generateBaseShape(){
//Randomise BASE and AMPLITUDE
double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble();
ShapeType[] all=ShapeType.values();
ShapeType st=all[(shapeCount++)%all.length];
shape=new DictionaryModel.Shape(st,shapeLength,b,a);
// shape=new DictionaryModel.Shape(DictionaryModel.ShapeType.SPIKE,shapeLength,b,a);
// System.out.println("Shape is "+shape);
// shape.nextShape();
// shape
}
@Override
public double[] generateSeries(int n)
{
t=0;
double[] d;
generateRandomShapeVals();
//Resets the starting locations each time this is called
if(invert){
d= new double[n];
for(int i=0;i<n;i++)
d[i]=-generate();
invert=false;
}
else{
generateBaseShape();
d = new double[n];
for(int i=0;i<n;i++)
d[i]=generate();
invert=true;
}
return d;
}
private double generateConfig1(){
//Noise
// System.out.println("Error var ="+error.getVariance());
double value=0;
//Find the next shape
int insertionPoint=0;
while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t)
insertionPoint++;
//Bigger than all the start points, set to last
if(insertionPoint>=locations.size()){
insertionPoint=locations.size()-1;
}
int point=locations.get(insertionPoint);
if(point<=t && point+shapeLength>t)//in shape1
value=shapeVals[(int)(t-point)];
else
value= error.simulate();
// value+=shape.generateWithinShapelet((int)(t-point));
// System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t);
t++;
return value;
}
private double generateConfig2(){
//Noise
// System.out.println("Error var ="+error.getVariance());
double value=error.simulate();
//Find the next shape
int insertionPoint=0;
while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t)
insertionPoint++;
//Bigger than all the start points, set to last
if(insertionPoint>=locations.size()){
insertionPoint=locations.size()-1;
}
int point=locations.get(insertionPoint);
if(insertionPoint>0 && point==t){//New shape, randomise scale
// double b=shape.getBase()/5;
// double a=shape.getAmp()/5;
double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble();
shape.setAmp(a);
shape.setBase(b);
// System.out.println("changing second shape");
}
if(point<=t && point+shapeLength>t){//in shape1
value+=shape.generateWithinShapelet((int)(t-point));
// System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t);
}
t++;
return value;
}
//Generate point t
@Override
public double generate(){
return generateConfig1();
}
public static void generateExampleData(){
int length=500;
GLOBALSERIESLENGTH=length;
Model.setGlobalRandomSeed(3);
Model.setDefaultSigma(0);
MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1();
MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1();
double[][] d=new double[20][];
for(int i=0;i<10;i++){
d[i]=m1.generateSeries(length);
}
for(int i=10;i<20;i++){
d[i]=m1.generateSeries(length);
}
OutFile of=new OutFile("C:\\temp\\MP_ExampleSeries.csv");
for(int i=0;i<length;i++){
for(int j=0;j<10;j++)
of.writeString(d[j][i]+",");
of.writeString("\n");
}
}
public String toString(){
String str="";
for(Integer i:locations)
str+=i+",";
return str;
}
public static void main(String[] args){
generateExampleData();
System.exit(0);
//Set up two models with same intervals but different shapes
int length=500;
Model.setGlobalRandomSeed(10);
Model.setDefaultSigma(0.1);
MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1();
MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1();
double[] d1=m1.generateSeries(length);
double[] d2=m2.generateSeries(length);
OutFile of=new OutFile("C:\\temp\\MP_Ex.csv");
for(int i=0;i<length;i++)
of.writeLine(d1[i]+","+d2[i]);
}
}
| time-series-machine-learning/tsml-java | src/main/java/statistics/simulators/MatrixProfileModelVersion1.java | 3,086 | // System.out.println("Error var ="+error.getVariance()); | line_comment | nl | /*
* This file is part of the UEA Time Series Machine Learning (TSML) toolbox.
*
* The UEA TSML toolbox 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.
*
* The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>.
*/
/*
Bad ones
Model 1 = 93,119,
Model 2 = 67,98,
Classifier MP_ED acc =0.45555555555555555
Model 1 = 84,118,
Model 2 = 66,109,
*/
package statistics.simulators;
import fileIO.OutFile;
import java.util.*;
import java.io.*;
import statistics.distributions.NormalDistribution;
import statistics.simulators.DictionaryModel.ShapeType;
import static statistics.simulators.Model.rand;
import statistics.simulators.ShapeletModel.Shape;
public class MatrixProfileModelVersion1 extends Model {
private int nosLocations=2; //
private int shapeLength=29;
public static double MINBASE=-2;
public static double MINAMP=2;
public static double MAXBASE=2;
public static double MAXAMP=4;
DictionaryModel.Shape shape;//Will change for each series
private static int GLOBALSERIESLENGTH=500;
private int seriesLength; // Need to set intervals, maybe allow different lengths?
private int base=-1;
private int amplitude=2;
private int shapeCount=0;
private boolean invert=false;
boolean discord=false;
double[] shapeVals;
ArrayList<Integer> locations;
public static int getGlobalLength(){ return GLOBALSERIESLENGTH;}
public MatrixProfileModelVersion1(){
shapeCount=0;//rand.nextInt(ShapeType.values().length);
seriesLength=GLOBALSERIESLENGTH;
locations=new ArrayList<>();
setNonOverlappingIntervals();
shapeVals=new double[shapeLength];
generateRandomShapeVals();
}
public MatrixProfileModelVersion1(boolean d){
shapeCount=0;//rand.nextInt(ShapeType.values().length);
discord=d;
if(discord)
nosLocations=1;
seriesLength=GLOBALSERIESLENGTH;
locations=new ArrayList<>();
setNonOverlappingIntervals();
shapeVals=new double[shapeLength];
generateRandomShapeVals();
}
private void generateRandomShapeVals(){
for(int i=0;i<shapeLength;i++)
shapeVals[i]=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
}
public void setSeriesLength(int n){
seriesLength=n;
}
public static void setGlobalSeriesLength(int n){
GLOBALSERIESLENGTH=n;
}
public void setNonOverlappingIntervals(){
//Use Aarons way
ArrayList<Integer> startPoints=new ArrayList<>();
for(int i=shapeLength+1;i<seriesLength-shapeLength;i++)
startPoints.add(i);
for(int i=0;i<nosLocations;i++){
int pos=rand.nextInt(startPoints.size());
int l=startPoints.get(pos);
locations.add(l);
//+/- windowSize/2
if(pos<shapeLength)
pos=0;
else
pos=pos-shapeLength;
for(int j=0;startPoints.size()>pos && j<(3*shapeLength);j++)
startPoints.remove(pos);
/*
//Me giving up and just randomly placing the shapes until they are all non overlapping
for(int i=0;i<nosLocations;i++){
boolean ok=false;
int l=shapeLength/2;
while(!ok){
ok=true;
//Search mid points to level the distribution up somewhat
// System.out.println("Series length ="+seriesLength);
do{
l=rand.nextInt(seriesLength-shapeLength)+shapeLength/2;
}
while((l+shapeLength/2)>=seriesLength-shapeLength);
for(int in:locations){
//I think this is setting them too big
if((l>=in-shapeLength && l<in+shapeLength) //l inside ins
||(l<in-shapeLength && l+shapeLength>in) ){ //ins inside l
ok=false;
// System.out.println(l+" overlaps with "+in);
break;
}
}
}
*/
// System.out.println("Adding "+l);
}
/*//Revert to start points
for(int i=0;i<locations.size();i++){
int val=locations.get(i);
locations.set(i, val-shapeLength/2);
}
*/ Collections.sort(locations);
// System.out.println("MODEL START POINTS =");
// for(int i=0;i<locations.size();i++)
// System.out.println(locations.get(i));
}
@Override
public void setParameters(double[] p) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void setLocations(ArrayList<Integer> l, int length){
locations=new ArrayList<>(l);
shapeLength=length;
}
public ArrayList<Integer> getIntervals(){return locations;}
public int getShapeLength(){ return shapeLength;}
public void generateBaseShape(){
//Randomise BASE and AMPLITUDE
double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble();
ShapeType[] all=ShapeType.values();
ShapeType st=all[(shapeCount++)%all.length];
shape=new DictionaryModel.Shape(st,shapeLength,b,a);
// shape=new DictionaryModel.Shape(DictionaryModel.ShapeType.SPIKE,shapeLength,b,a);
// System.out.println("Shape is "+shape);
// shape.nextShape();
// shape
}
@Override
public double[] generateSeries(int n)
{
t=0;
double[] d;
generateRandomShapeVals();
//Resets the starting locations each time this is called
if(invert){
d= new double[n];
for(int i=0;i<n;i++)
d[i]=-generate();
invert=false;
}
else{
generateBaseShape();
d = new double[n];
for(int i=0;i<n;i++)
d[i]=generate();
invert=true;
}
return d;
}
private double generateConfig1(){
//Noise
// System.out.println("Error var ="+error.getVariance());
double value=0;
//Find the next shape
int insertionPoint=0;
while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t)
insertionPoint++;
//Bigger than all the start points, set to last
if(insertionPoint>=locations.size()){
insertionPoint=locations.size()-1;
}
int point=locations.get(insertionPoint);
if(point<=t && point+shapeLength>t)//in shape1
value=shapeVals[(int)(t-point)];
else
value= error.simulate();
// value+=shape.generateWithinShapelet((int)(t-point));
// System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t);
t++;
return value;
}
private double generateConfig2(){
//Noise
// System.out.println("Error var<SUF>
double value=error.simulate();
//Find the next shape
int insertionPoint=0;
while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t)
insertionPoint++;
//Bigger than all the start points, set to last
if(insertionPoint>=locations.size()){
insertionPoint=locations.size()-1;
}
int point=locations.get(insertionPoint);
if(insertionPoint>0 && point==t){//New shape, randomise scale
// double b=shape.getBase()/5;
// double a=shape.getAmp()/5;
double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble();
double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble();
shape.setAmp(a);
shape.setBase(b);
// System.out.println("changing second shape");
}
if(point<=t && point+shapeLength>t){//in shape1
value+=shape.generateWithinShapelet((int)(t-point));
// System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t);
}
t++;
return value;
}
//Generate point t
@Override
public double generate(){
return generateConfig1();
}
public static void generateExampleData(){
int length=500;
GLOBALSERIESLENGTH=length;
Model.setGlobalRandomSeed(3);
Model.setDefaultSigma(0);
MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1();
MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1();
double[][] d=new double[20][];
for(int i=0;i<10;i++){
d[i]=m1.generateSeries(length);
}
for(int i=10;i<20;i++){
d[i]=m1.generateSeries(length);
}
OutFile of=new OutFile("C:\\temp\\MP_ExampleSeries.csv");
for(int i=0;i<length;i++){
for(int j=0;j<10;j++)
of.writeString(d[j][i]+",");
of.writeString("\n");
}
}
public String toString(){
String str="";
for(Integer i:locations)
str+=i+",";
return str;
}
public static void main(String[] args){
generateExampleData();
System.exit(0);
//Set up two models with same intervals but different shapes
int length=500;
Model.setGlobalRandomSeed(10);
Model.setDefaultSigma(0.1);
MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1();
MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1();
double[] d1=m1.generateSeries(length);
double[] d2=m2.generateSeries(length);
OutFile of=new OutFile("C:\\temp\\MP_Ex.csv");
for(int i=0;i<length;i++)
of.writeLine(d1[i]+","+d2[i]);
}
}
|
47882_2 | package eu.digiwhist.worker.nl.clean;
import eu.digiwhist.worker.clean.BaseDigiwhistTenderCleaner;
import eu.dl.dataaccess.dto.clean.CleanTender;
import eu.dl.dataaccess.dto.codetables.BuyerActivityType;
import eu.dl.dataaccess.dto.codetables.BuyerType;
import eu.dl.dataaccess.dto.codetables.PublicationFormType;
import eu.dl.dataaccess.dto.codetables.TenderSupplyType;
import eu.dl.dataaccess.dto.parsed.ParsedTender;
import eu.dl.worker.clean.plugin.AddressPlugin;
import eu.dl.worker.clean.plugin.AwardCriteriaPlugin;
import eu.dl.worker.clean.plugin.BodyPlugin;
import eu.dl.worker.clean.plugin.DatePlugin;
import eu.dl.worker.clean.plugin.DateTimePlugin;
import eu.dl.worker.clean.plugin.FundingsPlugin;
import eu.dl.worker.clean.plugin.IntegerPlugin;
import eu.dl.worker.clean.plugin.LotPlugin;
import eu.dl.worker.clean.plugin.PublicationPlugin;
import eu.dl.worker.clean.plugin.TenderSupplyTypePlugin;
import java.text.NumberFormat;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Tender cleaner for TenderNed in Netherlands.
*
* @author Marek Mikes
*/
public class TenderNedTenderCleaner extends BaseDigiwhistTenderCleaner {
private static final String VERSION = "1";
private static final Locale LOCALE = new Locale("nl");
private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(LOCALE);
private static final List<DateTimeFormatter> DATE_FORMATTERS = Arrays.asList(
DateTimeFormatter.ofPattern("dd/MM/yyyy"),
DateTimeFormatter.ofPattern("dd-MM-yyyy"));
// date time examples:
// "09/09/2015 Tijdstip: 16:00"
// "05/12/2016 Plaatselijke tijd: 10:00"
// "31/10/2016 Plaatselijke tijd: -"
private static final List<DateTimeFormatter> DATETIME_FORMATTERS = Arrays.asList(
new DateTimeFormatterBuilder()
.appendPattern("dd/MM/yyyy")
.appendLiteral(" Tijdstip: ")
.appendPattern("HH:mm")
.toFormatter(LOCALE),
new DateTimeFormatterBuilder()
.appendPattern("dd/MM/yyyy")
.appendLiteral(" Plaatselijke tijd: ")
//optional time
.optionalStart()
.appendPattern("HH:mm")
.optionalEnd()
//optional not entered time
.optionalStart()
.appendLiteral("-")
.optionalEnd()
//default values for time
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter(LOCALE));
@Override
public final String getVersion() {
return VERSION;
}
@Override
protected final ParsedTender preProcessParsedItem(final ParsedTender parsedItem) {
// remove bid deadline when it has no useful information
if (parsedItem.getBidDeadline() != null && parsedItem.getBidDeadline().equals("- Tijdstip: -")) {
parsedItem.setBidDeadline(null);
}
return parsedItem;
}
@Override
protected final CleanTender postProcessSourceSpecificRules(final ParsedTender parsedTender,
final CleanTender cleanTender) {
return cleanTender;
}
@SuppressWarnings("unchecked")
@Override
protected final void registerSpecificPlugins() {
pluginRegistry
.registerPlugin("integerPlugin", new IntegerPlugin(NUMBER_FORMAT))
.registerPlugin("supplyType", new TenderSupplyTypePlugin(getSupplyTypeMapping()))
.registerPlugin("date", new DatePlugin(DATE_FORMATTERS))
.registerPlugin("datetime", new DateTimePlugin(DATETIME_FORMATTERS))
.registerPlugin("bodies", new BodyPlugin(getBuyerTypeMapping(), getBodyActivityMapping()))
.registerPlugin("lots", new LotPlugin(NUMBER_FORMAT, DATE_FORMATTERS, new HashMap<>()))
.registerPlugin("fundings", new FundingsPlugin(NUMBER_FORMAT))
.registerPlugin("address", new AddressPlugin())
.registerPlugin("awardCriteria", new AwardCriteriaPlugin(NUMBER_FORMAT))
.registerPlugin("publications",
new PublicationPlugin(NUMBER_FORMAT, DATE_FORMATTERS, getFormTypeMapping()));
}
/**
* @return supply type mapping for cleaning process
*/
private static Map<Enum, List<String>> getSupplyTypeMapping() {
final Map<Enum, List<String>> mapping = new HashMap<>();
mapping.put(TenderSupplyType.WORKS, Arrays.asList("(a) Werken"));
mapping.put(TenderSupplyType.SUPPLIES, Arrays.asList("(b) Leveringen"));
mapping.put(TenderSupplyType.SERVICES, Arrays.asList("(c) Diensten"));
return mapping;
}
/**
* @return body type mapping
*/
private static Map<Enum, List<String>> getBuyerTypeMapping() {
final Map<Enum, List<String>> mapping = new HashMap<>();
mapping.put(BuyerType.PUBLIC_BODY, Arrays.asList("Publiekrechtelijke instelling"));
mapping.put(BuyerType.NATIONAL_AGENCY, Arrays.asList("Nationaal of federaal agentschap/bureau"));
mapping.put(BuyerType.NATIONAL_AUTHORITY, Arrays.asList(
"Ministerie of andere nationale of federale instantie, met regionale of plaatselijke " +
"onderverdelingen ervan",
"Ministerie of andere nationale of federale instantie, met inbegrip van regionale of " +
"plaatselijke onderverdelingen"));
mapping.put(BuyerType.REGIONAL_AGENCY, Arrays.asList("Regionaal of plaatselijk agentschap/bureau"));
mapping.put(BuyerType.REGIONAL_AUTHORITY, Arrays.asList("Regionale of plaatselijke instantie",
"Andere: Gemeente", "Andere: gemeente"));
mapping.put(BuyerType.EUROPEAN_AGENCY, Arrays.asList(
"Europese instelling/Europees agentschap of internationale organisatie"));
return mapping;
}
/**
* @return body activities mapping
*/
private Map<Enum, List<String>> getBodyActivityMapping() {
final Map<Enum, List<String>> mapping = new HashMap<>();
mapping.put(BuyerActivityType.GENERAL_PUBLIC_SERVICES, Arrays.asList("Algemene overheidsdiensten"));
mapping.put(BuyerActivityType.EDUCATION, Arrays.asList("Onderwijs", "Onderwijs Andere: Onderzoek",
"Onderwijs Andere: onderzoek"));
mapping.put(BuyerActivityType.PUBLIC_ORDER_AND_SAFETY, Arrays.asList("Openbare orde en veiligheid"));
mapping.put(BuyerActivityType.HEALTH, Arrays.asList("Gezondheid"));
mapping.put(BuyerActivityType.HOUSING_AND_COMMUNITY_AMENITIES, Arrays.asList(
"Huisvesting en gemeenschappelijke voorzieningen"));
mapping.put(BuyerActivityType.DEFENCE, Arrays.asList("Defensie"));
mapping.put(BuyerActivityType.ENVIRONMENT, Arrays.asList("Milieu"));
mapping.put(BuyerActivityType.ECONOMIC_AND_FINANCIAL_AFFAIRS, Arrays.asList("Economische en financiële zaken"));
mapping.put(BuyerActivityType.RECREATION_CULTURE_AND_RELIGION, Arrays.asList(
"Recreatie, cultuur en godsdienst"));
mapping.put(BuyerActivityType.SOCIAL_PROTECTION, Arrays.asList("Sociale bescherming"));
mapping.put(BuyerActivityType.WATER, Arrays.asList("Andere: Waterschap",
"Algemene overheidsdiensten Andere: Waterschap", "Andere: Waterschap / drinkwater"));
return mapping;
}
/**
* @return form type mapping
*/
private Map<Enum, List<String>> getFormTypeMapping() {
final Map<Enum, List<String>> mapping = new HashMap<>();
mapping.put(PublicationFormType.CONTRACT_NOTICE, Arrays.asList(
"Aankondiging van een opdracht", "Aankondiging van een opdracht - Nutssectoren",
"Vereenvoudigde aankondiging van een overheidsopdracht in het kader van een dynamisch aankoopsysteem",
"Aankondiging van een prijsvraag voor ontwerpen",
"Aankondiging van een opdracht - Overheidsopdrachten - Sociale en andere specifieke diensten",
"Aankondiging van een opdracht voor opdrachten op het gebied van defensie en veiligheid",
"Aankondiging van een opdracht - opdrachten gegund door een concessiehouder die zelf geen " +
"aanbestedende dienst is"));
mapping.put(PublicationFormType.CONTRACT_AWARD, Arrays.asList(
"Aankondiging van een gegunde opdracht", "Aankondiging van een gegunde opdracht - Nutssectoren",
"Aankondiging van een gegunde opdracht - Overheidsopdrachten - Sociale en andere specifieke diensten",
"Resultaten van prijsvraag voor ontwerpen"));
mapping.put(PublicationFormType.PRIOR_INFORMATION_NOTICE, Arrays.asList(
"Vooraankondiging", "Periodieke indicatieve aankondiging - Nutssectoren",
"Vooraankondiging - Overheidsopdrachten - Sociale en andere specifieke diensten",
"Vooraankondiging voor opdrachten op het gebied van defensie en veiligheid"));
mapping.put(PublicationFormType.CONTRACT_UPDATE, Arrays.asList(
"Kennisgeving van aanvullende informatie, informatie over een onvolledige procedure of rectificatie"));
mapping.put(PublicationFormType.OTHER, Arrays.asList(
"Aankondiging in het geval van vrijwillige transparantie vooraf", "Erkenningsregeling - Nutssectoren",
"Marktconsultatie", "Aankondiging door middel van een kopersprofiel",
"Aankondiging van een concessieovereenkomst", "Concessieovereenkomst voor openbare werken",
"Aankondiging van de gunning van een concessieovereenkomst"));
return mapping;
}
}
| timgdavies/backend | digiwhist-worker/src/main/java/eu/digiwhist/worker/nl/clean/TenderNedTenderCleaner.java | 3,078 | // "09/09/2015 Tijdstip: 16:00" | line_comment | nl | package eu.digiwhist.worker.nl.clean;
import eu.digiwhist.worker.clean.BaseDigiwhistTenderCleaner;
import eu.dl.dataaccess.dto.clean.CleanTender;
import eu.dl.dataaccess.dto.codetables.BuyerActivityType;
import eu.dl.dataaccess.dto.codetables.BuyerType;
import eu.dl.dataaccess.dto.codetables.PublicationFormType;
import eu.dl.dataaccess.dto.codetables.TenderSupplyType;
import eu.dl.dataaccess.dto.parsed.ParsedTender;
import eu.dl.worker.clean.plugin.AddressPlugin;
import eu.dl.worker.clean.plugin.AwardCriteriaPlugin;
import eu.dl.worker.clean.plugin.BodyPlugin;
import eu.dl.worker.clean.plugin.DatePlugin;
import eu.dl.worker.clean.plugin.DateTimePlugin;
import eu.dl.worker.clean.plugin.FundingsPlugin;
import eu.dl.worker.clean.plugin.IntegerPlugin;
import eu.dl.worker.clean.plugin.LotPlugin;
import eu.dl.worker.clean.plugin.PublicationPlugin;
import eu.dl.worker.clean.plugin.TenderSupplyTypePlugin;
import java.text.NumberFormat;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Tender cleaner for TenderNed in Netherlands.
*
* @author Marek Mikes
*/
public class TenderNedTenderCleaner extends BaseDigiwhistTenderCleaner {
private static final String VERSION = "1";
private static final Locale LOCALE = new Locale("nl");
private static final NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(LOCALE);
private static final List<DateTimeFormatter> DATE_FORMATTERS = Arrays.asList(
DateTimeFormatter.ofPattern("dd/MM/yyyy"),
DateTimeFormatter.ofPattern("dd-MM-yyyy"));
// date time examples:
// "09/09/2015 Tijdstip:<SUF>
// "05/12/2016 Plaatselijke tijd: 10:00"
// "31/10/2016 Plaatselijke tijd: -"
private static final List<DateTimeFormatter> DATETIME_FORMATTERS = Arrays.asList(
new DateTimeFormatterBuilder()
.appendPattern("dd/MM/yyyy")
.appendLiteral(" Tijdstip: ")
.appendPattern("HH:mm")
.toFormatter(LOCALE),
new DateTimeFormatterBuilder()
.appendPattern("dd/MM/yyyy")
.appendLiteral(" Plaatselijke tijd: ")
//optional time
.optionalStart()
.appendPattern("HH:mm")
.optionalEnd()
//optional not entered time
.optionalStart()
.appendLiteral("-")
.optionalEnd()
//default values for time
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter(LOCALE));
@Override
public final String getVersion() {
return VERSION;
}
@Override
protected final ParsedTender preProcessParsedItem(final ParsedTender parsedItem) {
// remove bid deadline when it has no useful information
if (parsedItem.getBidDeadline() != null && parsedItem.getBidDeadline().equals("- Tijdstip: -")) {
parsedItem.setBidDeadline(null);
}
return parsedItem;
}
@Override
protected final CleanTender postProcessSourceSpecificRules(final ParsedTender parsedTender,
final CleanTender cleanTender) {
return cleanTender;
}
@SuppressWarnings("unchecked")
@Override
protected final void registerSpecificPlugins() {
pluginRegistry
.registerPlugin("integerPlugin", new IntegerPlugin(NUMBER_FORMAT))
.registerPlugin("supplyType", new TenderSupplyTypePlugin(getSupplyTypeMapping()))
.registerPlugin("date", new DatePlugin(DATE_FORMATTERS))
.registerPlugin("datetime", new DateTimePlugin(DATETIME_FORMATTERS))
.registerPlugin("bodies", new BodyPlugin(getBuyerTypeMapping(), getBodyActivityMapping()))
.registerPlugin("lots", new LotPlugin(NUMBER_FORMAT, DATE_FORMATTERS, new HashMap<>()))
.registerPlugin("fundings", new FundingsPlugin(NUMBER_FORMAT))
.registerPlugin("address", new AddressPlugin())
.registerPlugin("awardCriteria", new AwardCriteriaPlugin(NUMBER_FORMAT))
.registerPlugin("publications",
new PublicationPlugin(NUMBER_FORMAT, DATE_FORMATTERS, getFormTypeMapping()));
}
/**
* @return supply type mapping for cleaning process
*/
private static Map<Enum, List<String>> getSupplyTypeMapping() {
final Map<Enum, List<String>> mapping = new HashMap<>();
mapping.put(TenderSupplyType.WORKS, Arrays.asList("(a) Werken"));
mapping.put(TenderSupplyType.SUPPLIES, Arrays.asList("(b) Leveringen"));
mapping.put(TenderSupplyType.SERVICES, Arrays.asList("(c) Diensten"));
return mapping;
}
/**
* @return body type mapping
*/
private static Map<Enum, List<String>> getBuyerTypeMapping() {
final Map<Enum, List<String>> mapping = new HashMap<>();
mapping.put(BuyerType.PUBLIC_BODY, Arrays.asList("Publiekrechtelijke instelling"));
mapping.put(BuyerType.NATIONAL_AGENCY, Arrays.asList("Nationaal of federaal agentschap/bureau"));
mapping.put(BuyerType.NATIONAL_AUTHORITY, Arrays.asList(
"Ministerie of andere nationale of federale instantie, met regionale of plaatselijke " +
"onderverdelingen ervan",
"Ministerie of andere nationale of federale instantie, met inbegrip van regionale of " +
"plaatselijke onderverdelingen"));
mapping.put(BuyerType.REGIONAL_AGENCY, Arrays.asList("Regionaal of plaatselijk agentschap/bureau"));
mapping.put(BuyerType.REGIONAL_AUTHORITY, Arrays.asList("Regionale of plaatselijke instantie",
"Andere: Gemeente", "Andere: gemeente"));
mapping.put(BuyerType.EUROPEAN_AGENCY, Arrays.asList(
"Europese instelling/Europees agentschap of internationale organisatie"));
return mapping;
}
/**
* @return body activities mapping
*/
private Map<Enum, List<String>> getBodyActivityMapping() {
final Map<Enum, List<String>> mapping = new HashMap<>();
mapping.put(BuyerActivityType.GENERAL_PUBLIC_SERVICES, Arrays.asList("Algemene overheidsdiensten"));
mapping.put(BuyerActivityType.EDUCATION, Arrays.asList("Onderwijs", "Onderwijs Andere: Onderzoek",
"Onderwijs Andere: onderzoek"));
mapping.put(BuyerActivityType.PUBLIC_ORDER_AND_SAFETY, Arrays.asList("Openbare orde en veiligheid"));
mapping.put(BuyerActivityType.HEALTH, Arrays.asList("Gezondheid"));
mapping.put(BuyerActivityType.HOUSING_AND_COMMUNITY_AMENITIES, Arrays.asList(
"Huisvesting en gemeenschappelijke voorzieningen"));
mapping.put(BuyerActivityType.DEFENCE, Arrays.asList("Defensie"));
mapping.put(BuyerActivityType.ENVIRONMENT, Arrays.asList("Milieu"));
mapping.put(BuyerActivityType.ECONOMIC_AND_FINANCIAL_AFFAIRS, Arrays.asList("Economische en financiële zaken"));
mapping.put(BuyerActivityType.RECREATION_CULTURE_AND_RELIGION, Arrays.asList(
"Recreatie, cultuur en godsdienst"));
mapping.put(BuyerActivityType.SOCIAL_PROTECTION, Arrays.asList("Sociale bescherming"));
mapping.put(BuyerActivityType.WATER, Arrays.asList("Andere: Waterschap",
"Algemene overheidsdiensten Andere: Waterschap", "Andere: Waterschap / drinkwater"));
return mapping;
}
/**
* @return form type mapping
*/
private Map<Enum, List<String>> getFormTypeMapping() {
final Map<Enum, List<String>> mapping = new HashMap<>();
mapping.put(PublicationFormType.CONTRACT_NOTICE, Arrays.asList(
"Aankondiging van een opdracht", "Aankondiging van een opdracht - Nutssectoren",
"Vereenvoudigde aankondiging van een overheidsopdracht in het kader van een dynamisch aankoopsysteem",
"Aankondiging van een prijsvraag voor ontwerpen",
"Aankondiging van een opdracht - Overheidsopdrachten - Sociale en andere specifieke diensten",
"Aankondiging van een opdracht voor opdrachten op het gebied van defensie en veiligheid",
"Aankondiging van een opdracht - opdrachten gegund door een concessiehouder die zelf geen " +
"aanbestedende dienst is"));
mapping.put(PublicationFormType.CONTRACT_AWARD, Arrays.asList(
"Aankondiging van een gegunde opdracht", "Aankondiging van een gegunde opdracht - Nutssectoren",
"Aankondiging van een gegunde opdracht - Overheidsopdrachten - Sociale en andere specifieke diensten",
"Resultaten van prijsvraag voor ontwerpen"));
mapping.put(PublicationFormType.PRIOR_INFORMATION_NOTICE, Arrays.asList(
"Vooraankondiging", "Periodieke indicatieve aankondiging - Nutssectoren",
"Vooraankondiging - Overheidsopdrachten - Sociale en andere specifieke diensten",
"Vooraankondiging voor opdrachten op het gebied van defensie en veiligheid"));
mapping.put(PublicationFormType.CONTRACT_UPDATE, Arrays.asList(
"Kennisgeving van aanvullende informatie, informatie over een onvolledige procedure of rectificatie"));
mapping.put(PublicationFormType.OTHER, Arrays.asList(
"Aankondiging in het geval van vrijwillige transparantie vooraf", "Erkenningsregeling - Nutssectoren",
"Marktconsultatie", "Aankondiging door middel van een kopersprofiel",
"Aankondiging van een concessieovereenkomst", "Concessieovereenkomst voor openbare werken",
"Aankondiging van de gunning van een concessieovereenkomst"));
return mapping;
}
}
|
43907_0 | package nl.timgoes.transactionservice.transactionservice.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class TransactionServiceConfig {
@LoadBalanced //Moet gebeuren voor euruka anders werkt het niet
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
| timgoes1997/CapitaSelectaJEA6SpringBoot | transaction-service/src/main/java/nl/timgoes/transactionservice/transactionservice/config/TransactionServiceConfig.java | 130 | //Moet gebeuren voor euruka anders werkt het niet | line_comment | nl | package nl.timgoes.transactionservice.transactionservice.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class TransactionServiceConfig {
@LoadBalanced //Moet gebeuren<SUF>
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
|
46632_0 | package com.github.fontys.jms.serializer;
import com.github.fontys.jms.messaging.RequestReply;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class RequestReplySerializer<REQUEST, REPLY> {
private Gson gson; //gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund
private final Class<REQUEST> requestClass;
private final Class<REPLY> replyClass;
public RequestReplySerializer(Class<REQUEST> requestClass, Class<REPLY> replyClass){
this.requestClass = requestClass;
this.replyClass = replyClass;
gson = new GsonBuilder().create();
}
public String requestToString(REQUEST request){
return gson.toJson(request);
}
public REQUEST requestFromString(String str){
return gson.fromJson(str, requestClass);
}
public RequestReply requestReplyFromString(String str){
return gson.fromJson(str, TypeToken.getParameterized(RequestReply.class, requestClass, replyClass).getType());
}
public String requestReplyToString(RequestReply rr){
return gson.toJson(rr);
}
public String replyToString(REPLY reply){
return gson.toJson(reply);
}
public REPLY replyFromString(String str){
return gson.fromJson(str, replyClass);
}
} | timgoes1997/DPI-6 | src/main/com/github/fontys/jms/serializer/RequestReplySerializer.java | 409 | //gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund | line_comment | nl | package com.github.fontys.jms.serializer;
import com.github.fontys.jms.messaging.RequestReply;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class RequestReplySerializer<REQUEST, REPLY> {
private Gson gson; //gebruikte eerst<SUF>
private final Class<REQUEST> requestClass;
private final Class<REPLY> replyClass;
public RequestReplySerializer(Class<REQUEST> requestClass, Class<REPLY> replyClass){
this.requestClass = requestClass;
this.replyClass = replyClass;
gson = new GsonBuilder().create();
}
public String requestToString(REQUEST request){
return gson.toJson(request);
}
public REQUEST requestFromString(String str){
return gson.fromJson(str, requestClass);
}
public RequestReply requestReplyFromString(String str){
return gson.fromJson(str, TypeToken.getParameterized(RequestReply.class, requestClass, replyClass).getType());
}
public String requestReplyToString(RequestReply rr){
return gson.toJson(rr);
}
public String replyToString(REPLY reply){
return gson.toJson(reply);
}
public REPLY replyFromString(String str){
return gson.fromJson(str, replyClass);
}
} |
46693_0 | package com.github.timgoes1997.jms.serializer;
import com.github.timgoes1997.jms.messaging.StandardMessage;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class ObjectSerializer<OBJECT> {
private Gson gson; //gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund
private final Class<OBJECT> objectClass;
public ObjectSerializer(Class<OBJECT> objectClass){
this.objectClass = objectClass;
gson = new GsonBuilder().create();
}
public String objectToString(OBJECT object){
return gson.toJson(object);
}
public OBJECT objectFromString(String str){
return gson.fromJson(str, objectClass);
}
public StandardMessage standardMessageFromString(String str){
return gson.fromJson(str, TypeToken.getParameterized(StandardMessage.class, objectClass).getType());
}
public String standardMessageToString(StandardMessage standardMessage){
return gson.toJson(standardMessage);
}
}
| timgoes1997/DPI-KilometerRijden | Tim-JMS/src/main/com/github/timgoes1997/jms/serializer/ObjectSerializer.java | 313 | //gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund | line_comment | nl | package com.github.timgoes1997.jms.serializer;
import com.github.timgoes1997.jms.messaging.StandardMessage;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class ObjectSerializer<OBJECT> {
private Gson gson; //gebruikte eerst<SUF>
private final Class<OBJECT> objectClass;
public ObjectSerializer(Class<OBJECT> objectClass){
this.objectClass = objectClass;
gson = new GsonBuilder().create();
}
public String objectToString(OBJECT object){
return gson.toJson(object);
}
public OBJECT objectFromString(String str){
return gson.fromJson(str, objectClass);
}
public StandardMessage standardMessageFromString(String str){
return gson.fromJson(str, TypeToken.getParameterized(StandardMessage.class, objectClass).getType());
}
public String standardMessageToString(StandardMessage standardMessage){
return gson.toJson(standardMessage);
}
}
|
46143_2 | package DomumViri.Main;
import DomumViri.Menu;
import DomumViri.Rendering.Renderer;
import DomumViri.Managers.InputManager;
import DomumViri.Managers.AudioManager;
import DomumViri.Entities.Bot;
import DomumViri.Entities.Entity;
import DomumViri.Level.MapInfo;
import DomumViri.Level.MapName;
import DomumViri.Time.Time;
import DomumViri.Time.TimeStatus;
import DomumViri.User.Account;
import DomumViri.World.GameWorld;
import DomumViri.World.MultiPlayer.GameWorldMultiPlayer;
import DomumViri.World.SinglePlayer.GameWorldSinglePlayer;
import java.util.List;
import javafx.animation.AnimationTimer;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.net.InetAddress;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
public class Game {
private AnimationTimer timer;
private int width;
private int height;
private int gameTime;
public static final int SECONDINNANOS = 1000000000;
private int fps;
private long lastFrame;
private long lastSecond;
private long lastFrameMS;
private Stage currentStage;
private GraphicsContext gc;
private InputManager im;
private Renderer renderer;
private boolean fullscreen;
private Menu menu;
private GameWorld world;
private Account account;
private boolean playing;
private boolean multiplayer;
private InetAddress ip;
private int port;
private boolean debugPressed;
private boolean debugTilePositionPressed;
private boolean escapePressed;
private boolean isMoveUpPressed;
public boolean isPlaying() {
return playing;
}
public Game(Stage currentStage, int gameTime, int sceneWidth, int sceneHeight, boolean fullscreen, Account account) {
this.gameTime = gameTime;
this.currentStage = currentStage;
this.width = sceneWidth;
this.height = sceneHeight;
this.fullscreen = fullscreen;
this.account = account;
this.multiplayer = false;
}
public Game(Stage currentStage, int gameTime, int sceneWidth, int sceneHeight, boolean fullscreen, Account account, InetAddress ip, int port) {
this.gameTime = gameTime;
this.currentStage = currentStage;
this.width = sceneWidth;
this.height = sceneHeight;
this.fullscreen = fullscreen;
this.account = account;
this.ip = ip;
this.port = port;
this.multiplayer = true;
}
/**
* Genereert een compleet nieuwe gamescene met een nieuwe gamewereld.
*
* @param renderedWidth Op welk resolutie deze scene moet worden weergeven.
* @param renderedHeight Op welk resolutie deze scene moet worden weergeven.
* @param fullscreen Of deze scene in fullscreen modus moet worden weergeven
* of niet.
* @return
*/
public Scene generateScene(int renderedWidth, int renderedHeight, boolean fullscreen) {
this.fullscreen = fullscreen;
Canvas canvas = new Canvas(width, height); //Maakt een nieuw canvas aan met de bepaalde hoogte en breedte waarop het level wordt gerendert (Dus niet weergeven).
gc = canvas.getGraphicsContext2D();
Group root = new Group();
root.getChildren().add(canvas);
Scene gameScene = new Scene(root);
gameScene.setFill(Color.BLACK);
renderer = new Renderer(gc, width, height, renderedWidth, renderedHeight);
im = new InputManager(gameScene);
if (multiplayer) {
try {
world = new GameWorldMultiPlayer(im, account, ip, port);
} catch (Exception ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Couldn't connect to the given server!");
alert.setHeaderText("A error has been catched with the following information!");
alert.setContentText(ex.getMessage());
alert.showAndWait();
forceStop();
}
} else {
world = new GameWorldSinglePlayer(MapName.Default, MapInfo.Default, im, GameMode.SinglePlayer, account, new Time(System.nanoTime(), gameTime, TimeStatus.Ingame));
}
lastSecond = System.nanoTime(); //De huidige seconde in nanosecondes.
return gameScene;
}
/**
* Hervat een level dat al begonnen is of op pauze is gezet.
*
* @param renderedWidth Op welk resolutie deze scene moet worden weergeven.
* @param renderedHeight Op welk resolutie deze scene moet worden weergeven.
* @param fullscreen Of deze scene in fullscreen modus moet worden weergeven
* of niet.
* @return
*/
public Scene continueScene(int renderedWidth, int renderedHeight, boolean fullscreen) {
this.fullscreen = fullscreen;
Canvas canvas = new Canvas(width, height);
gc = canvas.getGraphicsContext2D();
Group root = new Group();
root.getChildren().add(canvas);
Scene gameScene = new Scene(root);
gameScene.setFill(Color.BLACK);
renderer = new Renderer(gc, width, height, renderedWidth, renderedHeight);
im = new InputManager(gameScene);
resetInputManager();
lastSecond = System.nanoTime();
return gameScene;
}
/**
* Voegt een nieuwe inputmanager toe aan de gameworld.
*/
public void resetInputManager() {
world.resetInputManager(im);
}
/**
* Maakt een nieuwe animatietimer aan (In dit geval de gameloop)
*/
private void setAnimationTimer() {
timer = new AnimationTimer() {
@Override
public void handle(long now) { //now is de huidige tick in nanoseconden.
lastFrameMS = now - lastFrame; //Hoelang de frametime is tussen het huidige frame en de laatste frame.
fps = (int) (SECONDINNANOS / lastFrameMS); //Hoeveel frames er per seconde worden weergeven op het scherm.
currentStage.setTitle("FPS:" + fps + " | DomumViri |");
lastFrame = now;
update(); //Update de gameworld en renderer.
checkFramesAndSeconds(now);
}
@Override
public void start() {
lastFrame = System.nanoTime();
super.start();
}
};
}
/**
* Checkt het frame en stelt de game time in.
*/
private void checkFramesAndSeconds(long now) {
renderer.setDrawCallsFrame(0); //reset de drawcalls van dit frame.
if ((lastSecond + SECONDINNANOS) <= now) { //Kijkt of er een seconde voorbij is.
lastSecond += SECONDINNANOS; //Verhoogt de laatste seconde.
renderer.setDrawCallsSecond(0); //Reset de drawcalls per seconde.
gameTime = world.getTime().getRemainingTime(now);
}
}
/**
* Update de game.
*/
public void update() {
renderer.clear(); //Cleart het scherm van alle drawings.
checkInput(); //Kijkt naar de huidige input.
world.update(lastFrameMS / (float) SECONDINNANOS); //Update de huidige wereld met alle objecten die daar in zitten.
renderer.update(world); //, 0, (height / 2) + 72
String debugLine = " | ScaleX:" + renderer.getScaleX() + " | ScaleY: " + renderer.getScaleY() + " | tileSoorten: "
+ world.getMap().getTileSoorten().size() + " | tiles: " + world.getMap().getTileMap().size()
+ " | drawCallsSecond: " + renderer.getDrawCallsSecond() + " | drawCallsFrame: " + renderer.getDrawCallsFrame() + "| remaining Time: " + gameTime
+ " | status: " + world.getTime().getStatus().toString() + " | falling: " + world.getPlayer().isFalling(); //String die een gedeelte van de huidige gegevens over de game weergeeft.
String posX = " | currentX:" + (world.getPlayer().getTile().getLocation().getX());
String posY = " | currentY:" + (world.getPlayer().getTile().getLocation().getY());
renderer.debugLine(Color.ORANGE, debugLine, 10, 10);
renderer.debugLine(Color.CYAN, posX, 10, 23);
renderer.debugLine(Color.CYAN, posY, 10, 36);
if (gameTime <= 10) { //end game timer voor als er nog minder dan 10 seconden zijn.
//(world.player().getTile().getImage().getWidth() / 4)
if (world.getTime().getStatus() == TimeStatus.Waiting) {
renderer.drawLine(Color.YELLOW, Integer.toString(gameTime), (width / 2), 50);
} else if (world.getTime().getStatus() == TimeStatus.Warmup) {
renderer.drawLine(Color.GREEN, Integer.toString(gameTime), (width / 2), 50);
} else if (world.getTime().getStatus() == TimeStatus.Ingame) {
renderer.drawLine(Color.ORANGERED, Integer.toString(gameTime), (width / 2), 50);
}
}
if (world.getTime().getStatus() == TimeStatus.Finished || world.isStopped()) { //stopt de game.
endGame();
playing = false;
}
if (world.endGame()) {
endGame();
}
}
/**
* Zorgt er voor dat de game stopt.
*/
public void stop() {
timer.stop(); //Stopt de game timer.
//world.shutdown();
menu.changeMenuToPaused(false);
currentStage.show(); //Laat het menu zien.
}
public void forceStop() {
if (timer != null) {
timer.stop();
}
world.shutdown();
menu.changeMenuToPaused(true);
}
/**
* Eindigt het spel
*/
public void endGame() {
world.shutdown();
timer.stop(); //Stopt de game timer.
gameTime = 0;
List<Entity> entiteiten = world.getEntities();
Bot b = null;
for (Entity e : entiteiten) {
if (e instanceof Bot) {
b = (Bot) e;
}
}
playing = false;
menu.gameOver(b, world.getPlayer()); //Laat de pauze knop zien.
currentStage.show(); //Laat het menu zien.
}
/**
* Start de game
*
* @param menu het menu
* @param gameScene de gameScene
*/
public void start(Menu menu, Scene gameScene) {
this.menu = menu;
setAnimationTimer();
currentStage.setScene(gameScene);
currentStage.setFullScreen(fullscreen);
currentStage.show();
timer.start();
playing = true;
}
/**
* Stelt de grootte van de game in
*
* @param width de breedte
* @param height de hoogte
*/
public void setSize(int width, int height) {
this.width = width;
this.height = height;
}
/**
* Checkt de input van de knop o, p en escape voor debuging en terug gaan
* naar het menu.
*/
public void checkInput() {
if (im.isDebug() && !debugPressed) {
renderer.setDebug(!renderer.isDebug());
debugPressed = true;
}
if (!im.isDebug() && debugPressed) {
debugPressed = false;
}
if (im.isDebugTilePosition() && !debugTilePositionPressed) {
renderer.showPositionTilesDebug(!renderer.isDebugTilePosition());
debugTilePositionPressed = true;
}
if (!im.isDebugTilePosition() && debugTilePositionPressed) {
debugTilePositionPressed = false;
}
if (im.isMenu() && !escapePressed) {
stop();
escapePressed = true;
}
if (!im.isMenu() && escapePressed) {
escapePressed = false;
}
if (im.isMoveUp() && !isMoveUpPressed) {
if (!world.getPlayer().isFalling()) {
AudioManager.playJump(menu.getDecibel() * 5);
} else if (!world.getPlayer().hasDoublejumped()) {
AudioManager.playJump(menu.getDecibel() * 5);
}
isMoveUpPressed = true;
}
if (!im.isMoveUp() && isMoveUpPressed) {
isMoveUpPressed = false;
}
}
}
| timgoes1997/DomumViriGithub | DomumViri/src/DomumViri/Main/Game.java | 3,529 | //De huidige seconde in nanosecondes. | line_comment | nl | package DomumViri.Main;
import DomumViri.Menu;
import DomumViri.Rendering.Renderer;
import DomumViri.Managers.InputManager;
import DomumViri.Managers.AudioManager;
import DomumViri.Entities.Bot;
import DomumViri.Entities.Entity;
import DomumViri.Level.MapInfo;
import DomumViri.Level.MapName;
import DomumViri.Time.Time;
import DomumViri.Time.TimeStatus;
import DomumViri.User.Account;
import DomumViri.World.GameWorld;
import DomumViri.World.MultiPlayer.GameWorldMultiPlayer;
import DomumViri.World.SinglePlayer.GameWorldSinglePlayer;
import java.util.List;
import javafx.animation.AnimationTimer;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.net.InetAddress;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
public class Game {
private AnimationTimer timer;
private int width;
private int height;
private int gameTime;
public static final int SECONDINNANOS = 1000000000;
private int fps;
private long lastFrame;
private long lastSecond;
private long lastFrameMS;
private Stage currentStage;
private GraphicsContext gc;
private InputManager im;
private Renderer renderer;
private boolean fullscreen;
private Menu menu;
private GameWorld world;
private Account account;
private boolean playing;
private boolean multiplayer;
private InetAddress ip;
private int port;
private boolean debugPressed;
private boolean debugTilePositionPressed;
private boolean escapePressed;
private boolean isMoveUpPressed;
public boolean isPlaying() {
return playing;
}
public Game(Stage currentStage, int gameTime, int sceneWidth, int sceneHeight, boolean fullscreen, Account account) {
this.gameTime = gameTime;
this.currentStage = currentStage;
this.width = sceneWidth;
this.height = sceneHeight;
this.fullscreen = fullscreen;
this.account = account;
this.multiplayer = false;
}
public Game(Stage currentStage, int gameTime, int sceneWidth, int sceneHeight, boolean fullscreen, Account account, InetAddress ip, int port) {
this.gameTime = gameTime;
this.currentStage = currentStage;
this.width = sceneWidth;
this.height = sceneHeight;
this.fullscreen = fullscreen;
this.account = account;
this.ip = ip;
this.port = port;
this.multiplayer = true;
}
/**
* Genereert een compleet nieuwe gamescene met een nieuwe gamewereld.
*
* @param renderedWidth Op welk resolutie deze scene moet worden weergeven.
* @param renderedHeight Op welk resolutie deze scene moet worden weergeven.
* @param fullscreen Of deze scene in fullscreen modus moet worden weergeven
* of niet.
* @return
*/
public Scene generateScene(int renderedWidth, int renderedHeight, boolean fullscreen) {
this.fullscreen = fullscreen;
Canvas canvas = new Canvas(width, height); //Maakt een nieuw canvas aan met de bepaalde hoogte en breedte waarop het level wordt gerendert (Dus niet weergeven).
gc = canvas.getGraphicsContext2D();
Group root = new Group();
root.getChildren().add(canvas);
Scene gameScene = new Scene(root);
gameScene.setFill(Color.BLACK);
renderer = new Renderer(gc, width, height, renderedWidth, renderedHeight);
im = new InputManager(gameScene);
if (multiplayer) {
try {
world = new GameWorldMultiPlayer(im, account, ip, port);
} catch (Exception ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Couldn't connect to the given server!");
alert.setHeaderText("A error has been catched with the following information!");
alert.setContentText(ex.getMessage());
alert.showAndWait();
forceStop();
}
} else {
world = new GameWorldSinglePlayer(MapName.Default, MapInfo.Default, im, GameMode.SinglePlayer, account, new Time(System.nanoTime(), gameTime, TimeStatus.Ingame));
}
lastSecond = System.nanoTime(); //De huidige<SUF>
return gameScene;
}
/**
* Hervat een level dat al begonnen is of op pauze is gezet.
*
* @param renderedWidth Op welk resolutie deze scene moet worden weergeven.
* @param renderedHeight Op welk resolutie deze scene moet worden weergeven.
* @param fullscreen Of deze scene in fullscreen modus moet worden weergeven
* of niet.
* @return
*/
public Scene continueScene(int renderedWidth, int renderedHeight, boolean fullscreen) {
this.fullscreen = fullscreen;
Canvas canvas = new Canvas(width, height);
gc = canvas.getGraphicsContext2D();
Group root = new Group();
root.getChildren().add(canvas);
Scene gameScene = new Scene(root);
gameScene.setFill(Color.BLACK);
renderer = new Renderer(gc, width, height, renderedWidth, renderedHeight);
im = new InputManager(gameScene);
resetInputManager();
lastSecond = System.nanoTime();
return gameScene;
}
/**
* Voegt een nieuwe inputmanager toe aan de gameworld.
*/
public void resetInputManager() {
world.resetInputManager(im);
}
/**
* Maakt een nieuwe animatietimer aan (In dit geval de gameloop)
*/
private void setAnimationTimer() {
timer = new AnimationTimer() {
@Override
public void handle(long now) { //now is de huidige tick in nanoseconden.
lastFrameMS = now - lastFrame; //Hoelang de frametime is tussen het huidige frame en de laatste frame.
fps = (int) (SECONDINNANOS / lastFrameMS); //Hoeveel frames er per seconde worden weergeven op het scherm.
currentStage.setTitle("FPS:" + fps + " | DomumViri |");
lastFrame = now;
update(); //Update de gameworld en renderer.
checkFramesAndSeconds(now);
}
@Override
public void start() {
lastFrame = System.nanoTime();
super.start();
}
};
}
/**
* Checkt het frame en stelt de game time in.
*/
private void checkFramesAndSeconds(long now) {
renderer.setDrawCallsFrame(0); //reset de drawcalls van dit frame.
if ((lastSecond + SECONDINNANOS) <= now) { //Kijkt of er een seconde voorbij is.
lastSecond += SECONDINNANOS; //Verhoogt de laatste seconde.
renderer.setDrawCallsSecond(0); //Reset de drawcalls per seconde.
gameTime = world.getTime().getRemainingTime(now);
}
}
/**
* Update de game.
*/
public void update() {
renderer.clear(); //Cleart het scherm van alle drawings.
checkInput(); //Kijkt naar de huidige input.
world.update(lastFrameMS / (float) SECONDINNANOS); //Update de huidige wereld met alle objecten die daar in zitten.
renderer.update(world); //, 0, (height / 2) + 72
String debugLine = " | ScaleX:" + renderer.getScaleX() + " | ScaleY: " + renderer.getScaleY() + " | tileSoorten: "
+ world.getMap().getTileSoorten().size() + " | tiles: " + world.getMap().getTileMap().size()
+ " | drawCallsSecond: " + renderer.getDrawCallsSecond() + " | drawCallsFrame: " + renderer.getDrawCallsFrame() + "| remaining Time: " + gameTime
+ " | status: " + world.getTime().getStatus().toString() + " | falling: " + world.getPlayer().isFalling(); //String die een gedeelte van de huidige gegevens over de game weergeeft.
String posX = " | currentX:" + (world.getPlayer().getTile().getLocation().getX());
String posY = " | currentY:" + (world.getPlayer().getTile().getLocation().getY());
renderer.debugLine(Color.ORANGE, debugLine, 10, 10);
renderer.debugLine(Color.CYAN, posX, 10, 23);
renderer.debugLine(Color.CYAN, posY, 10, 36);
if (gameTime <= 10) { //end game timer voor als er nog minder dan 10 seconden zijn.
//(world.player().getTile().getImage().getWidth() / 4)
if (world.getTime().getStatus() == TimeStatus.Waiting) {
renderer.drawLine(Color.YELLOW, Integer.toString(gameTime), (width / 2), 50);
} else if (world.getTime().getStatus() == TimeStatus.Warmup) {
renderer.drawLine(Color.GREEN, Integer.toString(gameTime), (width / 2), 50);
} else if (world.getTime().getStatus() == TimeStatus.Ingame) {
renderer.drawLine(Color.ORANGERED, Integer.toString(gameTime), (width / 2), 50);
}
}
if (world.getTime().getStatus() == TimeStatus.Finished || world.isStopped()) { //stopt de game.
endGame();
playing = false;
}
if (world.endGame()) {
endGame();
}
}
/**
* Zorgt er voor dat de game stopt.
*/
public void stop() {
timer.stop(); //Stopt de game timer.
//world.shutdown();
menu.changeMenuToPaused(false);
currentStage.show(); //Laat het menu zien.
}
public void forceStop() {
if (timer != null) {
timer.stop();
}
world.shutdown();
menu.changeMenuToPaused(true);
}
/**
* Eindigt het spel
*/
public void endGame() {
world.shutdown();
timer.stop(); //Stopt de game timer.
gameTime = 0;
List<Entity> entiteiten = world.getEntities();
Bot b = null;
for (Entity e : entiteiten) {
if (e instanceof Bot) {
b = (Bot) e;
}
}
playing = false;
menu.gameOver(b, world.getPlayer()); //Laat de pauze knop zien.
currentStage.show(); //Laat het menu zien.
}
/**
* Start de game
*
* @param menu het menu
* @param gameScene de gameScene
*/
public void start(Menu menu, Scene gameScene) {
this.menu = menu;
setAnimationTimer();
currentStage.setScene(gameScene);
currentStage.setFullScreen(fullscreen);
currentStage.show();
timer.start();
playing = true;
}
/**
* Stelt de grootte van de game in
*
* @param width de breedte
* @param height de hoogte
*/
public void setSize(int width, int height) {
this.width = width;
this.height = height;
}
/**
* Checkt de input van de knop o, p en escape voor debuging en terug gaan
* naar het menu.
*/
public void checkInput() {
if (im.isDebug() && !debugPressed) {
renderer.setDebug(!renderer.isDebug());
debugPressed = true;
}
if (!im.isDebug() && debugPressed) {
debugPressed = false;
}
if (im.isDebugTilePosition() && !debugTilePositionPressed) {
renderer.showPositionTilesDebug(!renderer.isDebugTilePosition());
debugTilePositionPressed = true;
}
if (!im.isDebugTilePosition() && debugTilePositionPressed) {
debugTilePositionPressed = false;
}
if (im.isMenu() && !escapePressed) {
stop();
escapePressed = true;
}
if (!im.isMenu() && escapePressed) {
escapePressed = false;
}
if (im.isMoveUp() && !isMoveUpPressed) {
if (!world.getPlayer().isFalling()) {
AudioManager.playJump(menu.getDecibel() * 5);
} else if (!world.getPlayer().hasDoublejumped()) {
AudioManager.playJump(menu.getDecibel() * 5);
}
isMoveUpPressed = true;
}
if (!im.isMoveUp() && isMoveUpPressed) {
isMoveUpPressed = false;
}
}
}
|
61206_0 | package com.github.fontys.jms.serializer;
import com.github.fontys.jms.messaging.RequestReply;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class Serializer<REQUEST, REPLY> {
private Gson gson; //gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund
private final Class<REQUEST> requestClass;
private final Class<REPLY> replyClass;
public Serializer(Class<REQUEST> requestClass, Class<REPLY> replyClass){
this.requestClass = requestClass;
this.replyClass = replyClass;
gson = new GsonBuilder().create();
}
public String requestToString(REQUEST request){
return gson.toJson(request);
}
public REQUEST requestFromString(String str){
return gson.fromJson(str, requestClass);
}
public RequestReply requestReplyFromString(String str){
return gson.fromJson(str, TypeToken.getParameterized(RequestReply.class, requestClass, replyClass).getType());
}
public String requestReplyToString(RequestReply rr){
return gson.toJson(rr);
}
public String replyToString(REPLY reply){
return gson.toJson(reply);
}
public REPLY replyFromString(String str){
return gson.fromJson(str, replyClass);
}
} | timgoes1997/NLDSamenwerking | src/main/com/github/fontys/jms/serializer/Serializer.java | 405 | //gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund | line_comment | nl | package com.github.fontys.jms.serializer;
import com.github.fontys.jms.messaging.RequestReply;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class Serializer<REQUEST, REPLY> {
private Gson gson; //gebruikte eerst<SUF>
private final Class<REQUEST> requestClass;
private final Class<REPLY> replyClass;
public Serializer(Class<REQUEST> requestClass, Class<REPLY> replyClass){
this.requestClass = requestClass;
this.replyClass = replyClass;
gson = new GsonBuilder().create();
}
public String requestToString(REQUEST request){
return gson.toJson(request);
}
public REQUEST requestFromString(String str){
return gson.fromJson(str, requestClass);
}
public RequestReply requestReplyFromString(String str){
return gson.fromJson(str, TypeToken.getParameterized(RequestReply.class, requestClass, replyClass).getType());
}
public String requestReplyToString(RequestReply rr){
return gson.toJson(rr);
}
public String replyToString(REPLY reply){
return gson.toJson(reply);
}
public REPLY replyFromString(String str){
return gson.fromJson(str, replyClass);
}
} |
187733_15 | package util;
import bank.dao.AccountDAOJPAImpl;
import bank.domain.Account;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.sql.SQLException;
import static org.junit.Assert.*;
/**
* Created by tim on 16-11-2016.
*/
public class DatabaseTest
{
private final EntityManagerFactory emf = Persistence.createEntityManagerFactory("bankPU");
private EntityManager em;
private DatabaseCleaner dc;
@Before
public void setUp()
throws
Exception
{
em = emf.createEntityManager();
dc = new DatabaseCleaner(em);
}
@After
public void tearDown()
throws
Exception
{
}
@Test
public void Vraag1(){
Account account = new Account(1L);
em.getTransaction().begin();
em.persist(account);
//TODO: verklaar en pas eventueel aan (Verwijzing gedaan in persistence xml)
assertNull(account.getId());
em.getTransaction().commit();
System.out.println("AccountId: " + account.getId());
//TODO: verklaar en pas eventueel aan
assertTrue(account.getId() > 0L);
try
{
dc.clean();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
@Test
public void Vraag2(){
Account account = new Account(111L);
em.getTransaction().begin();
em.persist(account);
assertNull(account.getId());
em.getTransaction().rollback();
// TODO code om te testen dat table account geen records bevat. Hint: bestudeer/gebruik AccountDAOJPAImpl
AccountDAOJPAImpl adao = new AccountDAOJPAImpl(em);
assertEquals(0, adao.findAll().size());
}
@Test
public void Vraag3(){
Long expected = -100L;
Account account = new Account(111L);
account.setId(expected);
em.getTransaction().begin();
em.persist(account);
//TODO: verklaar en pas eventueel aan
assertNotEquals(expected, account.getId());
em.flush();
//TODO: verklaar en pas eventueel aan
assertEquals(expected, account.getId());
em.getTransaction().commit();
//TODO: verklaar en pas eventueel aan
assertNotEquals(expected, account.getId());
}
public void Vraag4(){
Long expectedBalance = 400L;
Account account = new Account(114L);
em.getTransaction().begin();
em.persist(account);
account.setBalance(expectedBalance);
em.getTransaction().commit();
assertEquals(expectedBalance, account.getBalance());
//TODO: verklaar de waarde van account.getBalance
Long acId = account.getId();
account = null;
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
Account found = em2.find(Account.class, acId);
//TODO: verklaar de waarde van found.getBalance
assertEquals(expectedBalance, found.getBalance());
}
public void Vraag5(){
/*
In de vorige opdracht verwijzen de objecten account en found naar dezelfde rij in de database.
Pas een van de objecten aan, persisteer naar de database.
Refresh vervolgens het andere object om de veranderde state uit de database te halen.
Test met asserties dat dit gelukt is.
*/
}
public void Vraag6(){
Account acc = new Account(1L);
Account acc2 = new Account(2L);
Account acc9 = new Account(9L);
// scenario 1
Long balance1 = 100L;
em.getTransaction().begin();
em.persist(acc);
acc.setBalance(balance1);
em.getTransaction().commit();
//TODO: voeg asserties toe om je verwachte waarde van de attributen te verifieren.
//TODO: doe dit zowel voor de bovenstaande java objecten als voor opnieuw bij de entitymanager opgevraagde objecten met overeenkomstig Id.
// scenario 2
Long balance2a = 211L;
acc = new Account(2L);
em.getTransaction().begin();
acc9 = em.merge(acc);
acc.setBalance(balance2a);
acc9.setBalance(balance2a+balance2a);
em.getTransaction().commit();
//TODO: voeg asserties toe om je verwachte waarde van de attributen te verifiëren.
//TODO: doe dit zowel voor de bovenstaande java objecten als voor opnieuw bij de entitymanager opgevraagde objecten met overeenkomstig Id.
// HINT: gebruik acccountDAO.findByAccountNr
// scenario 3
Long balance3b = 322L;
Long balance3c = 333L;
acc = new Account(3L);
em.getTransaction().begin();
acc2 = em.merge(acc);
assertTrue(em.contains(acc)); // verklaar
assertTrue(em.contains(acc2)); // verklaar
assertEquals(acc,acc2); //verklaar
acc2.setBalance(balance3b);
acc.setBalance(balance3c);
em.getTransaction().commit();
//TODO: voeg asserties toe om je verwachte waarde van de attributen te verifiëren.
//TODO: doe dit zowel voor de bovenstaande java objecten als voor opnieuw bij de entitymanager opgevraagde objecten met overeenkomstig Id.
// scenario 4
Account account = new Account(114L);
account.setBalance(450L);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(account);
em.getTransaction().commit();
Account account2 = new Account(114L);
Account tweedeAccountObject = account2;
tweedeAccountObject.setBalance(650l);
assertEquals((Long)650L,account2.getBalance()); //verklaar
account2.setId(account.getId());
em.getTransaction().begin();
account2 = em.merge(account2);
assertSame(account,account2); //verklaar
assertTrue(em.contains(account2)); //verklaar
assertFalse(em.contains(tweedeAccountObject)); //verklaar
tweedeAccountObject.setBalance(850l);
assertEquals((Long)650L,account.getBalance()); //verklaar
assertEquals((Long)650L,account2.getBalance()); //verklaar
em.getTransaction().commit();
em.close();
}
public void Vraag7(){
Account acc1 = new Account(77L);
em.getTransaction().begin();
em.persist(acc1);
em.getTransaction().commit();
//Database bevat nu een account.
// scenario 1
Account accF1;
Account accF2;
accF1 = em.find(Account.class, acc1.getId());
accF2 = em.find(Account.class, acc1.getId());
assertSame(accF1, accF2);
// scenario 2
accF1 = em.find(Account.class, acc1.getId());
em.clear();
accF2 = em.find(Account.class, acc1.getId());
assertSame(accF1, accF2);
//TODO verklaar verschil tussen beide scenario's
}
public void Vraag8(){
Account acc1 = new Account(88L);
em.getTransaction().begin();
em.persist(acc1);
em.getTransaction().commit();
Long id = acc1.getId();
//Database bevat nu een account.
em.remove(acc1);
assertEquals(id, acc1.getId());
Account accFound = em.find(Account.class, id);
assertNull(accFound);
//TODO: verklaar bovenstaande asserts
}
public void Vraag9(){
/*
Opgave 1 heb je uitgevoerd met @GeneratedValue(strategy = GenerationType.IDENTITY)
Voer dezelfde opdracht nu uit met GenerationType SEQUENCE en TABLE.
Verklaar zowel de verschillen in testresultaat als verschillen van de database structuur.
*/
}
} | timgoes1997/SE-projecten | bank/src/test/java/util/DatabaseTest.java | 2,331 | //TODO: voeg asserties toe om je verwachte waarde van de attributen te verifiëren. | line_comment | nl | package util;
import bank.dao.AccountDAOJPAImpl;
import bank.domain.Account;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.sql.SQLException;
import static org.junit.Assert.*;
/**
* Created by tim on 16-11-2016.
*/
public class DatabaseTest
{
private final EntityManagerFactory emf = Persistence.createEntityManagerFactory("bankPU");
private EntityManager em;
private DatabaseCleaner dc;
@Before
public void setUp()
throws
Exception
{
em = emf.createEntityManager();
dc = new DatabaseCleaner(em);
}
@After
public void tearDown()
throws
Exception
{
}
@Test
public void Vraag1(){
Account account = new Account(1L);
em.getTransaction().begin();
em.persist(account);
//TODO: verklaar en pas eventueel aan (Verwijzing gedaan in persistence xml)
assertNull(account.getId());
em.getTransaction().commit();
System.out.println("AccountId: " + account.getId());
//TODO: verklaar en pas eventueel aan
assertTrue(account.getId() > 0L);
try
{
dc.clean();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
@Test
public void Vraag2(){
Account account = new Account(111L);
em.getTransaction().begin();
em.persist(account);
assertNull(account.getId());
em.getTransaction().rollback();
// TODO code om te testen dat table account geen records bevat. Hint: bestudeer/gebruik AccountDAOJPAImpl
AccountDAOJPAImpl adao = new AccountDAOJPAImpl(em);
assertEquals(0, adao.findAll().size());
}
@Test
public void Vraag3(){
Long expected = -100L;
Account account = new Account(111L);
account.setId(expected);
em.getTransaction().begin();
em.persist(account);
//TODO: verklaar en pas eventueel aan
assertNotEquals(expected, account.getId());
em.flush();
//TODO: verklaar en pas eventueel aan
assertEquals(expected, account.getId());
em.getTransaction().commit();
//TODO: verklaar en pas eventueel aan
assertNotEquals(expected, account.getId());
}
public void Vraag4(){
Long expectedBalance = 400L;
Account account = new Account(114L);
em.getTransaction().begin();
em.persist(account);
account.setBalance(expectedBalance);
em.getTransaction().commit();
assertEquals(expectedBalance, account.getBalance());
//TODO: verklaar de waarde van account.getBalance
Long acId = account.getId();
account = null;
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
Account found = em2.find(Account.class, acId);
//TODO: verklaar de waarde van found.getBalance
assertEquals(expectedBalance, found.getBalance());
}
public void Vraag5(){
/*
In de vorige opdracht verwijzen de objecten account en found naar dezelfde rij in de database.
Pas een van de objecten aan, persisteer naar de database.
Refresh vervolgens het andere object om de veranderde state uit de database te halen.
Test met asserties dat dit gelukt is.
*/
}
public void Vraag6(){
Account acc = new Account(1L);
Account acc2 = new Account(2L);
Account acc9 = new Account(9L);
// scenario 1
Long balance1 = 100L;
em.getTransaction().begin();
em.persist(acc);
acc.setBalance(balance1);
em.getTransaction().commit();
//TODO: voeg asserties toe om je verwachte waarde van de attributen te verifieren.
//TODO: doe dit zowel voor de bovenstaande java objecten als voor opnieuw bij de entitymanager opgevraagde objecten met overeenkomstig Id.
// scenario 2
Long balance2a = 211L;
acc = new Account(2L);
em.getTransaction().begin();
acc9 = em.merge(acc);
acc.setBalance(balance2a);
acc9.setBalance(balance2a+balance2a);
em.getTransaction().commit();
//TODO: voeg asserties toe om je verwachte waarde van de attributen te verifiëren.
//TODO: doe dit zowel voor de bovenstaande java objecten als voor opnieuw bij de entitymanager opgevraagde objecten met overeenkomstig Id.
// HINT: gebruik acccountDAO.findByAccountNr
// scenario 3
Long balance3b = 322L;
Long balance3c = 333L;
acc = new Account(3L);
em.getTransaction().begin();
acc2 = em.merge(acc);
assertTrue(em.contains(acc)); // verklaar
assertTrue(em.contains(acc2)); // verklaar
assertEquals(acc,acc2); //verklaar
acc2.setBalance(balance3b);
acc.setBalance(balance3c);
em.getTransaction().commit();
//TODO: voeg<SUF>
//TODO: doe dit zowel voor de bovenstaande java objecten als voor opnieuw bij de entitymanager opgevraagde objecten met overeenkomstig Id.
// scenario 4
Account account = new Account(114L);
account.setBalance(450L);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(account);
em.getTransaction().commit();
Account account2 = new Account(114L);
Account tweedeAccountObject = account2;
tweedeAccountObject.setBalance(650l);
assertEquals((Long)650L,account2.getBalance()); //verklaar
account2.setId(account.getId());
em.getTransaction().begin();
account2 = em.merge(account2);
assertSame(account,account2); //verklaar
assertTrue(em.contains(account2)); //verklaar
assertFalse(em.contains(tweedeAccountObject)); //verklaar
tweedeAccountObject.setBalance(850l);
assertEquals((Long)650L,account.getBalance()); //verklaar
assertEquals((Long)650L,account2.getBalance()); //verklaar
em.getTransaction().commit();
em.close();
}
public void Vraag7(){
Account acc1 = new Account(77L);
em.getTransaction().begin();
em.persist(acc1);
em.getTransaction().commit();
//Database bevat nu een account.
// scenario 1
Account accF1;
Account accF2;
accF1 = em.find(Account.class, acc1.getId());
accF2 = em.find(Account.class, acc1.getId());
assertSame(accF1, accF2);
// scenario 2
accF1 = em.find(Account.class, acc1.getId());
em.clear();
accF2 = em.find(Account.class, acc1.getId());
assertSame(accF1, accF2);
//TODO verklaar verschil tussen beide scenario's
}
public void Vraag8(){
Account acc1 = new Account(88L);
em.getTransaction().begin();
em.persist(acc1);
em.getTransaction().commit();
Long id = acc1.getId();
//Database bevat nu een account.
em.remove(acc1);
assertEquals(id, acc1.getId());
Account accFound = em.find(Account.class, id);
assertNull(accFound);
//TODO: verklaar bovenstaande asserts
}
public void Vraag9(){
/*
Opgave 1 heb je uitgevoerd met @GeneratedValue(strategy = GenerationType.IDENTITY)
Voer dezelfde opdracht nu uit met GenerationType SEQUENCE en TABLE.
Verklaar zowel de verschillen in testresultaat als verschillen van de database structuur.
*/
}
} |
22223_9 | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.nanoTime();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.nanoTime(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " ns.";
}
}
/**
* override van toString methode. Geeft alle tijdsperiode weer.
*/
public String toString() {
StringBuffer buffer = new StringBuffer();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
}
| timgoes1997/jsf32kochfractal | src/timeutil/TimeStamp.java | 1,264 | /**
* override van toString methode. Geeft alle tijdsperiode weer.
*/ | block_comment | nl | package timeutil;
import java.util.LinkedList;
import java.util.List;
/**
* Deze klasse maakt het mogelijk om opeenvolgende tijdsperiodes een naam te
* geven, deze op te slaan en deze daarna te printen (via toString).
*
* Tijdsperiodes worden bepaald door een begintijd en een eindtijd.
*
* begintijd van een periode kan gezet worden door setBegin, de eindtijd kan
* gezet worden door de methode setEind.
*
* Zowel bij de begin- als eindtijd van ee periode kan een String meegegeven
* worden die voor de gebruiker een betekenisvolle aanduiding toevoegt aan dat
* tijdstip. Indien geen string meegegeven wordt, wordt een teller gebruikt, die
* automatisch opgehoogd wordt.
*
* Na het opgeven van een begintijdstip (via setBegin of eenmalig via init ) kan
* t.o.v. dit begintijdstip steeds een eindtijdstip opgegeven worden. Zodoende
* kun je vanaf 1 begintijdstip, meerdere eindtijden opgeven.
*
* Een andere mogelijkheid is om een eindtijdstip direct te laten fungeren als
* begintijdstip voor een volgende periode. Dit kan d.m.v. SetEndBegin of seb.
*
* alle tijdsperiodes kunnen gereset worden dmv init()
*
* @author erik
*
*/
public class TimeStamp {
private static long counter = 0;
private long curBegin;
private String curBeginS;
private List<Period> list;
public TimeStamp() {
TimeStamp.counter = 0;
this.init();
}
/**
* initialiseer klasse. begin met geen tijdsperiodes.
*/
public void init() {
this.curBegin = 0;
this.curBeginS = null;
this.list = new LinkedList();
}
/**
* zet begintijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setBegin() {
this.setBegin(String.valueOf(TimeStamp.counter++));
}
/**
* zet begintijdstip
*
* @param timepoint betekenisvolle identificatie van begintijdstip
*/
public void setBegin(String timepoint) {
this.curBegin = System.nanoTime();
this.curBeginS = timepoint;
}
/**
* zet eindtijdstip. gebruik interne teller voor identificatie van het
* tijdstip
*/
public void setEnd() {
this.setEnd(String.valueOf(TimeStamp.counter++));
}
/**
* zet eindtijdstip
*
* @param timepoint betekenisvolle identificatie vanhet eindtijdstip
*/
public void setEnd(String timepoint) {
this.list.add(new Period(this.curBegin, this.curBeginS, System.nanoTime(), timepoint));
}
/**
* zet eindtijdstip plus begintijdstip
*
* @param timepoint identificatie van het eind- en begintijdstip.
*/
public void setEndBegin(String timepoint) {
this.setEnd(timepoint);
this.setBegin(timepoint);
}
/**
* verkorte versie van setEndBegin
*
* @param timepoint
*/
public void seb(String timepoint) {
this.setEndBegin(timepoint);
}
/**
* interne klasse voor bijhouden van periodes.
*
* @author erik
*
*/
private class Period {
long begin;
String beginS;
long end;
String endS;
public Period(long b, String sb, long e, String se) {
this.setBegin(b, sb);
this.setEnd(e, se);
}
private void setBegin(long b, String sb) {
this.begin = b;
this.beginS = sb;
}
private void setEnd(long e, String se) {
this.end = e;
this.endS = se;
}
@Override
public String toString() {
return "From '" + this.beginS + "' till '" + this.endS + "' is " + (this.end - this.begin) + " ns.";
}
}
/**
* override van toString<SUF>*/
public String toString() {
StringBuffer buffer = new StringBuffer();
for (Period p : this.list) {
buffer.append(p.toString());
buffer.append('\n');
}
return buffer.toString();
}
}
|
30572_3 | package com.misset.opp.model;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.misset.opp.model.constants.OWL;
import com.misset.opp.model.constants.RDF;
import com.misset.opp.ttl.TTLFileType;
import org.apache.commons.io.FileUtils;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.*;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;
/*
Helper class to generate a OntologyModel (Apache Jena) with all imports recursively processed as SubModels
The default import handler doesn't work with the current setup of the Opp Model
*/
@Service
public final class OntologyModelLoader {
private final Project project;
private Collection<File> modelFiles = Collections.emptyList();
private static final String TTL = "TTL";
private static final String MISSET_IT_NL = "https://misset-it.nl";
private static final String REFERENTIEDATA = "http://ontologie.politie.nl/referentiedata";
private final HashMap<Resource, OntModel> ontologies = new HashMap<>();
private ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
private OntologyModel ontologyModel;
public OntologyModelLoader(Project project) {
this.project = project;
}
public static OntologyModelLoader getInstance(@NotNull Project project) {
return project.getService(OntologyModelLoader.class);
}
public OntologyModel read(File file) {
return read(file, indicator);
}
public OntologyModel read(File file, ProgressIndicator indicator) {
this.indicator = indicator;
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
init(file, model);
ontologyModel = new OntologyModel(project);
ontologyModel.init(model);
return ontologyModel;
}
public Collection<File> getModelFiles() {
return modelFiles;
}
public OntologyModel getOntologyModel() {
return ontologyModel;
}
private void setIndicatorText(String text) {
if (indicator == null) {
return;
}
indicator.setText(text);
}
private void setIndicatorText2(String text) {
if (indicator == null) {
return;
}
indicator.setText2(text);
}
private void init(File rootFile, OntModel model) {
if (!rootFile.exists()) {
return;
}
setIndicatorText("Reading ontology file");
// load all other ontology files in the subfolders (recursively)
modelFiles = FileUtils.listFiles(rootFile.getParentFile(), new String[]{TTLFileType.EXTENSION}, true);
modelFiles
.stream()
.filter(file -> !FileUtil.filesEqual(file, rootFile))
.map(file -> {
setIndicatorText2(file.getName());
return file;
})
.map(this::readFile)
.filter(Objects::nonNull)
.map(this::getSubmodel)
.forEach(subModel -> ontologies.put(getOntologyResource(subModel), subModel));
ontologies.keySet().forEach(resource -> model.addLoadedImport(resource.getURI()));
model.read(readFile(rootFile), MISSET_IT_NL, TTL);
processImports(model, new ArrayList<>());
processData(model);
}
private void processImports(OntModel model, List<Resource> processed) {
final Resource ontologyResource = getOntologyResource(model);
// add first to prevent recursion
processed.add(ontologyResource);
final Property imports = model.createProperty(OWL.IMPORTS.getUri());
model.getOntResource(ontologyResource)
.listProperties(imports)
.forEach(statement -> bindImports(model, statement, processed));
}
private void processData(OntModel model) {
// open issue: https://github.com/timmisset/omt-odt-plugin/issues/129
final Resource modelResource = model.getResource(REFERENTIEDATA);
// the data files are loaded separately from the model, they are not part of the ontology import tree
final OntModel data = ontologies.get(modelResource);
if (data != null) {
model.addSubModel(data);
}
}
private void bindImports(OntModel model, Statement statement, List<Resource> processed) {
Optional.ofNullable(statement.getObject())
.map(RDFNode::asResource)
.map(ontologies::get)
.filter(subModel -> !processed.contains(getOntologyResource(subModel)))
.ifPresent(subModel -> {
model.addSubModel(subModel);
processImports(subModel, processed);
});
}
private OntModel getSubmodel(InputStream inputStream) {
final OntModel subModel = ModelFactory.createOntologyModel(OntModelSpec.RDFS_MEM);
subModel.read(inputStream, null, TTL);
return subModel;
}
private Resource getOntologyResource(OntModel model) {
final Property rdtType = model.createProperty(RDF.TYPE.getUri());
final Property ontology = model.createProperty(OWL.ONTOLOGY.getUri());
final ResIterator resIterator = model.listSubjectsWithProperty(rdtType, ontology);
return resIterator.hasNext() ? resIterator.next() : model.createResource();
}
private FileInputStream readFile(File file) {
try {
setIndicatorText2(file.getName());
return new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
| timmisset/omt-odt-plugin | src/main/java/com/misset/opp/model/OntologyModelLoader.java | 1,669 | // open issue: https://github.com/timmisset/omt-odt-plugin/issues/129 | line_comment | nl | package com.misset.opp.model;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.misset.opp.model.constants.OWL;
import com.misset.opp.model.constants.RDF;
import com.misset.opp.ttl.TTLFileType;
import org.apache.commons.io.FileUtils;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.*;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;
/*
Helper class to generate a OntologyModel (Apache Jena) with all imports recursively processed as SubModels
The default import handler doesn't work with the current setup of the Opp Model
*/
@Service
public final class OntologyModelLoader {
private final Project project;
private Collection<File> modelFiles = Collections.emptyList();
private static final String TTL = "TTL";
private static final String MISSET_IT_NL = "https://misset-it.nl";
private static final String REFERENTIEDATA = "http://ontologie.politie.nl/referentiedata";
private final HashMap<Resource, OntModel> ontologies = new HashMap<>();
private ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
private OntologyModel ontologyModel;
public OntologyModelLoader(Project project) {
this.project = project;
}
public static OntologyModelLoader getInstance(@NotNull Project project) {
return project.getService(OntologyModelLoader.class);
}
public OntologyModel read(File file) {
return read(file, indicator);
}
public OntologyModel read(File file, ProgressIndicator indicator) {
this.indicator = indicator;
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
init(file, model);
ontologyModel = new OntologyModel(project);
ontologyModel.init(model);
return ontologyModel;
}
public Collection<File> getModelFiles() {
return modelFiles;
}
public OntologyModel getOntologyModel() {
return ontologyModel;
}
private void setIndicatorText(String text) {
if (indicator == null) {
return;
}
indicator.setText(text);
}
private void setIndicatorText2(String text) {
if (indicator == null) {
return;
}
indicator.setText2(text);
}
private void init(File rootFile, OntModel model) {
if (!rootFile.exists()) {
return;
}
setIndicatorText("Reading ontology file");
// load all other ontology files in the subfolders (recursively)
modelFiles = FileUtils.listFiles(rootFile.getParentFile(), new String[]{TTLFileType.EXTENSION}, true);
modelFiles
.stream()
.filter(file -> !FileUtil.filesEqual(file, rootFile))
.map(file -> {
setIndicatorText2(file.getName());
return file;
})
.map(this::readFile)
.filter(Objects::nonNull)
.map(this::getSubmodel)
.forEach(subModel -> ontologies.put(getOntologyResource(subModel), subModel));
ontologies.keySet().forEach(resource -> model.addLoadedImport(resource.getURI()));
model.read(readFile(rootFile), MISSET_IT_NL, TTL);
processImports(model, new ArrayList<>());
processData(model);
}
private void processImports(OntModel model, List<Resource> processed) {
final Resource ontologyResource = getOntologyResource(model);
// add first to prevent recursion
processed.add(ontologyResource);
final Property imports = model.createProperty(OWL.IMPORTS.getUri());
model.getOntResource(ontologyResource)
.listProperties(imports)
.forEach(statement -> bindImports(model, statement, processed));
}
private void processData(OntModel model) {
// open issue:<SUF>
final Resource modelResource = model.getResource(REFERENTIEDATA);
// the data files are loaded separately from the model, they are not part of the ontology import tree
final OntModel data = ontologies.get(modelResource);
if (data != null) {
model.addSubModel(data);
}
}
private void bindImports(OntModel model, Statement statement, List<Resource> processed) {
Optional.ofNullable(statement.getObject())
.map(RDFNode::asResource)
.map(ontologies::get)
.filter(subModel -> !processed.contains(getOntologyResource(subModel)))
.ifPresent(subModel -> {
model.addSubModel(subModel);
processImports(subModel, processed);
});
}
private OntModel getSubmodel(InputStream inputStream) {
final OntModel subModel = ModelFactory.createOntologyModel(OntModelSpec.RDFS_MEM);
subModel.read(inputStream, null, TTL);
return subModel;
}
private Resource getOntologyResource(OntModel model) {
final Property rdtType = model.createProperty(RDF.TYPE.getUri());
final Property ontology = model.createProperty(OWL.ONTOLOGY.getUri());
final ResIterator resIterator = model.listSubjectsWithProperty(rdtType, ontology);
return resIterator.hasNext() ? resIterator.next() : model.createResource();
}
private FileInputStream readFile(File file) {
try {
setIndicatorText2(file.getName());
return new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
|
130365_1 | package nl.thermans.whereis.auth;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import nl.thermans.whereis.user.Account;
import nl.thermans.whereis.user.AccountRepository;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static nl.thermans.whereis.auth.AuthConstants.*;
// based on https://www.freecodecamp.org/news/how-to-setup-jwt-authorization-and-authentication-in-spring/
public class AuthenticationFilter extends BasicAuthenticationFilter {
private final AccountRepository accountRepository;
public AuthenticationFilter(AuthenticationManager authenticationManager, AccountRepository accountRepository) {
super(authenticationManager);
this.accountRepository = accountRepository;
}
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
String header = req.getHeader(HEADER_STRING);
if (header == null || !header.startsWith(TOKEN_PREFIX)) {
chain.doFilter(req, res);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(header);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
}
private UsernamePasswordAuthenticationToken getAuthentication(String tokenWithPrefix) {
// TODO: nadenken over token expiry enzo. Dus exceptions afvangen
String tokenString = tokenWithPrefix.replace(TOKEN_PREFIX, "");
Token token = new Token(tokenString);
String email = token.getEmail();
if (email == null) {
return null;
}
Optional<Account> account = accountRepository.findByEmail(email);
return account.map(a -> new UsernamePasswordAuthenticationToken(a, null, a.getAuthorities()))
.orElseThrow();
}
}
| timohermans/whereis | api/src/main/java/nl/thermans/whereis/auth/AuthenticationFilter.java | 650 | // TODO: nadenken over token expiry enzo. Dus exceptions afvangen | line_comment | nl | package nl.thermans.whereis.auth;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import nl.thermans.whereis.user.Account;
import nl.thermans.whereis.user.AccountRepository;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static nl.thermans.whereis.auth.AuthConstants.*;
// based on https://www.freecodecamp.org/news/how-to-setup-jwt-authorization-and-authentication-in-spring/
public class AuthenticationFilter extends BasicAuthenticationFilter {
private final AccountRepository accountRepository;
public AuthenticationFilter(AuthenticationManager authenticationManager, AccountRepository accountRepository) {
super(authenticationManager);
this.accountRepository = accountRepository;
}
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
String header = req.getHeader(HEADER_STRING);
if (header == null || !header.startsWith(TOKEN_PREFIX)) {
chain.doFilter(req, res);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(header);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(req, res);
}
private UsernamePasswordAuthenticationToken getAuthentication(String tokenWithPrefix) {
// TODO: nadenken<SUF>
String tokenString = tokenWithPrefix.replace(TOKEN_PREFIX, "");
Token token = new Token(tokenString);
String email = token.getEmail();
if (email == null) {
return null;
}
Optional<Account> account = accountRepository.findByEmail(email);
return account.map(a -> new UsernamePasswordAuthenticationToken(a, null, a.getAuthorities()))
.orElseThrow();
}
}
|
37742_23 | package com.e.pocketleague;
import android.content.Context;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.*;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Database extends AppCompatActivity
{
private static Database databaseInstance;
//const api key
final static private String apiKey = "Your_Riot_API_key";
//interface que en listeners
private static Context context;
private static RequestQueue requestQueue;
private static CustomVolleyListener.CustomVolleyListenerChampion listener = null;
private static CustomVolleyListener.CustomVolleyListenerProfile listener2 = null;
//singelton gebruiken omdat je maar 1 static instnace van het database object wilt hebben
//region singleton
//private constructor.
private Database()
{
//veiligheid check zodat je alleen de instance kan aanspreken
if (databaseInstance != null)
{
throw new RuntimeException("Use getInstance() method ;)");
}
}
//singleton static instance
public static Database getInstance(Context context, CustomVolleyListener.CustomVolleyListenerChampion listener)
{
//checken of er al een instance van is
if (databaseInstance == null)
{
synchronized (Database.class)
{
//nieuwe instance aanmaken als er geen is
if (databaseInstance == null) databaseInstance = new Database();
}
}
//listener en que voor volley
Database.context = context;
Database.listener = listener;
Database.requestQueue = Volley.newRequestQueue(context);
return databaseInstance;
}
//method overloading voor andere interface volley response
public static Database getInstance(Context context, CustomVolleyListener.CustomVolleyListenerProfile listener)
{
//checks if there is already an instance
if (databaseInstance == null)
{
synchronized (Database.class)
{
//create new instance when none available
if (databaseInstance == null) databaseInstance = new Database();
}
}
Database.context = context;
Database.listener2 = listener;
Database.requestQueue = Volley.newRequestQueue(context);
return databaseInstance;
}
//endregion
//Alle champions ophalen
public void getChampions()
{
final String url = "http://ddragon.leagueoflegends.com/cdn/10.7.1/data/en_US/champion.json";
final List<Champion> champions = new ArrayList<Champion>();
//alle champions ophalen uit de leagoe of legends api als jsonObject
try
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
try
{
//data opbject ophalen en in object stoppem
JSONObject data = response.getJSONObject("data");
//
//door alle objecten loopen in het data object
for(int i = 0; i < data.names().length(); i++)
{
//alle gegevens invullen, champion van maken en aan de champions lijst toevoegen
JSONObject champJSON = data.getJSONObject(data.names().getString(i));
String sprite = champJSON.getJSONObject("image").getString("full").toLowerCase();
String name = champJSON.getString("name");
String title = champJSON.getString("title");
int key = champJSON.getInt("key");
String[] tags = new String[champJSON.getJSONArray("tags").length()];
//door de tags loopen
for (int j = 0; j < champJSON.getJSONArray("tags").length(); j++)
{
tags[j] = champJSON.getJSONArray("tags").getString(j);
}
champions.add(new Champion(name,key,title,sprite,tags));
}
//System.out.println("In de response");
//aan de interface meegeven zodat ie opgehaald kan worden vanuit een andere Activity
listener.onVolleyResponse(champions);
}
catch (JSONException e)
{
e.printStackTrace();
}
//System.out.println(champions);
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError e)
{
e.printStackTrace();
}
});
requestQueue.add(jsonObjectRequest);
}
catch (Exception e)
{
e.printStackTrace();
}
//System.out.println("voor de return");
//return champions;
}
//profiel ophalen
public void getProfile(String name)
{
//profiel ophalen uit de leagoe of legends API met de naam uit de settings
final String url = "https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + name;
try
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
try
{
//nieuwe gebruiken maken, gegevens invullen terug sturen
User user = new User(
response.getString("name"),
response.getString("id"),
response.getString("profileIconId"),
response.getString("summonerLevel"));
listener2.onVolleyResponseUser(user);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError e)
{
e.printStackTrace();
}
})
{
//API key meesturen
@Override
public Map getHeaders() throws AuthFailureError
{
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-Riot-Token", apiKey);
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public String testMe()
{
return "TEST SINGLETON";
}
}
| timonvw/PocketLeague | app/src/main/java/com/e/pocketleague/Database.java | 1,874 | //API key meesturen | line_comment | nl | package com.e.pocketleague;
import android.content.Context;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.*;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Database extends AppCompatActivity
{
private static Database databaseInstance;
//const api key
final static private String apiKey = "Your_Riot_API_key";
//interface que en listeners
private static Context context;
private static RequestQueue requestQueue;
private static CustomVolleyListener.CustomVolleyListenerChampion listener = null;
private static CustomVolleyListener.CustomVolleyListenerProfile listener2 = null;
//singelton gebruiken omdat je maar 1 static instnace van het database object wilt hebben
//region singleton
//private constructor.
private Database()
{
//veiligheid check zodat je alleen de instance kan aanspreken
if (databaseInstance != null)
{
throw new RuntimeException("Use getInstance() method ;)");
}
}
//singleton static instance
public static Database getInstance(Context context, CustomVolleyListener.CustomVolleyListenerChampion listener)
{
//checken of er al een instance van is
if (databaseInstance == null)
{
synchronized (Database.class)
{
//nieuwe instance aanmaken als er geen is
if (databaseInstance == null) databaseInstance = new Database();
}
}
//listener en que voor volley
Database.context = context;
Database.listener = listener;
Database.requestQueue = Volley.newRequestQueue(context);
return databaseInstance;
}
//method overloading voor andere interface volley response
public static Database getInstance(Context context, CustomVolleyListener.CustomVolleyListenerProfile listener)
{
//checks if there is already an instance
if (databaseInstance == null)
{
synchronized (Database.class)
{
//create new instance when none available
if (databaseInstance == null) databaseInstance = new Database();
}
}
Database.context = context;
Database.listener2 = listener;
Database.requestQueue = Volley.newRequestQueue(context);
return databaseInstance;
}
//endregion
//Alle champions ophalen
public void getChampions()
{
final String url = "http://ddragon.leagueoflegends.com/cdn/10.7.1/data/en_US/champion.json";
final List<Champion> champions = new ArrayList<Champion>();
//alle champions ophalen uit de leagoe of legends api als jsonObject
try
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
try
{
//data opbject ophalen en in object stoppem
JSONObject data = response.getJSONObject("data");
//
//door alle objecten loopen in het data object
for(int i = 0; i < data.names().length(); i++)
{
//alle gegevens invullen, champion van maken en aan de champions lijst toevoegen
JSONObject champJSON = data.getJSONObject(data.names().getString(i));
String sprite = champJSON.getJSONObject("image").getString("full").toLowerCase();
String name = champJSON.getString("name");
String title = champJSON.getString("title");
int key = champJSON.getInt("key");
String[] tags = new String[champJSON.getJSONArray("tags").length()];
//door de tags loopen
for (int j = 0; j < champJSON.getJSONArray("tags").length(); j++)
{
tags[j] = champJSON.getJSONArray("tags").getString(j);
}
champions.add(new Champion(name,key,title,sprite,tags));
}
//System.out.println("In de response");
//aan de interface meegeven zodat ie opgehaald kan worden vanuit een andere Activity
listener.onVolleyResponse(champions);
}
catch (JSONException e)
{
e.printStackTrace();
}
//System.out.println(champions);
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError e)
{
e.printStackTrace();
}
});
requestQueue.add(jsonObjectRequest);
}
catch (Exception e)
{
e.printStackTrace();
}
//System.out.println("voor de return");
//return champions;
}
//profiel ophalen
public void getProfile(String name)
{
//profiel ophalen uit de leagoe of legends API met de naam uit de settings
final String url = "https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" + name;
try
{
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
try
{
//nieuwe gebruiken maken, gegevens invullen terug sturen
User user = new User(
response.getString("name"),
response.getString("id"),
response.getString("profileIconId"),
response.getString("summonerLevel"));
listener2.onVolleyResponseUser(user);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError e)
{
e.printStackTrace();
}
})
{
//API key<SUF>
@Override
public Map getHeaders() throws AuthFailureError
{
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-Riot-Token", apiKey);
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public String testMe()
{
return "TEST SINGLETON";
}
}
|
1625_5 | /**
* Created by Sneeuwpopsneeuw on 12-Apr-16.
*/
public class Problem007_10001stPrime {
public static void main (String args[]) {
magic();
}
public static void magic() {
long max = 999999999; // if it goes wrong it will stop here
int m = 1; // number
int counter = 0; // amount of counters
for (int i = 2; i <= max; i++) { // bijna infinite loop met build in stop
counter = 0;
for (int n = 2; n < i; n++)
if (i % n == 0)
counter++;
if (counter == 0) { // dit is een prime
System.out.println(m+" : "+i);
m++;
}
if (m == (10001 + 1)) { // als we bij de nummertje 10001 zijn geef het antwoord
System.out.println("Answere = " + i);
break;
}
}
}
}
/*
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6^th prime is 13.
What is the 10001^st prime number?
*/ | timostrating/ProjectEuler | java/Problem007_10001stPrime.java | 346 | // als we bij de nummertje 10001 zijn geef het antwoord | line_comment | nl | /**
* Created by Sneeuwpopsneeuw on 12-Apr-16.
*/
public class Problem007_10001stPrime {
public static void main (String args[]) {
magic();
}
public static void magic() {
long max = 999999999; // if it goes wrong it will stop here
int m = 1; // number
int counter = 0; // amount of counters
for (int i = 2; i <= max; i++) { // bijna infinite loop met build in stop
counter = 0;
for (int n = 2; n < i; n++)
if (i % n == 0)
counter++;
if (counter == 0) { // dit is een prime
System.out.println(m+" : "+i);
m++;
}
if (m == (10001 + 1)) { // als we<SUF>
System.out.println("Answere = " + i);
break;
}
}
}
}
/*
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6^th prime is 13.
What is the 10001^st prime number?
*/ |
7424_0 | package GUI;
import game_util.Arcade;
import game_util.Arcade.GameFactory;
import game_util.Arcade.PlayerFactory;
import game_util.Arcade.RefereeFactory;
import game_util.GameRules;
import game_util.GameRules.GameState;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.ImageCursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import network.Connection;
import reversi.Reversi;
import tic_tac_toe.TicTacToe;
import util.CallbackWithParam;
import util.CompositionRoot;
import util.StringUtils;
import java.util.ArrayList;
public class PlayField {
private static final int GAME_VIEW_SIZE = 600;
// Images
private static Image kermit = new Image("GUI/pictures/kermitPiece.gif", 60, 60, false,true),
o = new Image("GUI/pictures/o.png", 150, 150, false, true),
x = new Image("GUI/pictures/x.png", 150, 150, false, true),
black = new Image("GUI/pictures/blackPiece.png", 60, 60, false, true),
white = new Image("GUI/pictures/whitePiece.png", 60, 60, false, true);
private VBox[] panes;
public volatile int guiPlayerInput = -1; // MOET -1 zijn in het begin GuiPlayer heeft infiniate loop op de verandering van deze variable
private Scene scene;
private Label player1;
private Label player2;
private Label currentPlayer;
private HBox currentPlayerPane, timerPane;
private boolean switching = true;
private GameRules gameRules;
private boolean guiPlayerIsPlaying = false;
private VBox winPane;
private PlayField(int boardSize, GameRules gameRules) { this(boardSize, boardSize, gameRules); }
private PlayField(int rows, int columns, GameRules gameRules) {
CompositionRoot.getInstance().lobby.playField = this;
this.gameRules = gameRules;
GridPane gridPane = new GridPane();
gridPane.setStyle("-fx-background-color: white;");
// Current player
currentPlayer = new Label("");
currentPlayer.setStyle("-fx-font-size: 3em;");
currentPlayer.setPadding(new Insets(10, 0,0,40));
currentPlayerPane = new HBox();
currentPlayerPane.getChildren().add(currentPlayer);
// Timer
timerPane = new HBox();
timerPane.setPadding(new Insets(10, 350,0,0));
timerPane.getChildren().add(createTimer());
BorderPane top = new BorderPane();
top.setStyle("-fx-background-color: white; -fx-border-width: 0 0 2 0; -fx-border-color: black;");
top.setLeft(currentPlayerPane);
top.setRight(timerPane);
GridPane forfeitButtonPane = new GridPane();
gridPane.setPadding(new Insets(15,15,15,15));
forfeitButtonPane.setPadding(new Insets(25,45,25,45));
// forfeit button
Button forfeitButton = new Button("Opgeven");
forfeitButton.setId("button1");
// Player List
player1 = new Label("");
player2 = new Label("");
player1.setPadding(new Insets(10, 20, 0, 20));
player2.setPadding(new Insets(10, 20, 0, 20));
player1.setStyle("-fx-font-size: 2em;");
player2.setStyle("-fx-font-size: 2em;");
ImageView blackGamePiece = new ImageView(black);
ImageView whiteGamePiece = new ImageView(white);
VBox scorePane = new VBox();
gridPane.add(blackGamePiece, 0,0);
gridPane.add(whiteGamePiece, 0,1);
gridPane.add(player1, 1,0);
gridPane.add(player2, 1,1);
forfeitButtonPane.add(forfeitButton, 0,0);
gridPane.add(forfeitButtonPane, 0,4, 2,1);
gridPane.getStylesheets().add("GUI/playFieldStyle.css");
scorePane.getChildren().addAll(gridPane);
GridPane game = new GridPane();
game.setAlignment(Pos.CENTER);
panes = new VBox[rows * columns];
game.getStyleClass().add("game-grid");
for (int x = 0; x < columns; x++)
game.getColumnConstraints().add(new ColumnConstraints((GAME_VIEW_SIZE / columns)));
for (int y = 0; y < rows; y++)
game.getRowConstraints().add(new RowConstraints((GAME_VIEW_SIZE / rows)));
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
VBox pane = new VBox();
pane.setAlignment(Pos.CENTER);
final int total = y * rows + x; // This is required to be final so that the setOnMouseReleased lambda can use the memory
panes[total] = pane;
pane.setOnMouseReleased(e -> {
if (guiPlayerIsPlaying) {
System.out.println("GuiPlayer clicked on: ("+total % rows+", " +total / columns+") i = "+total);
setGuiPlayerInput(total);
}
});
if (gameRules instanceof TicTacToe) {
pane.getStyleClass().add("game-tic-grid-cell");
}
else if (gameRules instanceof Reversi){
pane.getStyleClass().add("game-grid-cell");
}
if (x == 0) { pane.getStyleClass().add("first-column"); }
if (y == 0) { pane.getStyleClass().add("first-row"); }
game.add(pane, x, y);
}
}
BorderPane totalPane = new BorderPane();
totalPane.setStyle("-fx-background-color: white;");
totalPane.setTop(top);
totalPane.setCenter(game);
totalPane.setRight(scorePane);
scene = new Scene(totalPane, 1000, 700, Color.WHITE);
scene.getStylesheets().add("/GUI/game.css");
forfeitButton.setOnAction(event -> CompositionRoot.getInstance().connection.getToServer().setForfeit());
}
private static ImageView getPicture(String player) {
ImageView imageView = null;
if (player.equals("x")) { imageView = new ImageView(x); }
if (player.equals("o")) { imageView = new ImageView(o); }
if (player.equals("black")) { imageView = new ImageView(black); }
if (player.equals("white")) { imageView = new ImageView(white); }
if (player.equals("kermit")) { imageView = new ImageView(kermit); }
return imageView;
}
private void setPicture(GameRules games, int i, int player) {
if (games instanceof TicTacToe) {
panes[i].getChildren().add(getPicture((player == 1) ? "x" : "o"));
}
else if (games instanceof Reversi) {
panes[i].getChildren().add(getPicture((player == 1) ? "black" : "white"));
}
System.out.println("zet " + i + " voor player " + player);
}
private void displayWinScreen(GameState gamestate) {
winPane = new VBox();
winPane.getStylesheets().add("GUI/playFieldStyle.css");
winPane.setAlignment(Pos.CENTER);
Label winningPlayer;
if (gamestate == GameState.PLAYER_1_WINS) {
if (gameRules.getPlayer(0).getName() != null) {
if(gameRules.getPlayer(0).getName().equals(LoginPane.username)) {
winningPlayer = new Label("Je hebt gewonnen!");
setWinStyle();
} else {
winningPlayer = new Label("Je hebt verloren!");
setLoseStyle();
}
} else {
winningPlayer = new Label("Speler 1 heeft gewonnen!");
}
} else if (gamestate == GameState.PLAYER_2_WINS) {
if (gameRules.getPlayer(1).getName() != null) {
if (gameRules.getPlayer(1).getName().equals(LoginPane.username)) {
winningPlayer = new Label("Je hebt gewonnen!");
setWinStyle();
} else {
winningPlayer = new Label("Je hebt verloren!");
setLoseStyle();
}
} else {
winningPlayer = new Label("Speler 2 heeft gewonnen!");
}
} else { // else if (gamestate == GameState.DRAW)
winningPlayer = new Label("Het is gelijk spel geworden!");
winPane.setStyle("-fx-background-image: url(\"GUI/pictures/pokemonHand.gif\");\n" +
"-fx-background-repeat: stretch; \n" +
"-fx-background-size: 1000 700;\n" +
"-fx-background-position: center center;\n" +
"-fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0);");
}
winningPlayer.setStyle("-fx-font-size: 6em; -fx-text-fill: white;");
winPane.getChildren().add(winningPlayer);
Label padLab = new Label("");
Button continueTournament = new Button("Doorgaan met het toernooi");
Button back = new Button("Terug naar lobby");
continueTournament.setOnAction(e -> {
Connection connection = CompositionRoot.getInstance().connection;
connection.getToServer().subscribeGame("Reversi");
BorderPane QueuePane = new QueuePane(true);
Scene scene = new Scene(QueuePane, 576, 316);
CompositionRoot.getInstance().lobby.setScene(scene);
});
back.setOnAction(e -> {
GridPane lobby = new LobbyPane();
Scene scene1 = new Scene(lobby, 576, 316);
Image cursor = new Image("GUI/pictures/kermitCursor.png");
scene1.setCursor(new ImageCursor(cursor));
CompositionRoot.getInstance().lobby.setScene(scene1);
});
winPane.getChildren().addAll(continueTournament, padLab, back);
Scene winScene = new Scene(winPane, 1000, 700);
CompositionRoot.getInstance().lobby.setScene(winScene);
}
public Scene getScene() { return scene; }
private void setWinStyle(){
winPane.setStyle("-fx-background-image: url(\"GUI/pictures/kermitDance.gif\");;\n" +
" -fx-background-repeat: stretch; \n" +
" -fx-background-size: 1000 700;\n" +
" -fx-background-position: center center;\n");
}
private void setLoseStyle(){
winPane.setStyle("-fx-background-image: url(\"GUI/pictures/kermitDark.gif\");\n" +
"-fx-background-repeat: stretch; \n" +
"-fx-background-size: 1000 700;\n" +
"-fx-background-position: center center;\n" +
"-fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0);");
}
private ArrayList<Integer> lijstje = new ArrayList<>();
private void setGuiPlayerInput(int position) {
guiPlayerInput = position;
guiPlayerIsPlaying = false;
for (int index : lijstje)
panes[index].getChildren().remove(0);
lijstje.clear();
}
public void currentTurnIsGuiPlayersTurn() {
Platform.runLater( () -> {
guiPlayerIsPlaying = true;
int playerNr = 2; // TODO HARDCODED
if (gameRules instanceof Reversi) {
Reversi reversi = (Reversi) gameRules;
for (int i=0; i<reversi.openPositions.size(playerNr); i++) {
int index = reversi.openPositions.get(i, playerNr);
panes[index].getChildren().add(getPicture("kermit"));
lijstje.add(index);
}
}
});
}
public void resetGuiPlayerInput() {
guiPlayerInput = -1;
}
private void redraw() {
if (gameRules instanceof Reversi) { // TODO remove if possible
if (gameRules.getPlayer(0).getName() != null) {
player1.setText(StringUtils.capitalize(gameRules.getPlayer(0).getName()));
player2.setText(StringUtils.capitalize(gameRules.getPlayer(1).getName()));
currentPlayerPane.getChildren().set(0, getCurrentPlayer());
}
timerPane.getChildren().set(0,createTimer());
Reversi reversi = (Reversi) gameRules;
for (VBox pane : panes) pane.getChildren().clear();
for (int i=0; i<panes.length; i++) {
if (reversi.board.get(i) == 1)
panes[i].getChildren().add(getPicture("black"));
if (reversi.board.get(i) == 2)
panes[i].getChildren().add(getPicture("white"));
}
}
}
public enum StandardGameType {
OFFLINE_AI_VS_PLAYER(RefereeFactory.DefaultReferee, PlayerFactory.BestAvailableAI, PlayerFactory.GUIPlayer),
// OFFLINE_PLAYER_VS_AI(RefereeFactory.DefaultReferee, PlayerFactory.GUIPlayer, PlayerFactory.BestAvailableAI),
ONLINE_AI_VS_REMOTE(RefereeFactory.NetworkedReferee, PlayerFactory.BestAvailableAI, PlayerFactory.RemotePlayer),
ONLINE_HUMAN_VS_REMOTE(RefereeFactory.NetworkedReferee, PlayerFactory.BestAvailableAI, PlayerFactory.HumanPlayer),
ONLINE_REMOTE_VS_AI(RefereeFactory.NetworkedReferee, PlayerFactory.RemotePlayer, PlayerFactory.BestAvailableAI),
ONLINE_REMOTE_VS_HUMAN(RefereeFactory.NetworkedReferee, PlayerFactory.RemotePlayer, PlayerFactory.HumanPlayer);
public final RefereeFactory refereeFactory;
public final PlayerFactory first;
public final PlayerFactory second;
StandardGameType(RefereeFactory refereeFactory, PlayerFactory first, PlayerFactory second) {
this.refereeFactory = refereeFactory;
this.first = first;
this.second = second;
}
}
public static PlayField createGameAndPlayField(GameFactory gameFactory, StandardGameType standardGameType) {
return createGameAndPlayField(gameFactory, standardGameType, (e)->{} );
}
public static PlayField createGameAndPlayField(GameFactory gameFactory, StandardGameType standardGameType, CallbackWithParam<GameRules> BeforeGameStart) {
Arcade arcade = CompositionRoot.getInstance().arcade;
GameRules game = arcade.createGame(gameFactory, standardGameType.refereeFactory, standardGameType.first, standardGameType.second);
PlayField playField = new PlayField(gameFactory.boardSize, game);
BeforeGameStart.callback(game);
registerDefaultCallBacks(game, playField);
new Thread(game).start();
return playField;
}
private Label createTimer() {
Integer startTime = 10;
Label timerLabel = new Label();
Timeline timeline = new Timeline();
IntegerProperty timeSeconds = new SimpleIntegerProperty(startTime);
timerLabel.textProperty().bind(timeSeconds.asString());
timerLabel.setTextFill(Color.BLACK);
timerLabel.setStyle("-fx-font-size: 3em;");
timeSeconds.set(startTime);
timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(startTime + 1), new KeyValue(timeSeconds, 0)));
timeline.playFromStart();
return timerLabel;
}
private Label getCurrentPlayer() {
if(switching) {
currentPlayer.setText("Aan zet: " + StringUtils.capitalize(gameRules.getPlayer(0).getName()));
switching = false;
} else {
currentPlayer.setText("Aan zet: " + StringUtils.capitalize(gameRules.getPlayer(1).getName()));
switching = true;
}
return currentPlayer;
}
private static void registerDefaultCallBacks(GameRules game, PlayField playField) {
Platform.runLater(playField::redraw); // TODO this is a hack
game.onValidMovePlayed.register((pair0 -> {
Platform.runLater(() -> playField.setPicture(game, pair0.getKey(), pair0.getValue()));
if (game instanceof Reversi) {
Platform.runLater(playField::redraw); // TODO this is a hack
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
game.onGameEnded.register(() -> Platform.runLater(() -> playField.displayWinScreen(game.getGameState())));
game.onValidMovePlayed.register(i -> System.out.println(game));
}
}
| timostrating/reversi_ai | src/GUI/PlayField.java | 5,005 | // MOET -1 zijn in het begin GuiPlayer heeft infiniate loop op de verandering van deze variable | line_comment | nl | package GUI;
import game_util.Arcade;
import game_util.Arcade.GameFactory;
import game_util.Arcade.PlayerFactory;
import game_util.Arcade.RefereeFactory;
import game_util.GameRules;
import game_util.GameRules.GameState;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.ImageCursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.util.Duration;
import network.Connection;
import reversi.Reversi;
import tic_tac_toe.TicTacToe;
import util.CallbackWithParam;
import util.CompositionRoot;
import util.StringUtils;
import java.util.ArrayList;
public class PlayField {
private static final int GAME_VIEW_SIZE = 600;
// Images
private static Image kermit = new Image("GUI/pictures/kermitPiece.gif", 60, 60, false,true),
o = new Image("GUI/pictures/o.png", 150, 150, false, true),
x = new Image("GUI/pictures/x.png", 150, 150, false, true),
black = new Image("GUI/pictures/blackPiece.png", 60, 60, false, true),
white = new Image("GUI/pictures/whitePiece.png", 60, 60, false, true);
private VBox[] panes;
public volatile int guiPlayerInput = -1; // MOET -1<SUF>
private Scene scene;
private Label player1;
private Label player2;
private Label currentPlayer;
private HBox currentPlayerPane, timerPane;
private boolean switching = true;
private GameRules gameRules;
private boolean guiPlayerIsPlaying = false;
private VBox winPane;
private PlayField(int boardSize, GameRules gameRules) { this(boardSize, boardSize, gameRules); }
private PlayField(int rows, int columns, GameRules gameRules) {
CompositionRoot.getInstance().lobby.playField = this;
this.gameRules = gameRules;
GridPane gridPane = new GridPane();
gridPane.setStyle("-fx-background-color: white;");
// Current player
currentPlayer = new Label("");
currentPlayer.setStyle("-fx-font-size: 3em;");
currentPlayer.setPadding(new Insets(10, 0,0,40));
currentPlayerPane = new HBox();
currentPlayerPane.getChildren().add(currentPlayer);
// Timer
timerPane = new HBox();
timerPane.setPadding(new Insets(10, 350,0,0));
timerPane.getChildren().add(createTimer());
BorderPane top = new BorderPane();
top.setStyle("-fx-background-color: white; -fx-border-width: 0 0 2 0; -fx-border-color: black;");
top.setLeft(currentPlayerPane);
top.setRight(timerPane);
GridPane forfeitButtonPane = new GridPane();
gridPane.setPadding(new Insets(15,15,15,15));
forfeitButtonPane.setPadding(new Insets(25,45,25,45));
// forfeit button
Button forfeitButton = new Button("Opgeven");
forfeitButton.setId("button1");
// Player List
player1 = new Label("");
player2 = new Label("");
player1.setPadding(new Insets(10, 20, 0, 20));
player2.setPadding(new Insets(10, 20, 0, 20));
player1.setStyle("-fx-font-size: 2em;");
player2.setStyle("-fx-font-size: 2em;");
ImageView blackGamePiece = new ImageView(black);
ImageView whiteGamePiece = new ImageView(white);
VBox scorePane = new VBox();
gridPane.add(blackGamePiece, 0,0);
gridPane.add(whiteGamePiece, 0,1);
gridPane.add(player1, 1,0);
gridPane.add(player2, 1,1);
forfeitButtonPane.add(forfeitButton, 0,0);
gridPane.add(forfeitButtonPane, 0,4, 2,1);
gridPane.getStylesheets().add("GUI/playFieldStyle.css");
scorePane.getChildren().addAll(gridPane);
GridPane game = new GridPane();
game.setAlignment(Pos.CENTER);
panes = new VBox[rows * columns];
game.getStyleClass().add("game-grid");
for (int x = 0; x < columns; x++)
game.getColumnConstraints().add(new ColumnConstraints((GAME_VIEW_SIZE / columns)));
for (int y = 0; y < rows; y++)
game.getRowConstraints().add(new RowConstraints((GAME_VIEW_SIZE / rows)));
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
VBox pane = new VBox();
pane.setAlignment(Pos.CENTER);
final int total = y * rows + x; // This is required to be final so that the setOnMouseReleased lambda can use the memory
panes[total] = pane;
pane.setOnMouseReleased(e -> {
if (guiPlayerIsPlaying) {
System.out.println("GuiPlayer clicked on: ("+total % rows+", " +total / columns+") i = "+total);
setGuiPlayerInput(total);
}
});
if (gameRules instanceof TicTacToe) {
pane.getStyleClass().add("game-tic-grid-cell");
}
else if (gameRules instanceof Reversi){
pane.getStyleClass().add("game-grid-cell");
}
if (x == 0) { pane.getStyleClass().add("first-column"); }
if (y == 0) { pane.getStyleClass().add("first-row"); }
game.add(pane, x, y);
}
}
BorderPane totalPane = new BorderPane();
totalPane.setStyle("-fx-background-color: white;");
totalPane.setTop(top);
totalPane.setCenter(game);
totalPane.setRight(scorePane);
scene = new Scene(totalPane, 1000, 700, Color.WHITE);
scene.getStylesheets().add("/GUI/game.css");
forfeitButton.setOnAction(event -> CompositionRoot.getInstance().connection.getToServer().setForfeit());
}
private static ImageView getPicture(String player) {
ImageView imageView = null;
if (player.equals("x")) { imageView = new ImageView(x); }
if (player.equals("o")) { imageView = new ImageView(o); }
if (player.equals("black")) { imageView = new ImageView(black); }
if (player.equals("white")) { imageView = new ImageView(white); }
if (player.equals("kermit")) { imageView = new ImageView(kermit); }
return imageView;
}
private void setPicture(GameRules games, int i, int player) {
if (games instanceof TicTacToe) {
panes[i].getChildren().add(getPicture((player == 1) ? "x" : "o"));
}
else if (games instanceof Reversi) {
panes[i].getChildren().add(getPicture((player == 1) ? "black" : "white"));
}
System.out.println("zet " + i + " voor player " + player);
}
private void displayWinScreen(GameState gamestate) {
winPane = new VBox();
winPane.getStylesheets().add("GUI/playFieldStyle.css");
winPane.setAlignment(Pos.CENTER);
Label winningPlayer;
if (gamestate == GameState.PLAYER_1_WINS) {
if (gameRules.getPlayer(0).getName() != null) {
if(gameRules.getPlayer(0).getName().equals(LoginPane.username)) {
winningPlayer = new Label("Je hebt gewonnen!");
setWinStyle();
} else {
winningPlayer = new Label("Je hebt verloren!");
setLoseStyle();
}
} else {
winningPlayer = new Label("Speler 1 heeft gewonnen!");
}
} else if (gamestate == GameState.PLAYER_2_WINS) {
if (gameRules.getPlayer(1).getName() != null) {
if (gameRules.getPlayer(1).getName().equals(LoginPane.username)) {
winningPlayer = new Label("Je hebt gewonnen!");
setWinStyle();
} else {
winningPlayer = new Label("Je hebt verloren!");
setLoseStyle();
}
} else {
winningPlayer = new Label("Speler 2 heeft gewonnen!");
}
} else { // else if (gamestate == GameState.DRAW)
winningPlayer = new Label("Het is gelijk spel geworden!");
winPane.setStyle("-fx-background-image: url(\"GUI/pictures/pokemonHand.gif\");\n" +
"-fx-background-repeat: stretch; \n" +
"-fx-background-size: 1000 700;\n" +
"-fx-background-position: center center;\n" +
"-fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0);");
}
winningPlayer.setStyle("-fx-font-size: 6em; -fx-text-fill: white;");
winPane.getChildren().add(winningPlayer);
Label padLab = new Label("");
Button continueTournament = new Button("Doorgaan met het toernooi");
Button back = new Button("Terug naar lobby");
continueTournament.setOnAction(e -> {
Connection connection = CompositionRoot.getInstance().connection;
connection.getToServer().subscribeGame("Reversi");
BorderPane QueuePane = new QueuePane(true);
Scene scene = new Scene(QueuePane, 576, 316);
CompositionRoot.getInstance().lobby.setScene(scene);
});
back.setOnAction(e -> {
GridPane lobby = new LobbyPane();
Scene scene1 = new Scene(lobby, 576, 316);
Image cursor = new Image("GUI/pictures/kermitCursor.png");
scene1.setCursor(new ImageCursor(cursor));
CompositionRoot.getInstance().lobby.setScene(scene1);
});
winPane.getChildren().addAll(continueTournament, padLab, back);
Scene winScene = new Scene(winPane, 1000, 700);
CompositionRoot.getInstance().lobby.setScene(winScene);
}
public Scene getScene() { return scene; }
private void setWinStyle(){
winPane.setStyle("-fx-background-image: url(\"GUI/pictures/kermitDance.gif\");;\n" +
" -fx-background-repeat: stretch; \n" +
" -fx-background-size: 1000 700;\n" +
" -fx-background-position: center center;\n");
}
private void setLoseStyle(){
winPane.setStyle("-fx-background-image: url(\"GUI/pictures/kermitDark.gif\");\n" +
"-fx-background-repeat: stretch; \n" +
"-fx-background-size: 1000 700;\n" +
"-fx-background-position: center center;\n" +
"-fx-effect: dropshadow(three-pass-box, black, 30, 0.5, 0, 0);");
}
private ArrayList<Integer> lijstje = new ArrayList<>();
private void setGuiPlayerInput(int position) {
guiPlayerInput = position;
guiPlayerIsPlaying = false;
for (int index : lijstje)
panes[index].getChildren().remove(0);
lijstje.clear();
}
public void currentTurnIsGuiPlayersTurn() {
Platform.runLater( () -> {
guiPlayerIsPlaying = true;
int playerNr = 2; // TODO HARDCODED
if (gameRules instanceof Reversi) {
Reversi reversi = (Reversi) gameRules;
for (int i=0; i<reversi.openPositions.size(playerNr); i++) {
int index = reversi.openPositions.get(i, playerNr);
panes[index].getChildren().add(getPicture("kermit"));
lijstje.add(index);
}
}
});
}
public void resetGuiPlayerInput() {
guiPlayerInput = -1;
}
private void redraw() {
if (gameRules instanceof Reversi) { // TODO remove if possible
if (gameRules.getPlayer(0).getName() != null) {
player1.setText(StringUtils.capitalize(gameRules.getPlayer(0).getName()));
player2.setText(StringUtils.capitalize(gameRules.getPlayer(1).getName()));
currentPlayerPane.getChildren().set(0, getCurrentPlayer());
}
timerPane.getChildren().set(0,createTimer());
Reversi reversi = (Reversi) gameRules;
for (VBox pane : panes) pane.getChildren().clear();
for (int i=0; i<panes.length; i++) {
if (reversi.board.get(i) == 1)
panes[i].getChildren().add(getPicture("black"));
if (reversi.board.get(i) == 2)
panes[i].getChildren().add(getPicture("white"));
}
}
}
public enum StandardGameType {
OFFLINE_AI_VS_PLAYER(RefereeFactory.DefaultReferee, PlayerFactory.BestAvailableAI, PlayerFactory.GUIPlayer),
// OFFLINE_PLAYER_VS_AI(RefereeFactory.DefaultReferee, PlayerFactory.GUIPlayer, PlayerFactory.BestAvailableAI),
ONLINE_AI_VS_REMOTE(RefereeFactory.NetworkedReferee, PlayerFactory.BestAvailableAI, PlayerFactory.RemotePlayer),
ONLINE_HUMAN_VS_REMOTE(RefereeFactory.NetworkedReferee, PlayerFactory.BestAvailableAI, PlayerFactory.HumanPlayer),
ONLINE_REMOTE_VS_AI(RefereeFactory.NetworkedReferee, PlayerFactory.RemotePlayer, PlayerFactory.BestAvailableAI),
ONLINE_REMOTE_VS_HUMAN(RefereeFactory.NetworkedReferee, PlayerFactory.RemotePlayer, PlayerFactory.HumanPlayer);
public final RefereeFactory refereeFactory;
public final PlayerFactory first;
public final PlayerFactory second;
StandardGameType(RefereeFactory refereeFactory, PlayerFactory first, PlayerFactory second) {
this.refereeFactory = refereeFactory;
this.first = first;
this.second = second;
}
}
public static PlayField createGameAndPlayField(GameFactory gameFactory, StandardGameType standardGameType) {
return createGameAndPlayField(gameFactory, standardGameType, (e)->{} );
}
public static PlayField createGameAndPlayField(GameFactory gameFactory, StandardGameType standardGameType, CallbackWithParam<GameRules> BeforeGameStart) {
Arcade arcade = CompositionRoot.getInstance().arcade;
GameRules game = arcade.createGame(gameFactory, standardGameType.refereeFactory, standardGameType.first, standardGameType.second);
PlayField playField = new PlayField(gameFactory.boardSize, game);
BeforeGameStart.callback(game);
registerDefaultCallBacks(game, playField);
new Thread(game).start();
return playField;
}
private Label createTimer() {
Integer startTime = 10;
Label timerLabel = new Label();
Timeline timeline = new Timeline();
IntegerProperty timeSeconds = new SimpleIntegerProperty(startTime);
timerLabel.textProperty().bind(timeSeconds.asString());
timerLabel.setTextFill(Color.BLACK);
timerLabel.setStyle("-fx-font-size: 3em;");
timeSeconds.set(startTime);
timeline.getKeyFrames().add(new KeyFrame(Duration.seconds(startTime + 1), new KeyValue(timeSeconds, 0)));
timeline.playFromStart();
return timerLabel;
}
private Label getCurrentPlayer() {
if(switching) {
currentPlayer.setText("Aan zet: " + StringUtils.capitalize(gameRules.getPlayer(0).getName()));
switching = false;
} else {
currentPlayer.setText("Aan zet: " + StringUtils.capitalize(gameRules.getPlayer(1).getName()));
switching = true;
}
return currentPlayer;
}
private static void registerDefaultCallBacks(GameRules game, PlayField playField) {
Platform.runLater(playField::redraw); // TODO this is a hack
game.onValidMovePlayed.register((pair0 -> {
Platform.runLater(() -> playField.setPicture(game, pair0.getKey(), pair0.getValue()));
if (game instanceof Reversi) {
Platform.runLater(playField::redraw); // TODO this is a hack
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
game.onGameEnded.register(() -> Platform.runLater(() -> playField.displayWinScreen(game.getGameState())));
game.onValidMovePlayed.register(i -> System.out.println(game));
}
}
|
188122_28 | /**
* Created Aug 23, 2007
*
* @by Sebastian Lenz ([email protected])
*
* Copyright 2007 Sebastian Lenz
*
* This file is part of parsemis.
*
* Licence:
* LGPL: http://www.gnu.org/licenses/lgpl.html
* EPL: http://www.eclipse.org/org/documents/epl-v10.php
* See the LICENSE file in the project's top-level directory for details.
*/
package de.parsemis.visualisation;
import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import prefuse.action.layout.graph.TreeLayout;
import prefuse.data.Graph;
import prefuse.util.collections.IntIterator;
import prefuse.visual.NodeItem;
/**
*
* @author Sebastian Lenz ([email protected])
*/
public class SugiyamaLayout extends TreeLayout {
// public static String sync = "sync";
public static class Co {
private double x;
private final int y;
final private int id;
public Co(final double x, final int y, final int id) {
this.x = x;
this.y = y;
this.id = id;
}
public void changeX(final double i) {
this.x = i;
}
public int getId() {
return this.id;
}
public double getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
private double m_bspace = 30; // the spacing between sibling nodes
private double m_tspace = 25; // the spacing between subtrees
private double m_dspace = 50; // the spacing between depth levels
private double m_offset = 50; // pixel offset for root node position
private final double[] m_depths = new double[10];
private double m_ax, m_ay; // for holding anchor co-ordinates
private int[] degree;
private final Map<Integer, Collection<Double>> calc;
private Co[] coord;
private int maxLen;
// ------------------------------------------------------------------------
boolean ready = false;
/**
*
* @param group
* the data group to layout. Must resolve to a Graph instance.
*/
public SugiyamaLayout(final String group) {
super(group);
calc = new HashMap<Integer, Collection<Double>>();
}
private void computeX(final Graph g) {
Arrays.sort(coord, new Comparator<Co>() {
public int compare(final Co co1, final Co co2) {
final Double x1 = co1.getX();
final Integer y1 = co1.getY();
final Integer id1 = co1.getId();
final Double x2 = co2.getX();
final Integer y2 = co2.getY();
final Integer id2 = co2.getId();
if (!(y1.equals(y2))) {
return y1.compareTo(y2);
} else if (!(x1.equals(x2))) {
return x1.compareTo(x2);
} else {
return id1.compareTo(id2);
}
}
});
double fix = 0;
int i = 0;
int layer = 0;
int state = 0;
int arraypos = 0;
int layerstart = 0;
double istSum = 0;
double sollSum = 0;
while (i < coord.length) {
switch (state) {
case 0: // layer = 0, x wird gesetzt
coord[arraypos].changeX(fix);
fix++;
arraypos++;
if (arraypos == coord.length) { // keine knoten mehr uebrig,
// abbruchbedingung
i = arraypos;
break;
}
if (coord[arraypos].getY() != layer) { // ende aktueller layer
state = 2;
}
break;
case 1: // layer != 0, x muss berechnet werden
double erg = 0;
if (calc.containsKey(coord[arraypos].getId())) {
final Collection<Double> test = calc.get(coord[arraypos]
.getId());
final Iterator<Double> values = test.iterator();
while (values.hasNext()) {
erg = erg + values.next();
}
erg = erg / test.size();
} else {
assert (false);
}
coord[arraypos].changeX(erg);
arraypos++;
if (arraypos == coord.length) {// keine knoten mehr uebrig
state = 3;// kein abbruch, da noch ueberpruefung auf
// ueberschneidung noetig
break;
}
if (coord[arraypos].getY() != layer) {// ende aktueller layer
state = 3;
break;
}
break;
case 2: // vorberechnung der nachfolger
if (arraypos == coord.length) {// keine knoten mehr uebrig,
// abbruchbedingung
i = arraypos;
break;
}
for (int j = layerstart; j < arraypos; j++) {
double f = 0;
final IntIterator it = g.outEdgeRows(coord[j].getId());
final double n = g.getOutDegree(coord[j].getId());
while (it.hasNext()) {
final int e = it.nextInt();
final int t = g.getTargetNode(e);
Collection<Double> temp = calc.get(t);
if (temp == null) {
temp = new Vector<Double>();
}
temp.add(-((n - 1) / 2) + f + coord[j].getX());
calc.put(t, temp);
f = f + 1.0;
}
}
state = 1;
layer++;
layerstart = arraypos;
i = arraypos;
break;
case 3: // test auf eventuelle ueberschneidungen
sollSum = 0;
istSum = 0;
Arrays.sort(coord, layerstart, arraypos, new Comparator<Co>() {// aktueller
// layer
// nach
// x
// sortieren
public int compare(final Co co1, final Co co2) { // um
// feste
// reihefolge
// fuer
// schleife
// zu haben
final Double x1 = co1.getX();
final Integer id1 = co1.getId();
final Double x2 = co2.getX();
final Integer id2 = co2.getId();
if (!(x1.equals(x2))) {
return x1.compareTo(x2);
} else {
return id1.compareTo(id2);
}
}
});
for (int j = layerstart; j < arraypos - 1; j++) {
final double diff = Math.abs(coord[j].getX()
- coord[j + 1].getX());
if (diff < 1) {
sollSum++;
} else {
sollSum = sollSum + diff;
}
istSum = istSum + diff;
}
if (Math.abs(istSum - sollSum) < .0000001) {
// keine ueberschneidung
// state = 2; //weiter mit vorberechnung
state = 5; // weiter mit Kantenkreuzungen bereinigen
} else {// ueberschneidung, korrigieren ...
state = 4;
}
break;
case 4: // korrigieren der ueberschneidungen
double oldPosX = coord[layerstart].getX();
coord[layerstart].changeX(oldPosX - (sollSum - istSum) / 2);
for (int j = layerstart; j < arraypos - 2; j++) {
final double diff = Math.abs(oldPosX - coord[j + 1].getX());
oldPosX = coord[j + 1].getX();
if (diff < 1) {
coord[j + 1].changeX(coord[j].getX() + 1);
} else {
coord[j + 1].changeX(coord[j].getX() + diff);
}
}
coord[arraypos - 1].changeX(coord[arraypos - 1].getX()
+ (sollSum - istSum) / 2);
// state = 2; //weiter mit vorberechnung
state = 5; // weiter mit Kantenkreuzungen bereinigen
break;
case 5: // entfernen der kantenkreuzungen
for (int j = layerstart; j < arraypos - 1; j++) {
final IntIterator it = g.inEdgeRows(coord[j].getId());// vorgaenger
// knoten 1
// finden
Co[] test1 = null;
int y = 0;
while (it.hasNext()) {
final int e = it.nextInt();
final int t = g.getSourceNode(e);
if (test1 == null) {
test1 = new Co[g.getInDegree(coord[j].getId())];
}
int z = 0;
while (coord[z].getId() != t) {
z++;
}
test1[y] = coord[z];
y++;
}
final IntIterator et = g.inEdgeRows(coord[j + 1].getId());// vorgaenger
// knoten
// 2
// finden
Co[] test2 = null;
y = 0;
while (et.hasNext()) {
final int e = et.nextInt();
final int t = g.getSourceNode(e);
if (test2 == null) {
test2 = new Co[g.getInDegree(coord[j + 1].getId())];
}
int z = 0;
while (coord[z].getId() != t) {
z++;
}
test2[y] = coord[z];
y++;
}
if (test1 == null | test2 == null) {
break;
}
// vorgaenger nach x sortieren
if (test1.length > 1) {
Arrays.sort(test1, new Comparator<Co>() {
public int compare(final Co co1, final Co co2) {
final Double x1 = co1.getX();
final Double x2 = co2.getX();
return x1.compareTo(x2);
}
});
}
if (test2.length > 1) {
Arrays.sort(test2, new Comparator<Co>() {
public int compare(final Co co1, final Co co2) {
final Double x1 = co1.getX();
final Double x2 = co2.getX();
return x1.compareTo(x2);
}
});
}
// wenn der linkeste vorgaenger des rechten knoten < der
// rechteste vorgaenger des linken knotens
if (test2[0].getX() < test1[test1.length - 1].getX()) {
final double sw = coord[j].getX();
coord[j].changeX(coord[j + 1].getX());
coord[j + 1].changeX(sw);
}
}
state = 2;
break;
default:
break;
}// end-switch
}// end-while
}
private void computeY(final Graph g) {
int r = 0;
int c = 0;
final int cnt = g.getNodeCount();
degree = new int[cnt];
final IntIterator it = g.nodeRows();
while (it.hasNext()) {
final int i = it.nextInt();
degree[i] = g.getInDegree(i);
}
while (c != cnt) {
c = rank(r, c, g);
r++;
}
}
/**
* Get the spacing between neighbor nodes.
*
* @return the breadth spacing
*/
public double getBreadthSpacing() {
return m_bspace;
}
/**
* Get the spacing between depth levels.
*
* @return the depth spacing
*/
public double getDepthSpacing() {
return m_dspace;
}
/**
* Get the offset value for placing the root node of the tree.
*
* @return the value by which the root node of the tree is offset
*/
public double getRootNodeOffset() {
return m_offset;
}
/**
* Get the spacing between neighboring subtrees.
*
* @return the subtree spacing
*/
public double getSubtreeSpacing() {
return m_tspace;
}
// -----------------------------------------------------------------------
private int rank(final int r, int c, final Graph g) {
final int cnt = g.getNodeCount();
for (int j = 0; j < cnt; j++) {
if (degree[j] == 0) {
coord[j] = new Co(0.0, r, j);
maxLen = Math.max(maxLen, g.getNode(j).getString("name")
.length());
degree[j] = -1;
}
}
for (int j = 0; j < cnt; j++) {
if (degree[j] == -1) {
final IntIterator ed = g.outEdgeRows(j);
while (ed.hasNext()) {
final int e = ed.nextInt();
degree[g.getTargetNode(e)]--;
}
degree[j] = -2;
c++;
}
}
return c;
}
public synchronized boolean ready() {
return ready;
}
/**
* @see prefuse.action.Action#run(double)
*/
@Override
public synchronized void run(final double frac) {
maxLen = 0;
final Graph g = (Graph) m_vis.getGroup(m_group);
Arrays.fill(m_depths, 0);
final Point2D a = getLayoutAnchor();
m_ax = a.getX();
m_ay = a.getY();
// -----
coord = new Co[g.getNodeCount()];
computeY(g);
computeX(g);
for (int i = 0; i < g.getNodeCount(); i++) {
final NodeItem n = (NodeItem) g.getNode(coord[i].getId());
double hoch = coord[i].getY();
double breit = coord[i].getX();
breit = breit * m_bspace * Math.sqrt(maxLen);
hoch = hoch * m_dspace;
setBreadth(n, null, breit);
setDepth(n, null, hoch);
}
ready = true;
}
private void setBreadth(final NodeItem n, final NodeItem p, final double b) {
setX(n, p, m_ax + b);
}
/**
* Set the spacing between neighbor nodes.
*
* @param b
* the breadth spacing to use
*/
public void setBreadthSpacing(final double b) {
m_bspace = b;
}
private void setDepth(final NodeItem n, final NodeItem p, final double d) {
setY(n, p, m_ay + d);
}
/**
* Set the spacing between depth levels.
*
* @param d
* the depth spacing to use
*/
public void setDepthSpacing(final double d) {
m_dspace = d;
}
/**
* Set the offset value for placing the root node of the tree. The dimension
* in which this offset is applied is dependent upon the orientation of the
* tree. For example, in a left-to-right orientation, the offset will a
* horizontal offset from the left edge of the layout bounds.
*
* @param o
* the value by which to offset the root node of the tree
*/
public void setRootNodeOffset(final double o) {
m_offset = o;
}
/**
* Set the spacing between neighboring subtrees.
*
* @param s
* the subtree spacing to use
*/
public void setSubtreeSpacing(final double s) {
m_tspace = s;
}
}
| timtadh/parsemis | src/de/parsemis/visualisation/SugiyamaLayout.java | 4,704 | // rechteste vorgaenger des linken knotens | line_comment | nl | /**
* Created Aug 23, 2007
*
* @by Sebastian Lenz ([email protected])
*
* Copyright 2007 Sebastian Lenz
*
* This file is part of parsemis.
*
* Licence:
* LGPL: http://www.gnu.org/licenses/lgpl.html
* EPL: http://www.eclipse.org/org/documents/epl-v10.php
* See the LICENSE file in the project's top-level directory for details.
*/
package de.parsemis.visualisation;
import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import prefuse.action.layout.graph.TreeLayout;
import prefuse.data.Graph;
import prefuse.util.collections.IntIterator;
import prefuse.visual.NodeItem;
/**
*
* @author Sebastian Lenz ([email protected])
*/
public class SugiyamaLayout extends TreeLayout {
// public static String sync = "sync";
public static class Co {
private double x;
private final int y;
final private int id;
public Co(final double x, final int y, final int id) {
this.x = x;
this.y = y;
this.id = id;
}
public void changeX(final double i) {
this.x = i;
}
public int getId() {
return this.id;
}
public double getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
private double m_bspace = 30; // the spacing between sibling nodes
private double m_tspace = 25; // the spacing between subtrees
private double m_dspace = 50; // the spacing between depth levels
private double m_offset = 50; // pixel offset for root node position
private final double[] m_depths = new double[10];
private double m_ax, m_ay; // for holding anchor co-ordinates
private int[] degree;
private final Map<Integer, Collection<Double>> calc;
private Co[] coord;
private int maxLen;
// ------------------------------------------------------------------------
boolean ready = false;
/**
*
* @param group
* the data group to layout. Must resolve to a Graph instance.
*/
public SugiyamaLayout(final String group) {
super(group);
calc = new HashMap<Integer, Collection<Double>>();
}
private void computeX(final Graph g) {
Arrays.sort(coord, new Comparator<Co>() {
public int compare(final Co co1, final Co co2) {
final Double x1 = co1.getX();
final Integer y1 = co1.getY();
final Integer id1 = co1.getId();
final Double x2 = co2.getX();
final Integer y2 = co2.getY();
final Integer id2 = co2.getId();
if (!(y1.equals(y2))) {
return y1.compareTo(y2);
} else if (!(x1.equals(x2))) {
return x1.compareTo(x2);
} else {
return id1.compareTo(id2);
}
}
});
double fix = 0;
int i = 0;
int layer = 0;
int state = 0;
int arraypos = 0;
int layerstart = 0;
double istSum = 0;
double sollSum = 0;
while (i < coord.length) {
switch (state) {
case 0: // layer = 0, x wird gesetzt
coord[arraypos].changeX(fix);
fix++;
arraypos++;
if (arraypos == coord.length) { // keine knoten mehr uebrig,
// abbruchbedingung
i = arraypos;
break;
}
if (coord[arraypos].getY() != layer) { // ende aktueller layer
state = 2;
}
break;
case 1: // layer != 0, x muss berechnet werden
double erg = 0;
if (calc.containsKey(coord[arraypos].getId())) {
final Collection<Double> test = calc.get(coord[arraypos]
.getId());
final Iterator<Double> values = test.iterator();
while (values.hasNext()) {
erg = erg + values.next();
}
erg = erg / test.size();
} else {
assert (false);
}
coord[arraypos].changeX(erg);
arraypos++;
if (arraypos == coord.length) {// keine knoten mehr uebrig
state = 3;// kein abbruch, da noch ueberpruefung auf
// ueberschneidung noetig
break;
}
if (coord[arraypos].getY() != layer) {// ende aktueller layer
state = 3;
break;
}
break;
case 2: // vorberechnung der nachfolger
if (arraypos == coord.length) {// keine knoten mehr uebrig,
// abbruchbedingung
i = arraypos;
break;
}
for (int j = layerstart; j < arraypos; j++) {
double f = 0;
final IntIterator it = g.outEdgeRows(coord[j].getId());
final double n = g.getOutDegree(coord[j].getId());
while (it.hasNext()) {
final int e = it.nextInt();
final int t = g.getTargetNode(e);
Collection<Double> temp = calc.get(t);
if (temp == null) {
temp = new Vector<Double>();
}
temp.add(-((n - 1) / 2) + f + coord[j].getX());
calc.put(t, temp);
f = f + 1.0;
}
}
state = 1;
layer++;
layerstart = arraypos;
i = arraypos;
break;
case 3: // test auf eventuelle ueberschneidungen
sollSum = 0;
istSum = 0;
Arrays.sort(coord, layerstart, arraypos, new Comparator<Co>() {// aktueller
// layer
// nach
// x
// sortieren
public int compare(final Co co1, final Co co2) { // um
// feste
// reihefolge
// fuer
// schleife
// zu haben
final Double x1 = co1.getX();
final Integer id1 = co1.getId();
final Double x2 = co2.getX();
final Integer id2 = co2.getId();
if (!(x1.equals(x2))) {
return x1.compareTo(x2);
} else {
return id1.compareTo(id2);
}
}
});
for (int j = layerstart; j < arraypos - 1; j++) {
final double diff = Math.abs(coord[j].getX()
- coord[j + 1].getX());
if (diff < 1) {
sollSum++;
} else {
sollSum = sollSum + diff;
}
istSum = istSum + diff;
}
if (Math.abs(istSum - sollSum) < .0000001) {
// keine ueberschneidung
// state = 2; //weiter mit vorberechnung
state = 5; // weiter mit Kantenkreuzungen bereinigen
} else {// ueberschneidung, korrigieren ...
state = 4;
}
break;
case 4: // korrigieren der ueberschneidungen
double oldPosX = coord[layerstart].getX();
coord[layerstart].changeX(oldPosX - (sollSum - istSum) / 2);
for (int j = layerstart; j < arraypos - 2; j++) {
final double diff = Math.abs(oldPosX - coord[j + 1].getX());
oldPosX = coord[j + 1].getX();
if (diff < 1) {
coord[j + 1].changeX(coord[j].getX() + 1);
} else {
coord[j + 1].changeX(coord[j].getX() + diff);
}
}
coord[arraypos - 1].changeX(coord[arraypos - 1].getX()
+ (sollSum - istSum) / 2);
// state = 2; //weiter mit vorberechnung
state = 5; // weiter mit Kantenkreuzungen bereinigen
break;
case 5: // entfernen der kantenkreuzungen
for (int j = layerstart; j < arraypos - 1; j++) {
final IntIterator it = g.inEdgeRows(coord[j].getId());// vorgaenger
// knoten 1
// finden
Co[] test1 = null;
int y = 0;
while (it.hasNext()) {
final int e = it.nextInt();
final int t = g.getSourceNode(e);
if (test1 == null) {
test1 = new Co[g.getInDegree(coord[j].getId())];
}
int z = 0;
while (coord[z].getId() != t) {
z++;
}
test1[y] = coord[z];
y++;
}
final IntIterator et = g.inEdgeRows(coord[j + 1].getId());// vorgaenger
// knoten
// 2
// finden
Co[] test2 = null;
y = 0;
while (et.hasNext()) {
final int e = et.nextInt();
final int t = g.getSourceNode(e);
if (test2 == null) {
test2 = new Co[g.getInDegree(coord[j + 1].getId())];
}
int z = 0;
while (coord[z].getId() != t) {
z++;
}
test2[y] = coord[z];
y++;
}
if (test1 == null | test2 == null) {
break;
}
// vorgaenger nach x sortieren
if (test1.length > 1) {
Arrays.sort(test1, new Comparator<Co>() {
public int compare(final Co co1, final Co co2) {
final Double x1 = co1.getX();
final Double x2 = co2.getX();
return x1.compareTo(x2);
}
});
}
if (test2.length > 1) {
Arrays.sort(test2, new Comparator<Co>() {
public int compare(final Co co1, final Co co2) {
final Double x1 = co1.getX();
final Double x2 = co2.getX();
return x1.compareTo(x2);
}
});
}
// wenn der linkeste vorgaenger des rechten knoten < der
// rechteste vorgaenger<SUF>
if (test2[0].getX() < test1[test1.length - 1].getX()) {
final double sw = coord[j].getX();
coord[j].changeX(coord[j + 1].getX());
coord[j + 1].changeX(sw);
}
}
state = 2;
break;
default:
break;
}// end-switch
}// end-while
}
private void computeY(final Graph g) {
int r = 0;
int c = 0;
final int cnt = g.getNodeCount();
degree = new int[cnt];
final IntIterator it = g.nodeRows();
while (it.hasNext()) {
final int i = it.nextInt();
degree[i] = g.getInDegree(i);
}
while (c != cnt) {
c = rank(r, c, g);
r++;
}
}
/**
* Get the spacing between neighbor nodes.
*
* @return the breadth spacing
*/
public double getBreadthSpacing() {
return m_bspace;
}
/**
* Get the spacing between depth levels.
*
* @return the depth spacing
*/
public double getDepthSpacing() {
return m_dspace;
}
/**
* Get the offset value for placing the root node of the tree.
*
* @return the value by which the root node of the tree is offset
*/
public double getRootNodeOffset() {
return m_offset;
}
/**
* Get the spacing between neighboring subtrees.
*
* @return the subtree spacing
*/
public double getSubtreeSpacing() {
return m_tspace;
}
// -----------------------------------------------------------------------
private int rank(final int r, int c, final Graph g) {
final int cnt = g.getNodeCount();
for (int j = 0; j < cnt; j++) {
if (degree[j] == 0) {
coord[j] = new Co(0.0, r, j);
maxLen = Math.max(maxLen, g.getNode(j).getString("name")
.length());
degree[j] = -1;
}
}
for (int j = 0; j < cnt; j++) {
if (degree[j] == -1) {
final IntIterator ed = g.outEdgeRows(j);
while (ed.hasNext()) {
final int e = ed.nextInt();
degree[g.getTargetNode(e)]--;
}
degree[j] = -2;
c++;
}
}
return c;
}
public synchronized boolean ready() {
return ready;
}
/**
* @see prefuse.action.Action#run(double)
*/
@Override
public synchronized void run(final double frac) {
maxLen = 0;
final Graph g = (Graph) m_vis.getGroup(m_group);
Arrays.fill(m_depths, 0);
final Point2D a = getLayoutAnchor();
m_ax = a.getX();
m_ay = a.getY();
// -----
coord = new Co[g.getNodeCount()];
computeY(g);
computeX(g);
for (int i = 0; i < g.getNodeCount(); i++) {
final NodeItem n = (NodeItem) g.getNode(coord[i].getId());
double hoch = coord[i].getY();
double breit = coord[i].getX();
breit = breit * m_bspace * Math.sqrt(maxLen);
hoch = hoch * m_dspace;
setBreadth(n, null, breit);
setDepth(n, null, hoch);
}
ready = true;
}
private void setBreadth(final NodeItem n, final NodeItem p, final double b) {
setX(n, p, m_ax + b);
}
/**
* Set the spacing between neighbor nodes.
*
* @param b
* the breadth spacing to use
*/
public void setBreadthSpacing(final double b) {
m_bspace = b;
}
private void setDepth(final NodeItem n, final NodeItem p, final double d) {
setY(n, p, m_ay + d);
}
/**
* Set the spacing between depth levels.
*
* @param d
* the depth spacing to use
*/
public void setDepthSpacing(final double d) {
m_dspace = d;
}
/**
* Set the offset value for placing the root node of the tree. The dimension
* in which this offset is applied is dependent upon the orientation of the
* tree. For example, in a left-to-right orientation, the offset will a
* horizontal offset from the left edge of the layout bounds.
*
* @param o
* the value by which to offset the root node of the tree
*/
public void setRootNodeOffset(final double o) {
m_offset = o;
}
/**
* Set the spacing between neighboring subtrees.
*
* @param s
* the subtree spacing to use
*/
public void setSubtreeSpacing(final double s) {
m_tspace = s;
}
}
|
140672_15 | package org.xmlvm.ios;
import java.util.*;
import org.xmlvm.XMLVMSkeletonOnly;
@XMLVMSkeletonOnly
public class CMTimeRange {
/*
* Variables
*/
public CMTime start;
public CMTime duration;
/*
* Static methods
*/
/**
* CMTimeRange CMTimeRangeFromTimeToTime( CMTime start, CMTime end ) ;
*/
public static CMTimeRange fromTimeToTime(CMTime start, CMTime end){
throw new RuntimeException("Stub");
}
/**
* CMTimeRange CMTimeRangeMakeFromDictionary( CFDictionaryRef dict) ;
*/
public static CMTimeRange makeFromDictionary(CFDictionary dict){
throw new RuntimeException("Stub");
}
/**
* CFStringRef CMTimeRangeCopyDescription( CFAllocatorRef allocator, CMTimeRange range) ;
*/
public static String copyDescription(CFAllocator allocator, CMTimeRange range){
throw new RuntimeException("Stub");
}
/*
* Constructors
*/
/**
* CMTimeRange CMTimeRangeMake( CMTime start, CMTime duration) ;
*/
public CMTimeRange(CMTime start, CMTime duration) {}
/** Default constructor */
public CMTimeRange() {}
/*
* Instance methods
*/
/**
* CMTimeRange CMTimeRangeGetUnion( CMTimeRange range1, CMTimeRange range2) ;
*/
public CMTimeRange getUnion(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* CMTimeRange CMTimeRangeGetIntersection( CMTimeRange range1, CMTimeRange range2) ;
*/
public CMTimeRange getIntersection(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeEqual( CMTimeRange range1, CMTimeRange range2) ;
*/
public byte equal(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeContainsTime( CMTimeRange range, CMTime time) ;
*/
public byte containsTime(CMTime time){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeContainsTimeRange( CMTimeRange range1, CMTimeRange range2) ;
*/
public byte containsTimeRange(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* CMTime CMTimeRangeGetEnd( CMTimeRange range) ;
*/
public CMTime getEnd(){
throw new RuntimeException("Stub");
}
/**
* CFDictionaryRef CMTimeRangeCopyAsDictionary( CMTimeRange range, CFAllocatorRef allocator) ;
*/
public CFDictionary copyAsDictionary(CFAllocator allocator){
throw new RuntimeException("Stub");
}
/**
* void CMTimeRangeShow( CMTimeRange range) ;
*/
public void show(){
throw new RuntimeException("Stub");
}
}
| tisoft/xmlvm | src/ios/org/xmlvm/ios/CMTimeRange.java | 784 | /**
* void CMTimeRangeShow( CMTimeRange range) ;
*/ | block_comment | nl | package org.xmlvm.ios;
import java.util.*;
import org.xmlvm.XMLVMSkeletonOnly;
@XMLVMSkeletonOnly
public class CMTimeRange {
/*
* Variables
*/
public CMTime start;
public CMTime duration;
/*
* Static methods
*/
/**
* CMTimeRange CMTimeRangeFromTimeToTime( CMTime start, CMTime end ) ;
*/
public static CMTimeRange fromTimeToTime(CMTime start, CMTime end){
throw new RuntimeException("Stub");
}
/**
* CMTimeRange CMTimeRangeMakeFromDictionary( CFDictionaryRef dict) ;
*/
public static CMTimeRange makeFromDictionary(CFDictionary dict){
throw new RuntimeException("Stub");
}
/**
* CFStringRef CMTimeRangeCopyDescription( CFAllocatorRef allocator, CMTimeRange range) ;
*/
public static String copyDescription(CFAllocator allocator, CMTimeRange range){
throw new RuntimeException("Stub");
}
/*
* Constructors
*/
/**
* CMTimeRange CMTimeRangeMake( CMTime start, CMTime duration) ;
*/
public CMTimeRange(CMTime start, CMTime duration) {}
/** Default constructor */
public CMTimeRange() {}
/*
* Instance methods
*/
/**
* CMTimeRange CMTimeRangeGetUnion( CMTimeRange range1, CMTimeRange range2) ;
*/
public CMTimeRange getUnion(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* CMTimeRange CMTimeRangeGetIntersection( CMTimeRange range1, CMTimeRange range2) ;
*/
public CMTimeRange getIntersection(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeEqual( CMTimeRange range1, CMTimeRange range2) ;
*/
public byte equal(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeContainsTime( CMTimeRange range, CMTime time) ;
*/
public byte containsTime(CMTime time){
throw new RuntimeException("Stub");
}
/**
* Boolean CMTimeRangeContainsTimeRange( CMTimeRange range1, CMTimeRange range2) ;
*/
public byte containsTimeRange(CMTimeRange range2){
throw new RuntimeException("Stub");
}
/**
* CMTime CMTimeRangeGetEnd( CMTimeRange range) ;
*/
public CMTime getEnd(){
throw new RuntimeException("Stub");
}
/**
* CFDictionaryRef CMTimeRangeCopyAsDictionary( CMTimeRange range, CFAllocatorRef allocator) ;
*/
public CFDictionary copyAsDictionary(CFAllocator allocator){
throw new RuntimeException("Stub");
}
/**
* void CMTimeRangeShow( CMTimeRange<SUF>*/
public void show(){
throw new RuntimeException("Stub");
}
}
|
20752_1 | package Misc;
import java.awt.Color;
import java.awt.Component;
import javax.swing.*;
/**
*
* @author Titouan Vervack
*/
public class CellRenderer implements ListCellRenderer {
public CellRenderer() {
}
@Override
public Component getListCellRendererComponent(JList list, Object c, int i, boolean isSelected, boolean focus) {
if (c instanceof JPanel) {
JComponent component = (JComponent) c;
component.setForeground(Color.WHITE);
component.setBackground(Color.WHITE);
//Maak een kadertje rond het geselecteerde element
component.setBorder(isSelected ? BorderFactory.createLineBorder(Color.BLACK) : null);
return component;
}
return null;
}
}
| tivervac/RPG | src/Misc/CellRenderer.java | 210 | //Maak een kadertje rond het geselecteerde element | line_comment | nl | package Misc;
import java.awt.Color;
import java.awt.Component;
import javax.swing.*;
/**
*
* @author Titouan Vervack
*/
public class CellRenderer implements ListCellRenderer {
public CellRenderer() {
}
@Override
public Component getListCellRendererComponent(JList list, Object c, int i, boolean isSelected, boolean focus) {
if (c instanceof JPanel) {
JComponent component = (JComponent) c;
component.setForeground(Color.WHITE);
component.setBackground(Color.WHITE);
//Maak een<SUF>
component.setBorder(isSelected ? BorderFactory.createLineBorder(Color.BLACK) : null);
return component;
}
return null;
}
}
|
35516_1 | package jbox;
import modellen.SpelModel;
import org.jbox2d.callbacks.ContactImpulse;
import org.jbox2d.callbacks.ContactListener;
import org.jbox2d.collision.Manifold;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.contacts.Contact;
/**
*
* @author Titouan Vervack
*/
public class BreekListener implements ContactListener {
private SpelModel model;
private Body body1;
private Body body2;
public BreekListener(SpelModel model) {
this.model = model;
}
@Override
public void beginContact(Contact contact) {
body1 = contact.getFixtureA().getBody();
body2 = contact.getFixtureB().getBody();
}
@Override
public void endContact(Contact contact) {
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
//Voert krachten uit op de objecten
try {
//Als er rechtstreeks contact is tussen een doel en bozel verwijder het doel
if (model.getDoelen().contains(body1) && model.getBozels().containsValue(body2)) {
if (model.getMap().get((String) model.getBodies().get(body1)).getBreekbaar()) {
model.beschadig(body1, Float.MAX_VALUE);
}
return;
}
if (model.getDoelen().contains(body2) && model.getBozels().containsValue(body1)) {
if (model.getMap().get((String) model.getBodies().get(body2)).getBreekbaar()) {
model.beschadig(body2, Float.MAX_VALUE);
}
return;
}
//Vermenigvuldig met 1000 anders is alles direct kapot
if (model.getMap().get((String) model.getBodies().get(body1)).getBreekbaar()) {
model.beschadig(body1, impulse.normalImpulses[0] / (model.getTijdsstap() * 1000));
}
if (model.getMap().get((String) model.getBodies().get(body2)).getBreekbaar()) {
model.beschadig(body2, impulse.normalImpulses[1] / (model.getTijdsstap() * 1000));
}
} catch (Exception exp) {
//Nullpointers
}
}
} | tivervac/UGentProjects | Bozels/src/JBox/BreekListener.java | 694 | //Voert krachten uit op de objecten | line_comment | nl | package jbox;
import modellen.SpelModel;
import org.jbox2d.callbacks.ContactImpulse;
import org.jbox2d.callbacks.ContactListener;
import org.jbox2d.collision.Manifold;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.contacts.Contact;
/**
*
* @author Titouan Vervack
*/
public class BreekListener implements ContactListener {
private SpelModel model;
private Body body1;
private Body body2;
public BreekListener(SpelModel model) {
this.model = model;
}
@Override
public void beginContact(Contact contact) {
body1 = contact.getFixtureA().getBody();
body2 = contact.getFixtureB().getBody();
}
@Override
public void endContact(Contact contact) {
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
//Voert krachten<SUF>
try {
//Als er rechtstreeks contact is tussen een doel en bozel verwijder het doel
if (model.getDoelen().contains(body1) && model.getBozels().containsValue(body2)) {
if (model.getMap().get((String) model.getBodies().get(body1)).getBreekbaar()) {
model.beschadig(body1, Float.MAX_VALUE);
}
return;
}
if (model.getDoelen().contains(body2) && model.getBozels().containsValue(body1)) {
if (model.getMap().get((String) model.getBodies().get(body2)).getBreekbaar()) {
model.beschadig(body2, Float.MAX_VALUE);
}
return;
}
//Vermenigvuldig met 1000 anders is alles direct kapot
if (model.getMap().get((String) model.getBodies().get(body1)).getBreekbaar()) {
model.beschadig(body1, impulse.normalImpulses[0] / (model.getTijdsstap() * 1000));
}
if (model.getMap().get((String) model.getBodies().get(body2)).getBreekbaar()) {
model.beschadig(body2, impulse.normalImpulses[1] / (model.getTijdsstap() * 1000));
}
} catch (Exception exp) {
//Nullpointers
}
}
} |
23515_5 | package org.aikodi.chameleon.oo.type.generics;
import org.aikodi.chameleon.core.lookup.LookupException;
public class InstantiatedTypeParameter extends AbstractInstantiatedTypeParameter {
public InstantiatedTypeParameter(String name, TypeArgument argument) {
super(name,argument);
}
@Override
protected InstantiatedTypeParameter cloneSelf() {
return new InstantiatedTypeParameter(name(),argument());
}
/**
* @return
* @throws LookupException
*/
public boolean hasWildCardBound() throws LookupException {
return argument().isWildCardBound();
}
// /**
// * A generic parameter introduces itself. During lookup, the resolve() method will
// * introduce an alias.
// */
// public List<Member> getIntroducedMembers() {
// List<Member> result = new ArrayList<Member>();
// result.add(this);
// return result;
// }
// // upper en lower naar type param verhuizen? Wat met formal parameter? Moet dat daar niet hetzelfde blijven?
// public boolean compatibleWith(TypeParameter other) throws LookupException {
// return (other instanceof InstantiatedTypeParameter) && ((InstantiatedTypeParameter)other).argument().contains(argument());
// }
}
| tivervac/chameleon | src/org/aikodi/chameleon/oo/type/generics/InstantiatedTypeParameter.java | 341 | // // upper en lower naar type param verhuizen? Wat met formal parameter? Moet dat daar niet hetzelfde blijven? | line_comment | nl | package org.aikodi.chameleon.oo.type.generics;
import org.aikodi.chameleon.core.lookup.LookupException;
public class InstantiatedTypeParameter extends AbstractInstantiatedTypeParameter {
public InstantiatedTypeParameter(String name, TypeArgument argument) {
super(name,argument);
}
@Override
protected InstantiatedTypeParameter cloneSelf() {
return new InstantiatedTypeParameter(name(),argument());
}
/**
* @return
* @throws LookupException
*/
public boolean hasWildCardBound() throws LookupException {
return argument().isWildCardBound();
}
// /**
// * A generic parameter introduces itself. During lookup, the resolve() method will
// * introduce an alias.
// */
// public List<Member> getIntroducedMembers() {
// List<Member> result = new ArrayList<Member>();
// result.add(this);
// return result;
// }
// // upper en<SUF>
// public boolean compatibleWith(TypeParameter other) throws LookupException {
// return (other instanceof InstantiatedTypeParameter) && ((InstantiatedTypeParameter)other).argument().contains(argument());
// }
}
|
10292_3 | package be.kuleuven.cs.distrinet.jnome.core.type;
import java.util.ArrayList;
import java.util.List;
import org.aikodi.chameleon.core.element.Element;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.TypeReference;
import org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter;
import org.aikodi.chameleon.oo.type.generics.ExtendsConstraint;
import org.aikodi.chameleon.oo.type.generics.ExtendsWildcardType;
import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter;
import org.aikodi.chameleon.oo.type.generics.TypeArgument;
import org.aikodi.chameleon.oo.type.generics.TypeConstraint;
import org.aikodi.chameleon.oo.type.generics.TypeParameter;
import org.aikodi.chameleon.oo.view.ObjectOrientedView;
import org.aikodi.chameleon.workspace.View;
import be.kuleuven.cs.distrinet.jnome.core.language.Java7;
public class PureWildcard extends TypeArgument {
public PureWildcard() {
}
public TypeParameter capture(FormalTypeParameter formal) {
CapturedTypeParameter newParameter = new CapturedTypeParameter(formal.name());
capture(formal.constraints()).forEach(c -> newParameter.addConstraint(c));
return newParameter;
}
/**
* @param constraints
* @return
*/
public List<TypeConstraint> capture(List<TypeConstraint> constraints) {
List<TypeConstraint> newConstraints = new ArrayList<>();
for(TypeConstraint constraint: constraints) {
TypeConstraint clone = cloneAndResetTypeReference(constraint,constraint);
newConstraints.add(clone);
}
//FIXME This should actually be determined by the type parameter itself.
// perhaps it should compute its own upper bound reference
if(newConstraints.size() == 0) {
Java7 java = language(Java7.class);
BasicJavaTypeReference objectRef = java.createTypeReference(java.getDefaultSuperClassFQN());
TypeReference tref = java.createNonLocalTypeReference(objectRef,namespace().defaultNamespace());
newConstraints.add(new ExtendsConstraint(tref));
}
return newConstraints;
}
@Override
protected PureWildcard cloneSelf() {
return new PureWildcard();
}
// TypeVariable concept invoeren, en lowerbound,... verplaatsen naar daar? Deze is context sensitive. Hoewel, dat
// wordt toch nooit direct vergeleken. Er moet volgens mij altijd eerst gecaptured worden, dus dan moet dit inderdaad
// verplaatst worden. NOPE, niet altijd eerst capturen.
@Override
public Type lowerBound() throws LookupException {
View view = view();
ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class);
return l.getNullType(view.namespace());
}
@Override
public Type type() throws LookupException {
ExtendsWildcardType result = new ExtendsWildcardType(upperBound());
result.setUniParent(namespace().defaultNamespace());
return result;
// PureWildCardType pureWildCardType = new PureWildCardType(parameterBound());
// pureWildCardType.setUniParent(this);
// return pureWildCardType;
}
// public Type parameterBound() throws LookupException {
//// BasicJavaTypeReference nearestAncestor = nearestAncestor(BasicJavaTypeReference.class);
//// List<TypeArgument> args = nearestAncestor.typeArguments();
//// int index = args.indexOf(this);
//// // Wrong, this should not be the type constructor, we need to take into account the
//// // type instance
//// Type typeConstructor = nearestAncestor.typeConstructor();
//// Type typeInstance = nearestAncestor.getElement();
//// TypeParameter formalParameter = typeConstructor.parameter(TypeParameter.class,index);
//// TypeParameter actualParameter = typeInstance.parameter(TypeParameter.class, index);
//// TypeReference formalUpperBoundReference = formalParameter.upperBoundReference();
//// TypeReference clonedUpperBoundReference = clone(formalUpperBoundReference);
//// clonedUpperBoundReference.setUniParent(actualParameter);
////
////// Type result = formalParameter.upperBound(); // This fixes testGenericRejuse
//// Type result = clonedUpperBoundReference.getElement();
//// return result;
// }
@Override
public boolean uniSameAs(Element other) throws LookupException {
return other instanceof PureWildcard;
}
@Override
public Type upperBound() throws LookupException {
//return language(ObjectOrientedLanguage.class).getDefaultSuperClass();
return view(ObjectOrientedView.class).topLevelType();
}
@Override
public Verification verifySelf() {
return Valid.create();
}
public String toString(java.util.Set<Element> visited) {
return "?";
}
@Override
public boolean isWildCardBound() {
return true;
}
}
| tivervac/jnome | src/be/kuleuven/cs/distrinet/jnome/core/type/PureWildcard.java | 1,478 | // TypeVariable concept invoeren, en lowerbound,... verplaatsen naar daar? Deze is context sensitive. Hoewel, dat | line_comment | nl | package be.kuleuven.cs.distrinet.jnome.core.type;
import java.util.ArrayList;
import java.util.List;
import org.aikodi.chameleon.core.element.Element;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.validation.Valid;
import org.aikodi.chameleon.core.validation.Verification;
import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage;
import org.aikodi.chameleon.oo.type.Type;
import org.aikodi.chameleon.oo.type.TypeReference;
import org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter;
import org.aikodi.chameleon.oo.type.generics.ExtendsConstraint;
import org.aikodi.chameleon.oo.type.generics.ExtendsWildcardType;
import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter;
import org.aikodi.chameleon.oo.type.generics.TypeArgument;
import org.aikodi.chameleon.oo.type.generics.TypeConstraint;
import org.aikodi.chameleon.oo.type.generics.TypeParameter;
import org.aikodi.chameleon.oo.view.ObjectOrientedView;
import org.aikodi.chameleon.workspace.View;
import be.kuleuven.cs.distrinet.jnome.core.language.Java7;
public class PureWildcard extends TypeArgument {
public PureWildcard() {
}
public TypeParameter capture(FormalTypeParameter formal) {
CapturedTypeParameter newParameter = new CapturedTypeParameter(formal.name());
capture(formal.constraints()).forEach(c -> newParameter.addConstraint(c));
return newParameter;
}
/**
* @param constraints
* @return
*/
public List<TypeConstraint> capture(List<TypeConstraint> constraints) {
List<TypeConstraint> newConstraints = new ArrayList<>();
for(TypeConstraint constraint: constraints) {
TypeConstraint clone = cloneAndResetTypeReference(constraint,constraint);
newConstraints.add(clone);
}
//FIXME This should actually be determined by the type parameter itself.
// perhaps it should compute its own upper bound reference
if(newConstraints.size() == 0) {
Java7 java = language(Java7.class);
BasicJavaTypeReference objectRef = java.createTypeReference(java.getDefaultSuperClassFQN());
TypeReference tref = java.createNonLocalTypeReference(objectRef,namespace().defaultNamespace());
newConstraints.add(new ExtendsConstraint(tref));
}
return newConstraints;
}
@Override
protected PureWildcard cloneSelf() {
return new PureWildcard();
}
// TypeVariable concept<SUF>
// wordt toch nooit direct vergeleken. Er moet volgens mij altijd eerst gecaptured worden, dus dan moet dit inderdaad
// verplaatst worden. NOPE, niet altijd eerst capturen.
@Override
public Type lowerBound() throws LookupException {
View view = view();
ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class);
return l.getNullType(view.namespace());
}
@Override
public Type type() throws LookupException {
ExtendsWildcardType result = new ExtendsWildcardType(upperBound());
result.setUniParent(namespace().defaultNamespace());
return result;
// PureWildCardType pureWildCardType = new PureWildCardType(parameterBound());
// pureWildCardType.setUniParent(this);
// return pureWildCardType;
}
// public Type parameterBound() throws LookupException {
//// BasicJavaTypeReference nearestAncestor = nearestAncestor(BasicJavaTypeReference.class);
//// List<TypeArgument> args = nearestAncestor.typeArguments();
//// int index = args.indexOf(this);
//// // Wrong, this should not be the type constructor, we need to take into account the
//// // type instance
//// Type typeConstructor = nearestAncestor.typeConstructor();
//// Type typeInstance = nearestAncestor.getElement();
//// TypeParameter formalParameter = typeConstructor.parameter(TypeParameter.class,index);
//// TypeParameter actualParameter = typeInstance.parameter(TypeParameter.class, index);
//// TypeReference formalUpperBoundReference = formalParameter.upperBoundReference();
//// TypeReference clonedUpperBoundReference = clone(formalUpperBoundReference);
//// clonedUpperBoundReference.setUniParent(actualParameter);
////
////// Type result = formalParameter.upperBound(); // This fixes testGenericRejuse
//// Type result = clonedUpperBoundReference.getElement();
//// return result;
// }
@Override
public boolean uniSameAs(Element other) throws LookupException {
return other instanceof PureWildcard;
}
@Override
public Type upperBound() throws LookupException {
//return language(ObjectOrientedLanguage.class).getDefaultSuperClass();
return view(ObjectOrientedView.class).topLevelType();
}
@Override
public Verification verifySelf() {
return Valid.create();
}
public String toString(java.util.Set<Element> visited) {
return "?";
}
@Override
public boolean isWildCardBound() {
return true;
}
}
|
182362_3 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package deprecated_code;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
/**
*
* @author mswin
*/
public class DataHelper {
public static boolean dataEntryListContains(List<RawDataEntry> entryList, RawDataEntry entry) {
for (RawDataEntry tmp : entryList) {
if (tmp.isEquivalent(entry)) {
return true;
}
}
return false;
}
public static int minutesDiff(Date earlierDate, Date laterDate) {
if (earlierDate == null || laterDate == null) {
return 0;
}
return Math.abs((int) ((laterDate.getTime() / 60000) - (earlierDate.getTime() / 60000)));
}
// ###################################################################
// List computations
// ###################################################################
public static List<RawDataEntry> createCleanBgList(List<RawDataEntry> data) {
List<RawDataEntry> bgList = new ArrayList<>();
for (RawDataEntry item : data) {
// stronges is rf bg from measureing device
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[4])) {
bgList.add(item);
}
}
for (RawDataEntry item : data) {
// weaker is user entered values
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[3])) {
if (!dataEntryListContains(bgList, item)) {
bgList.add(item);
}
}
}
bgList.sort(RawDataEntry.getTimeSortComparator());
return bgList;
}
public static List<RawDataEntry> createHypoList(List<RawDataEntry> cleanBgList,
double threshold, int hypoTimeRange) {
List<RawDataEntry> listEntrys = new ArrayList<>();
RawDataEntry lastItem = null;
for (RawDataEntry item : cleanBgList) {
if (item.amount < threshold && item.amount > 0) {
// check if the item does belong to the same hypo
if (lastItem == null
|| minutesDiff(lastItem.timestamp,
item.timestamp) > hypoTimeRange) {
lastItem = item;
listEntrys.add(item);
}
} else if (item.amount > 0) {
// item that is over the threshold --> disconinues the series
lastItem = null;
}
}
// second pass to exclude
return listEntrys;
}
public static List<RawDataEntry> createHyperList(List<RawDataEntry> cleanBgList,
double threshold, int hyperTimeRange) {
List<RawDataEntry> listEntrys = new ArrayList<>();
for (RawDataEntry item : cleanBgList) {
if (item.amount > threshold && item.amount > 0) {
listEntrys.add(item);
}
}
return listEntrys;
}
public static List<RawDataEntry> createExerciseMarkerList(List<RawDataEntry> entryList) {
List<RawDataEntry> listEntrys = new ArrayList<>();
for (RawDataEntry item : entryList) {
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[2])) {
listEntrys.add(item);
}
}
return listEntrys;
}
public static List<RawDataEntry> createCleanPrimeList(List<RawDataEntry> data) {
List<RawDataEntry> primeList = new ArrayList<>();
for (RawDataEntry item : data) {
// strongest indicator for prime is rewind
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[0])) {
primeList.add(item);
// todo find corresbonding prime, and add amount
}
}
//TODO check is rewind has an prime bevore, if yes, don't add this
for (RawDataEntry item : data) {
// a little less strong is prime
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[1])) {
if (!dataEntryListContains(primeList, item)) {
primeList.add(item);
}
}
}
primeList.sort(RawDataEntry.getTimeSortComparator());
return primeList;
}
public static List<RawDataEntry> filterFollowingHypoValues(List<RawDataEntry> cleanBgList,
Date startTime, int minuteRange, double threshold) {
List<RawDataEntry> listEntrys = new ArrayList<>();
for (RawDataEntry item : cleanBgList) {
if (startTime.before(item.timestamp)
&& minutesDiff(item.timestamp, startTime) < minuteRange) {
listEntrys.add(item);
if (item.amount > threshold) {
// completes the series
break;
}
}
}
return listEntrys;
}
public static List<RawDataEntry> filterFollowingHyperValues(List<RawDataEntry> cleanBgList,
Date startTime, int minuteRange, double threshold) {
List<RawDataEntry> listEntrys = new ArrayList<>();
for (RawDataEntry item : cleanBgList) {
if (startTime.before(item.timestamp)
&& minutesDiff(item.timestamp, startTime) < minuteRange) {
listEntrys.add(item);
if (item.amount < threshold) {
// completes the series
break;
}
}
}
return listEntrys;
}
public static List<RawDataEntry> filterHistoryValues(List<RawDataEntry> entryList,
Date startTime, int minuteRange) {
List<RawDataEntry> listEntrys = new ArrayList<>();
for (RawDataEntry item : entryList) {
if (startTime.after(item.timestamp)
&& minutesDiff(item.timestamp, startTime) < minuteRange) {
listEntrys.add(item);
}
}
return listEntrys;
}
public static RawDataEntry filterNextValue(List<RawDataEntry> cleanBgList,
Date startTime) {
for (RawDataEntry item : cleanBgList) {
if (startTime.before(item.timestamp)) {
return item;
}
}
return null;
}
public static RawDataEntry filterLastValue(List<RawDataEntry> entryList,
Date startTime) {
for (int i = entryList.size() - 1; i >= 0; i--) {
RawDataEntry item = entryList.get(i);
if (startTime.after(item.timestamp)) {
return item;
}
}
return null;
}
public static boolean isUnitMmol(List<RawDataEntry> cleanBgList) {
double avg = 0;
for (RawDataEntry item : cleanBgList) {
avg += item.amount;
}
return (avg / cleanBgList.size()) < 50;
}
// this list is needed to create a combination of ke and bolus. --> later
// public static List<DataEntry> createCleanBolusList(List<DataEntry> data) {
// List<DataEntry> bolusList = new ArrayList<>();
//
// for (DataEntry item : data) {
// if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[6])) {
// bolusList.add(item);
// }
// }
//
// bolusList.sort(DataEntry.getTimeSortComparator());
// return bolusList;
// }
public static List<RawDataEntry> createCleanFoodBolusList(List<RawDataEntry> data) {
List<RawDataEntry> fullBolusList = new ArrayList<>();
List<RawDataEntry> bolusList = new ArrayList<>();
for (RawDataEntry item : data) {
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[5])) {
fullBolusList.add(item);
}
}
// fill up boli without wizard (uuhhh bad guys)
for (RawDataEntry item : data) {
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[6])) {
if (!dataEntryListContains(fullBolusList, item)) {
if (item.amount > 0.0) {
fullBolusList.add(item);
}
}
}
}
//remove correction entrys (needed to exclude boli)
for (RawDataEntry item : fullBolusList) {
if (item.amount > 0.0) {
bolusList.add(item);
}
}
bolusList.sort(RawDataEntry.getTimeSortComparator());
return bolusList;
}
public static List<RawDataEntry> filterTimeRange(List<RawDataEntry> list,
Date fromRagen, Date toRange) {
//TODO implement
return list;
}
// ###################################################################
// GUI Helper
// ###################################################################
public static String[] createGuiList(List<RawDataEntry> cleanList) {
List<String> listEntrys = new ArrayList<>();
for (RawDataEntry item : cleanList) {
listEntrys.add(item.toGuiListEntry());
}
return listEntrys.toArray(new String[]{});
}
// ###################################################################
// Export Helper
// ###################################################################
public static String createInformationMailBody(List<RawDataEntry> completeList,
List<RawDataEntry> primeList, List<RawDataEntry> bolusWizardList, List<RawDataEntry> hypoList,
List<RawDataEntry> hyperList, List<RawDataEntry> exerciseMarkerList,
double hypoThreshold, int hypoMealHistoryTime, int exerciseHistoryTime,
int wakupTime, int bedTime, int sleepThreshold, double hyperThreshold,
int hyperMealHistoryTime) {
StringBuilder sb = new StringBuilder();
SimpleDateFormat dformat = new SimpleDateFormat(Constants.DATE_TIME_OUTPUT_FORMAT);
// peamble
sb.append("\n\n\n\n");
// create Prime text
sb.append("Infusionsset-Wechsel:\n");
for (RawDataEntry item : primeList) {
sb.append(dformat.format(item.timestamp)).append(" routinemäßig\n");
}
// create hypo text
sb.append("\n\nHypoglykämien (<").append(hypoThreshold).append("):\n");
for (RawDataEntry item : hypoList) {
sb.append(item.toTextListEntry())
.append("\n");
sb.append("Gabe es Symptome? Ja.\n");
sb.append("Konnte die Unterzuckerung selbst behandelt werden? Ja.\n");
// calc last meals
List<RawDataEntry> lastMeals = DataHelper
.filterHistoryValues(bolusWizardList, item.timestamp, hypoMealHistoryTime);
if (lastMeals.isEmpty()) {
// if no value in range, show last available value
RawDataEntry lastValue = DataHelper.filterLastValue(bolusWizardList,
item.timestamp);
if (lastValue != null) {
sb.append("Letzte Hauptmahlzeit: ")
.append(lastValue.toTextListEntry()).append("\n");
} else {
sb.append("Letzte Hauptmahlzeit: ")
.append("ERROR").append("\n");
}
} else {
for (RawDataEntry meal : lastMeals) {
sb.append("Letzte Hauptmahlzeit: ")
.append(meal.toTextListEntry()).append("\n");
}
}
// calc exercise
sb.append("Stand in Zusammenhang mit körperlicher Aktivität? ");
List<RawDataEntry> exerciseMarker = DataHelper
.filterHistoryValues(exerciseMarkerList, item.timestamp,
exerciseHistoryTime);
if (exerciseMarker.isEmpty()) {
sb.append("Nein.\n");
} else {
sb.append("Ja.\n");
}
sb.append("Hatten sie Anzeichen von Krankheitssymptomen? Nein.\n");
// calc sleep
sb.append("Haben Sie geschlafen, als die Unterzuckerung auftrat? ");
RawDataEntry lastUserAction = DataHelper.filterLastValue(completeList,
item.timestamp);
if (lastUserAction != null) {
int lastEventMinutes = DataHelper.minutesDiff(lastUserAction.timestamp,
item.timestamp);
Calendar cal = new GregorianCalendar(Locale.GERMANY);
cal.setTime(item.timestamp);
if (lastEventMinutes > sleepThreshold && cal.get(Calendar.HOUR) > bedTime
|| cal.get(Calendar.HOUR_OF_DAY) < wakupTime) {
// inside sleep time and over threshold
sb.append("Ja.\nSind Sie von den Symptomen aufgewacht? Ja.\n");
} else if (lastEventMinutes < sleepThreshold && cal.get(Calendar.HOUR) < bedTime
|| cal.get(Calendar.HOUR_OF_DAY) > wakupTime) {
// there was an action and its day time
sb.append("Nein.\n");
} else {
sb.append("NO DATA\n");
}
} else {
sb.append("NO DATA\n");
}
sb.append("\n");
}
// create hyper text
sb.append("\n\nUnerklärliche Hyperglykämien (>").append(hyperThreshold).append("):\n");
for (RawDataEntry item : hyperList) {
sb.append(item.toTextListEntry()).append("\n");
// calc last meals
List<RawDataEntry> lastMeals = DataHelper
.filterHistoryValues(bolusWizardList, item.timestamp, hyperMealHistoryTime);
if (lastMeals.isEmpty()) {
// if no value in range, show last available value
RawDataEntry lastValue = DataHelper.filterLastValue(bolusWizardList,
item.timestamp);
if (lastValue != null) {
sb.append("Letzte Hauptmahlzeit: ")
.append(lastValue.toTextListEntry()).append("\n");
} else {
sb.append("Letzte Hauptmahlzeit: ")
.append("ERROR").append("\n");
}
} else {
for (RawDataEntry meal : lastMeals) {
sb.append("Letzte Hauptmahlzeit: ")
.append(meal.toTextListEntry()).append("\n");
}
}
sb.append("Keton im Blut: Nicht verfügbar.\n");
sb.append("Keton im Urin: \n\n");
}
return sb.toString();
}
}
| tiweGH/OpenDiabetes | engine/src/deprecated_code/DataHelper.java | 4,039 | // weaker is user entered values | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package deprecated_code;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
/**
*
* @author mswin
*/
public class DataHelper {
public static boolean dataEntryListContains(List<RawDataEntry> entryList, RawDataEntry entry) {
for (RawDataEntry tmp : entryList) {
if (tmp.isEquivalent(entry)) {
return true;
}
}
return false;
}
public static int minutesDiff(Date earlierDate, Date laterDate) {
if (earlierDate == null || laterDate == null) {
return 0;
}
return Math.abs((int) ((laterDate.getTime() / 60000) - (earlierDate.getTime() / 60000)));
}
// ###################################################################
// List computations
// ###################################################################
public static List<RawDataEntry> createCleanBgList(List<RawDataEntry> data) {
List<RawDataEntry> bgList = new ArrayList<>();
for (RawDataEntry item : data) {
// stronges is rf bg from measureing device
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[4])) {
bgList.add(item);
}
}
for (RawDataEntry item : data) {
// weaker is<SUF>
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[3])) {
if (!dataEntryListContains(bgList, item)) {
bgList.add(item);
}
}
}
bgList.sort(RawDataEntry.getTimeSortComparator());
return bgList;
}
public static List<RawDataEntry> createHypoList(List<RawDataEntry> cleanBgList,
double threshold, int hypoTimeRange) {
List<RawDataEntry> listEntrys = new ArrayList<>();
RawDataEntry lastItem = null;
for (RawDataEntry item : cleanBgList) {
if (item.amount < threshold && item.amount > 0) {
// check if the item does belong to the same hypo
if (lastItem == null
|| minutesDiff(lastItem.timestamp,
item.timestamp) > hypoTimeRange) {
lastItem = item;
listEntrys.add(item);
}
} else if (item.amount > 0) {
// item that is over the threshold --> disconinues the series
lastItem = null;
}
}
// second pass to exclude
return listEntrys;
}
public static List<RawDataEntry> createHyperList(List<RawDataEntry> cleanBgList,
double threshold, int hyperTimeRange) {
List<RawDataEntry> listEntrys = new ArrayList<>();
for (RawDataEntry item : cleanBgList) {
if (item.amount > threshold && item.amount > 0) {
listEntrys.add(item);
}
}
return listEntrys;
}
public static List<RawDataEntry> createExerciseMarkerList(List<RawDataEntry> entryList) {
List<RawDataEntry> listEntrys = new ArrayList<>();
for (RawDataEntry item : entryList) {
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[2])) {
listEntrys.add(item);
}
}
return listEntrys;
}
public static List<RawDataEntry> createCleanPrimeList(List<RawDataEntry> data) {
List<RawDataEntry> primeList = new ArrayList<>();
for (RawDataEntry item : data) {
// strongest indicator for prime is rewind
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[0])) {
primeList.add(item);
// todo find corresbonding prime, and add amount
}
}
//TODO check is rewind has an prime bevore, if yes, don't add this
for (RawDataEntry item : data) {
// a little less strong is prime
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[1])) {
if (!dataEntryListContains(primeList, item)) {
primeList.add(item);
}
}
}
primeList.sort(RawDataEntry.getTimeSortComparator());
return primeList;
}
public static List<RawDataEntry> filterFollowingHypoValues(List<RawDataEntry> cleanBgList,
Date startTime, int minuteRange, double threshold) {
List<RawDataEntry> listEntrys = new ArrayList<>();
for (RawDataEntry item : cleanBgList) {
if (startTime.before(item.timestamp)
&& minutesDiff(item.timestamp, startTime) < minuteRange) {
listEntrys.add(item);
if (item.amount > threshold) {
// completes the series
break;
}
}
}
return listEntrys;
}
public static List<RawDataEntry> filterFollowingHyperValues(List<RawDataEntry> cleanBgList,
Date startTime, int minuteRange, double threshold) {
List<RawDataEntry> listEntrys = new ArrayList<>();
for (RawDataEntry item : cleanBgList) {
if (startTime.before(item.timestamp)
&& minutesDiff(item.timestamp, startTime) < minuteRange) {
listEntrys.add(item);
if (item.amount < threshold) {
// completes the series
break;
}
}
}
return listEntrys;
}
public static List<RawDataEntry> filterHistoryValues(List<RawDataEntry> entryList,
Date startTime, int minuteRange) {
List<RawDataEntry> listEntrys = new ArrayList<>();
for (RawDataEntry item : entryList) {
if (startTime.after(item.timestamp)
&& minutesDiff(item.timestamp, startTime) < minuteRange) {
listEntrys.add(item);
}
}
return listEntrys;
}
public static RawDataEntry filterNextValue(List<RawDataEntry> cleanBgList,
Date startTime) {
for (RawDataEntry item : cleanBgList) {
if (startTime.before(item.timestamp)) {
return item;
}
}
return null;
}
public static RawDataEntry filterLastValue(List<RawDataEntry> entryList,
Date startTime) {
for (int i = entryList.size() - 1; i >= 0; i--) {
RawDataEntry item = entryList.get(i);
if (startTime.after(item.timestamp)) {
return item;
}
}
return null;
}
public static boolean isUnitMmol(List<RawDataEntry> cleanBgList) {
double avg = 0;
for (RawDataEntry item : cleanBgList) {
avg += item.amount;
}
return (avg / cleanBgList.size()) < 50;
}
// this list is needed to create a combination of ke and bolus. --> later
// public static List<DataEntry> createCleanBolusList(List<DataEntry> data) {
// List<DataEntry> bolusList = new ArrayList<>();
//
// for (DataEntry item : data) {
// if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[6])) {
// bolusList.add(item);
// }
// }
//
// bolusList.sort(DataEntry.getTimeSortComparator());
// return bolusList;
// }
public static List<RawDataEntry> createCleanFoodBolusList(List<RawDataEntry> data) {
List<RawDataEntry> fullBolusList = new ArrayList<>();
List<RawDataEntry> bolusList = new ArrayList<>();
for (RawDataEntry item : data) {
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[5])) {
fullBolusList.add(item);
}
}
// fill up boli without wizard (uuhhh bad guys)
for (RawDataEntry item : data) {
if (item.type.equalsIgnoreCase(Constants.CARELINK_TYPE[6])) {
if (!dataEntryListContains(fullBolusList, item)) {
if (item.amount > 0.0) {
fullBolusList.add(item);
}
}
}
}
//remove correction entrys (needed to exclude boli)
for (RawDataEntry item : fullBolusList) {
if (item.amount > 0.0) {
bolusList.add(item);
}
}
bolusList.sort(RawDataEntry.getTimeSortComparator());
return bolusList;
}
public static List<RawDataEntry> filterTimeRange(List<RawDataEntry> list,
Date fromRagen, Date toRange) {
//TODO implement
return list;
}
// ###################################################################
// GUI Helper
// ###################################################################
public static String[] createGuiList(List<RawDataEntry> cleanList) {
List<String> listEntrys = new ArrayList<>();
for (RawDataEntry item : cleanList) {
listEntrys.add(item.toGuiListEntry());
}
return listEntrys.toArray(new String[]{});
}
// ###################################################################
// Export Helper
// ###################################################################
public static String createInformationMailBody(List<RawDataEntry> completeList,
List<RawDataEntry> primeList, List<RawDataEntry> bolusWizardList, List<RawDataEntry> hypoList,
List<RawDataEntry> hyperList, List<RawDataEntry> exerciseMarkerList,
double hypoThreshold, int hypoMealHistoryTime, int exerciseHistoryTime,
int wakupTime, int bedTime, int sleepThreshold, double hyperThreshold,
int hyperMealHistoryTime) {
StringBuilder sb = new StringBuilder();
SimpleDateFormat dformat = new SimpleDateFormat(Constants.DATE_TIME_OUTPUT_FORMAT);
// peamble
sb.append("\n\n\n\n");
// create Prime text
sb.append("Infusionsset-Wechsel:\n");
for (RawDataEntry item : primeList) {
sb.append(dformat.format(item.timestamp)).append(" routinemäßig\n");
}
// create hypo text
sb.append("\n\nHypoglykämien (<").append(hypoThreshold).append("):\n");
for (RawDataEntry item : hypoList) {
sb.append(item.toTextListEntry())
.append("\n");
sb.append("Gabe es Symptome? Ja.\n");
sb.append("Konnte die Unterzuckerung selbst behandelt werden? Ja.\n");
// calc last meals
List<RawDataEntry> lastMeals = DataHelper
.filterHistoryValues(bolusWizardList, item.timestamp, hypoMealHistoryTime);
if (lastMeals.isEmpty()) {
// if no value in range, show last available value
RawDataEntry lastValue = DataHelper.filterLastValue(bolusWizardList,
item.timestamp);
if (lastValue != null) {
sb.append("Letzte Hauptmahlzeit: ")
.append(lastValue.toTextListEntry()).append("\n");
} else {
sb.append("Letzte Hauptmahlzeit: ")
.append("ERROR").append("\n");
}
} else {
for (RawDataEntry meal : lastMeals) {
sb.append("Letzte Hauptmahlzeit: ")
.append(meal.toTextListEntry()).append("\n");
}
}
// calc exercise
sb.append("Stand in Zusammenhang mit körperlicher Aktivität? ");
List<RawDataEntry> exerciseMarker = DataHelper
.filterHistoryValues(exerciseMarkerList, item.timestamp,
exerciseHistoryTime);
if (exerciseMarker.isEmpty()) {
sb.append("Nein.\n");
} else {
sb.append("Ja.\n");
}
sb.append("Hatten sie Anzeichen von Krankheitssymptomen? Nein.\n");
// calc sleep
sb.append("Haben Sie geschlafen, als die Unterzuckerung auftrat? ");
RawDataEntry lastUserAction = DataHelper.filterLastValue(completeList,
item.timestamp);
if (lastUserAction != null) {
int lastEventMinutes = DataHelper.minutesDiff(lastUserAction.timestamp,
item.timestamp);
Calendar cal = new GregorianCalendar(Locale.GERMANY);
cal.setTime(item.timestamp);
if (lastEventMinutes > sleepThreshold && cal.get(Calendar.HOUR) > bedTime
|| cal.get(Calendar.HOUR_OF_DAY) < wakupTime) {
// inside sleep time and over threshold
sb.append("Ja.\nSind Sie von den Symptomen aufgewacht? Ja.\n");
} else if (lastEventMinutes < sleepThreshold && cal.get(Calendar.HOUR) < bedTime
|| cal.get(Calendar.HOUR_OF_DAY) > wakupTime) {
// there was an action and its day time
sb.append("Nein.\n");
} else {
sb.append("NO DATA\n");
}
} else {
sb.append("NO DATA\n");
}
sb.append("\n");
}
// create hyper text
sb.append("\n\nUnerklärliche Hyperglykämien (>").append(hyperThreshold).append("):\n");
for (RawDataEntry item : hyperList) {
sb.append(item.toTextListEntry()).append("\n");
// calc last meals
List<RawDataEntry> lastMeals = DataHelper
.filterHistoryValues(bolusWizardList, item.timestamp, hyperMealHistoryTime);
if (lastMeals.isEmpty()) {
// if no value in range, show last available value
RawDataEntry lastValue = DataHelper.filterLastValue(bolusWizardList,
item.timestamp);
if (lastValue != null) {
sb.append("Letzte Hauptmahlzeit: ")
.append(lastValue.toTextListEntry()).append("\n");
} else {
sb.append("Letzte Hauptmahlzeit: ")
.append("ERROR").append("\n");
}
} else {
for (RawDataEntry meal : lastMeals) {
sb.append("Letzte Hauptmahlzeit: ")
.append(meal.toTextListEntry()).append("\n");
}
}
sb.append("Keton im Blut: Nicht verfügbar.\n");
sb.append("Keton im Urin: \n\n");
}
return sb.toString();
}
}
|
108716_5 | /*
* B3P Commons Core is a library with commonly used classes for webapps.
* Included are clieop3, oai, security, struts, taglibs and other
* general helper classes and extensions.
*
* Copyright 2000 - 2008 B3Partners BV
*
* This file is part of B3P Commons Core.
*
* B3P Commons Core 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.
*
* B3P Commons Core 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 B3P Commons Core. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* $Id: ASelectTicket.java 2291 2006-01-12 09:51:50Z Matthijs $
*/
package nl.b3p.commons.security.aselect;
import java.util.Date;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Deze class stelt een A-Select ticket voor en wordt door de
* ASelectAuthorizationFilter op de sessie gezet indien de gebruiker
* geautoriseerd is via A-Select.
* <p>
* Webapplicaties kunnen gebruik maken van dit object uit de sessie om toegang
* te krijgen tot de eigenschappen van de ingelogde gebruiker. Met de static
* methode <code>getFromSession(HttpSession session)</code> kan een ticket
* uit een sessie worden gehaald.
* <p>
* @author matthijsln
*/
public abstract class ASelectTicket {
protected static Log log = LogFactory.getLog(ASelectTicket.class);
/**
* Onder deze key wordt een ticket opgeslagen in een HttpSession
*/
private static final String TICKET_SESSION_KEY = ASelectTicket.class.getName() + ".TICKET";
/* A-Select ticket attributen */
private String ticket;
private String appId;
private String uid;
private String organization;
private Date startTime;
private Date expirationTime;
private String authSPLevel;
private String authSP;
private String attributes;
/* TODO: base64/cgi/url decode attributes naar Map, wordt nu niet gedecodeerd */
private HttpSession session;
protected ASelectTicket(String ticket, String appId, Date startTime, Date expTime, String uid,
String organization, String authSPLevel, String authSP, String attributes) {
this.ticket = ticket;
this.appId = appId;
this.startTime = startTime;
this.expirationTime = expTime;
this.uid = uid;
this.organization = organization;
this.authSPLevel = authSPLevel;
this.attributes = attributes;
}
protected abstract void doVerify()
throws IOException, ASelectAuthorizationException;
/**
* Verifieert of het ticket geldig is.
* <p>
* <b>Indien dit ticket niet geldig is wordt deze uit de sessie verwijderd en
* wordt een ASelectAuthorizationException gethrowed.</b>
*
* @throws ASelectAuthorizationException als het ticket ongeldig is
* @throws IOException indien er een fout optreedt bij communicatie met A-Select
* @throws UnsupportedOperationException indien deze methode niet van
* toepassing is (bij webserver-filter api)
*/
public void verify()
throws IOException, ASelectAuthorizationException {
try {
doVerify();
} catch (ASelectAuthorizationException aae) {
removeFromSession();
throw aae;
}
}
protected abstract void doKill()
throws IOException;
/**
* Maakt het ticket ongeldig en verwijderd deze uit de sessie.
*/
public void kill()
throws IOException {
doKill();
removeFromSession();
}
private void removeFromSession() {
if (session != null) {
session.removeAttribute(TICKET_SESSION_KEY);
}
}
/**
* Deze methode heeft package visibility omdat alleen ASelectAuthorizationFilter
* een ticket op de sessie kan zetten.
*/
void putOnSession(HttpSession session) {
this.session = session;
session.setAttribute(TICKET_SESSION_KEY, this);
}
/**
* Geeft het A-Select ticket indien die aanwezig is in de sessie of
* null wanneer er geen ticket is of de sessie ongeldig is.
*/
public static ASelectTicket getFromSession(HttpSession session) {
ASelectTicket t = null;
try {
t = (ASelectTicket) session.getAttribute(TICKET_SESSION_KEY);
} catch (IllegalStateException ise) {
log.error("getFromSession(): session IllegalStateException");
} catch (ClassCastException cce) {
log.error("getFromSession(): not an ASelectTicket object in session", cce);
}
return t;
}
/**
* @return ticket id dat door de A-Select server is afgegeven na verificatie van
* de credentials. Deze waarde is opaque voor de applicatie.
*/
public String getTicketId() {
return ticket;
}
public String getAppId() {
return appId;
}
public String getUid() {
return uid;
}
public String getOrganization() {
return organization;
}
/**
* @return de attributen zoals die zijn ontvangen van A-Select, niet
* base64/cgi/url gedecodeerd
*/
public String getUndecodedAttributes() {
return attributes;
}
public Date getStartTime() {
return startTime;
}
public Date getExpirationTime() {
return expirationTime;
}
public String getAuthSPLevel() {
return authSPLevel;
}
public String getAuthSP() {
return authSP;
}
}
| tjidde-nl/b3p-commons-core | src/main/java/nl/b3p/commons/security/aselect/ASelectTicket.java | 1,686 | /* TODO: base64/cgi/url decode attributes naar Map, wordt nu niet gedecodeerd */ | block_comment | nl | /*
* B3P Commons Core is a library with commonly used classes for webapps.
* Included are clieop3, oai, security, struts, taglibs and other
* general helper classes and extensions.
*
* Copyright 2000 - 2008 B3Partners BV
*
* This file is part of B3P Commons Core.
*
* B3P Commons Core 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.
*
* B3P Commons Core 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 B3P Commons Core. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* $Id: ASelectTicket.java 2291 2006-01-12 09:51:50Z Matthijs $
*/
package nl.b3p.commons.security.aselect;
import java.util.Date;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Deze class stelt een A-Select ticket voor en wordt door de
* ASelectAuthorizationFilter op de sessie gezet indien de gebruiker
* geautoriseerd is via A-Select.
* <p>
* Webapplicaties kunnen gebruik maken van dit object uit de sessie om toegang
* te krijgen tot de eigenschappen van de ingelogde gebruiker. Met de static
* methode <code>getFromSession(HttpSession session)</code> kan een ticket
* uit een sessie worden gehaald.
* <p>
* @author matthijsln
*/
public abstract class ASelectTicket {
protected static Log log = LogFactory.getLog(ASelectTicket.class);
/**
* Onder deze key wordt een ticket opgeslagen in een HttpSession
*/
private static final String TICKET_SESSION_KEY = ASelectTicket.class.getName() + ".TICKET";
/* A-Select ticket attributen */
private String ticket;
private String appId;
private String uid;
private String organization;
private Date startTime;
private Date expirationTime;
private String authSPLevel;
private String authSP;
private String attributes;
/* TODO: base64/cgi/url decode<SUF>*/
private HttpSession session;
protected ASelectTicket(String ticket, String appId, Date startTime, Date expTime, String uid,
String organization, String authSPLevel, String authSP, String attributes) {
this.ticket = ticket;
this.appId = appId;
this.startTime = startTime;
this.expirationTime = expTime;
this.uid = uid;
this.organization = organization;
this.authSPLevel = authSPLevel;
this.attributes = attributes;
}
protected abstract void doVerify()
throws IOException, ASelectAuthorizationException;
/**
* Verifieert of het ticket geldig is.
* <p>
* <b>Indien dit ticket niet geldig is wordt deze uit de sessie verwijderd en
* wordt een ASelectAuthorizationException gethrowed.</b>
*
* @throws ASelectAuthorizationException als het ticket ongeldig is
* @throws IOException indien er een fout optreedt bij communicatie met A-Select
* @throws UnsupportedOperationException indien deze methode niet van
* toepassing is (bij webserver-filter api)
*/
public void verify()
throws IOException, ASelectAuthorizationException {
try {
doVerify();
} catch (ASelectAuthorizationException aae) {
removeFromSession();
throw aae;
}
}
protected abstract void doKill()
throws IOException;
/**
* Maakt het ticket ongeldig en verwijderd deze uit de sessie.
*/
public void kill()
throws IOException {
doKill();
removeFromSession();
}
private void removeFromSession() {
if (session != null) {
session.removeAttribute(TICKET_SESSION_KEY);
}
}
/**
* Deze methode heeft package visibility omdat alleen ASelectAuthorizationFilter
* een ticket op de sessie kan zetten.
*/
void putOnSession(HttpSession session) {
this.session = session;
session.setAttribute(TICKET_SESSION_KEY, this);
}
/**
* Geeft het A-Select ticket indien die aanwezig is in de sessie of
* null wanneer er geen ticket is of de sessie ongeldig is.
*/
public static ASelectTicket getFromSession(HttpSession session) {
ASelectTicket t = null;
try {
t = (ASelectTicket) session.getAttribute(TICKET_SESSION_KEY);
} catch (IllegalStateException ise) {
log.error("getFromSession(): session IllegalStateException");
} catch (ClassCastException cce) {
log.error("getFromSession(): not an ASelectTicket object in session", cce);
}
return t;
}
/**
* @return ticket id dat door de A-Select server is afgegeven na verificatie van
* de credentials. Deze waarde is opaque voor de applicatie.
*/
public String getTicketId() {
return ticket;
}
public String getAppId() {
return appId;
}
public String getUid() {
return uid;
}
public String getOrganization() {
return organization;
}
/**
* @return de attributen zoals die zijn ontvangen van A-Select, niet
* base64/cgi/url gedecodeerd
*/
public String getUndecodedAttributes() {
return attributes;
}
public Date getStartTime() {
return startTime;
}
public Date getExpirationTime() {
return expirationTime;
}
public String getAuthSPLevel() {
return authSPLevel;
}
public String getAuthSP() {
return authSP;
}
}
|
64038_0 | package nl.b3p.kv7netwerk;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
*
* @author Matthijs Laan
*/
public class DataParser {
private final BufferedReader reader;
private String pushedBackLine;
private String[] groupFields, tableInfo, tableFields, row;
public DataParser(InputStream is) throws Exception {
reader = new BufferedReader(new InputStreamReader(is));
readGroup();
}
private String nextLine() throws IOException {
if(pushedBackLine != null) {
String l = pushedBackLine;
pushedBackLine = null;
return l;
}
String l = reader.readLine();
while(l != null && l.trim().length() == 0) {
l = reader.readLine();
}
return l == null ? null : l.trim();
}
public void close() throws IOException {
reader.close();
}
private static String[] parseFields(String l) {
String[] split = l.split("\\|");
for(int i = 0; i < split.length; i++) {
String s = split[i];
if("\\0".equals(s)) {
split[i] = null;
continue;
}
split[i] = s.replace("\\r", "\r").replace("\\n", "\n").replace("\\i", "\\").replace("\\p", "|");
}
return split;
}
private void readGroup() throws Exception {
String l = nextLine();
if(l == null || !l.startsWith("\\G")) {
throw new Exception("Ongeldig data formaat, verwacht regel met \\G, gelezen " + l);
}
groupFields = parseFields(l.substring(2));
}
public String[][] nextTable() throws Exception {
String l = nextLine();
while(l != null && !l.startsWith("\\T")) {
l = nextLine();
}
if(l == null) {
return null;
}
tableInfo = parseFields(l.substring(2));
l = nextLine();
if(l == null || !l.startsWith("\\L")) {
throw new Exception("Ongeldig data formaat, verwacht regel met \\L, gelezen " + l);
}
tableFields = parseFields(l.substring(2));
return new String[][] { tableInfo, tableFields };
}
public String[] nextRow() throws Exception {
String l = nextLine();
if(l == null) {
return null;
}
if(l.startsWith("\\T")) {
pushedBackLine = l;
return null;
}
row = parseFields(l);
return row;
}
public String[] getGroupFields() {
return groupFields;
}
public String[] getTableInfo() {
return tableInfo;
}
public String[] getTableFields() {
return tableFields;
}
public String[] getRow() {
return row;
}
public static void main(String[] args) throws Exception {
DataParser dp = new DataParser(new FileInputStream("/home/matthijsln/1157-2015-03-02_22_51_25.txt"));
System.out.println("Group: " + Arrays.toString(dp.getGroupFields()));
String[][] table;
while((table = dp.nextTable()) != null) {
System.out.println("Table: " + Arrays.toString(table[0]) + ", fields: " + Arrays.toString(table[1]));
String[] row;
while((row = dp.nextRow()) != null) {
System.out.println(" " + Arrays.toString(row));
}
}
}
}
| tjidde-nl/geo-ov-kv7netwerk | src/main/java/nl/b3p/kv7netwerk/DataParser.java | 1,027 | /**
*
* @author Matthijs Laan
*/ | block_comment | nl | package nl.b3p.kv7netwerk;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
*
* @author Matthijs Laan<SUF>*/
public class DataParser {
private final BufferedReader reader;
private String pushedBackLine;
private String[] groupFields, tableInfo, tableFields, row;
public DataParser(InputStream is) throws Exception {
reader = new BufferedReader(new InputStreamReader(is));
readGroup();
}
private String nextLine() throws IOException {
if(pushedBackLine != null) {
String l = pushedBackLine;
pushedBackLine = null;
return l;
}
String l = reader.readLine();
while(l != null && l.trim().length() == 0) {
l = reader.readLine();
}
return l == null ? null : l.trim();
}
public void close() throws IOException {
reader.close();
}
private static String[] parseFields(String l) {
String[] split = l.split("\\|");
for(int i = 0; i < split.length; i++) {
String s = split[i];
if("\\0".equals(s)) {
split[i] = null;
continue;
}
split[i] = s.replace("\\r", "\r").replace("\\n", "\n").replace("\\i", "\\").replace("\\p", "|");
}
return split;
}
private void readGroup() throws Exception {
String l = nextLine();
if(l == null || !l.startsWith("\\G")) {
throw new Exception("Ongeldig data formaat, verwacht regel met \\G, gelezen " + l);
}
groupFields = parseFields(l.substring(2));
}
public String[][] nextTable() throws Exception {
String l = nextLine();
while(l != null && !l.startsWith("\\T")) {
l = nextLine();
}
if(l == null) {
return null;
}
tableInfo = parseFields(l.substring(2));
l = nextLine();
if(l == null || !l.startsWith("\\L")) {
throw new Exception("Ongeldig data formaat, verwacht regel met \\L, gelezen " + l);
}
tableFields = parseFields(l.substring(2));
return new String[][] { tableInfo, tableFields };
}
public String[] nextRow() throws Exception {
String l = nextLine();
if(l == null) {
return null;
}
if(l.startsWith("\\T")) {
pushedBackLine = l;
return null;
}
row = parseFields(l);
return row;
}
public String[] getGroupFields() {
return groupFields;
}
public String[] getTableInfo() {
return tableInfo;
}
public String[] getTableFields() {
return tableFields;
}
public String[] getRow() {
return row;
}
public static void main(String[] args) throws Exception {
DataParser dp = new DataParser(new FileInputStream("/home/matthijsln/1157-2015-03-02_22_51_25.txt"));
System.out.println("Group: " + Arrays.toString(dp.getGroupFields()));
String[][] table;
while((table = dp.nextTable()) != null) {
System.out.println("Table: " + Arrays.toString(table[0]) + ", fields: " + Arrays.toString(table[1]));
String[] row;
while((row = dp.nextRow()) != null) {
System.out.println(" " + Arrays.toString(row));
}
}
}
}
|
61030_20 | /**
* KAR Geo Tool - applicatie voor het registreren van KAR meldpunten
*
* Copyright (C) 2009-2013 B3Partners B.V.
*
* 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 nl.b3p.incaa;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.PrecisionModel;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Message;
import net.sourceforge.stripes.action.SimpleMessage;
import net.sourceforge.stripes.validation.SimpleError;
import nl.b3p.kar.hibernate.ActivationPoint;
import nl.b3p.kar.hibernate.ActivationPointSignal;
import nl.b3p.kar.hibernate.DataOwner;
import nl.b3p.kar.hibernate.Gebruiker;
import nl.b3p.kar.hibernate.KarAttributes;
import nl.b3p.kar.hibernate.Movement;
import nl.b3p.kar.hibernate.MovementActivationPoint;
import nl.b3p.kar.hibernate.RoadsideEquipment;
import nl.b3p.kar.hibernate.VehicleType;
import nl.b3p.kar.imp.KV9ValidationError;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Meine Toonen [email protected]
*/
public class IncaaImport {
public IncaaImport() {
}
private static final int RIJKSDRIEHOEKSTELSEL = 28992;
// Intermediate format: Map<karrAddres, Map<signalGroupNumber, Movement>
private Map<Integer, Map<Integer, Movement>> movements;
// Opzoeklijstje obv karaddress
private Map<Integer, RoadsideEquipment> rseqs;
// Hou de Points per rseq bij, om later de positie van de rseq te genereren (centroïde)
private Map<Integer, List<Point>> rseqLocations;
/**
* Importeer een reader van een .ptx bestand.
* @param in Reader van een INCAA .ptx bestand.
* @param g Gebruiker om het voor te importeren
* @param context Context om meldingen terug te geven naar de gebruiker over rseqs die niet geimporteerd konden worden
* @return De lijst van geïmporteerde roadside equipments
* @throws Exception Wordt gegooid als het parsen/opslaan mis gaat.
*/
public List<RoadsideEquipment> importPtx(Reader in, Gebruiker g, ActionBeanContext context) throws Exception {
JSONObject profile = new JSONObject(g.getProfile());
JSONObject defaultKarAttributes = profile.getJSONObject("defaultKarAttributes");
// (Her)initialiseer de intermediate formats.
movements = new HashMap();
rseqs = new HashMap();
rseqLocations = new HashMap();
// Definieer een parser en parse de ptx file
CSVFormat format = CSVFormat.newFormat('\t');
format.withQuote('"');
format.withCommentMarker('#');
Iterable<CSVRecord> parser = format.parse(in);
//Iterable<CSVRecord> parser = CSVFormat.newBuilder().withCommentStart('#').withDelimiter('\t').withQuoteChar('"').parse(in);
List<Message> messages = new ArrayList<Message>();
for (CSVRecord csvRecord : parser) {
try{
parseRecord(csvRecord, messages);
}catch (IllegalArgumentException e){
context.getValidationErrors().add("Kruispunt mislukt", new SimpleError(e.getMessage()));
}
}
// Sla de boel op
EntityManager em = Stripersist.getEntityManager();
List<RoadsideEquipment> savedRseqs = new ArrayList();
// ??? XXX is rseqs niet altijd empty?
for (Integer karAddress : rseqs.keySet()) {
RoadsideEquipment rseq = rseqs.get(karAddress);
if(g.canEdit(rseq)){
// Maak van alle punten binnen een rseq een centroïde en gebruik dat als locatie van de rseq zelf
List<Point> points = rseqLocations.get(rseq.getKarAddress());
GeometryFactory gf = new GeometryFactory(new PrecisionModel(), RIJKSDRIEHOEKSTELSEL);
GeometryCollection gc = new GeometryCollection(points.toArray(new Point[points.size()]), gf);
rseq.setLocation(gc.getCentroid());
for (ActivationPoint point : rseq.getPoints()) {
em.persist(point);
}
rseq.setVehicleType(rseq.determineType());
int validationErrors = rseq.validateKV9(new ArrayList<KV9ValidationError>());
rseq.setValidationErrors(validationErrors);
getKarAttributes(defaultKarAttributes, rseq);
em.persist(rseq);
savedRseqs.add(rseq);
messages.add(new SimpleMessage("Kruispunt met KAR-adres " + rseq.getKarAddress() + " is geïmporteerd"));
}
}
context.getMessages().add(new SimpleMessage(("Er zijn " + rseqs.size() + " verkeerssystemen succesvol geïmporteerd.")));
context.getMessages().addAll(messages);
em.getTransaction().commit();
return savedRseqs;
}
private void parseRecord(CSVRecord record,List<Message> messages) throws IllegalArgumentException{
ActivationPoint ap = new ActivationPoint();
EntityManager em = Stripersist.getEntityManager();
// Haal de data uit het csv record
String beheercode = record.get(0);
String x = record.get(1);
String y = record.get(2);
Integer karAddress = Integer.parseInt(record.get(3));
Integer signalGroupNumber = Integer.parseInt(record.get(4));
Integer distanceTillStopline = Integer.parseInt(record.get(5));
Integer timeTillStopline = Integer.parseInt(record.get(6));
Integer commandType = Integer.parseInt(record.get(7));
Integer triggerType = 0;
try {
triggerType = Integer.parseInt(record.get(8));// Niet zeker. Mogelijke vertalingen: 0,1: forced, 2,3,4,5: manual
} catch (IndexOutOfBoundsException ex) {
// Niet nodig, optioneel veld
}
if(triggerType < 0 ||triggerType > 255){
throw new IllegalArgumentException("Triggertype not recognized: " + triggerType);
}
// Alleen vehicletypes behorende bij de groep hulpdiensten: ptx is voor hulpdiensten
List<VehicleType> vehicleTypes = em.createQuery("from VehicleType where groep = :h order by nummer")
.setParameter("h", VehicleType.VEHICLE_TYPE_HULPDIENSTEN)
.getResultList();
// Maak een ActivationPointSignal obv de gegevens uit de ptx
ActivationPointSignal aps = new ActivationPointSignal();
aps.setDistanceTillStopLine(distanceTillStopline);
aps.setSignalGroupNumber(signalGroupNumber);
aps.setKarCommandType(commandType);
aps.setTriggerType("" + triggerType);
aps.setVehicleTypes(vehicleTypes);
// Haal objecten op om aan elkaar te linken
DataOwner dataOwner = getDataOwner(beheercode);
Movement movement = getMovement(karAddress, signalGroupNumber, dataOwner, messages);
RoadsideEquipment rseq = movement.getRoadsideEquipment();
Set<ActivationPoint> ps = rseq.getPoints();
int maxNr = 0;
for(ActivationPoint p: ps) {
maxNr = Math.max(maxNr, p.getNummer());
}
ap.setNummer(maxNr + 1);
ps.add(ap);
// Maak geometrie
int xInt = Integer.parseInt(x);
int yInt = Integer.parseInt(y);
ap.setX(xInt);
ap.setY(yInt);
addPoint(karAddress, ap.getLocation());
ap.setRoadsideEquipment(rseq);
em.persist(ap);
// Maak MovementActivationPoint
MovementActivationPoint map = new MovementActivationPoint();
map.setPoint(ap);
map.setMovement(movement);
map.setBeginEndOrActivation(MovementActivationPoint.ACTIVATION); // geen begin/eindpunt in INCAA
map.setSignal(aps);
em.persist(map);
movement.getPoints().add(map);
}
/**
* Haal de movement op behorende bij het karAdress en signalGroupNumber. Binnen een .ptx gaan we ervan uit dat een karAdres 1 rseq
* vertegenwoordigd en een punten gegroepeerd op signalGroupNumber een movement vormen.
* Mocht deze movement nog niet bestaan, dan wordt hij aangemaakt.
* @param karAddress KarAddress dat binnen dit .ptx bestand een rseq vertegenwoordigd
* @param signalGroupNumber Signaalgroepnummer dat binnen de rseq van @karAddress een movement identificeert
* @return De movement binnen een rseq met karAddress @karAddres en met signaalgroepnummer @signalGroupNumber
*/
private Movement getMovement(Integer karAddress, Integer signalGroupNumber, DataOwner dataOwner,List<Message> messages) throws IllegalArgumentException{
Movement mvmnt = null;
RoadsideEquipment rseq = getRseq(karAddress,dataOwner, messages);
EntityManager em = Stripersist.getEntityManager();
if (!movements.containsKey(karAddress)) {
Map<Integer, Movement> signalGroupMovement = new HashMap<Integer, Movement>();
mvmnt = new Movement();
mvmnt.setRoadsideEquipment(rseq);
mvmnt.setNummer(rseq.getMovements().size() + 1);
em.persist(mvmnt);
signalGroupMovement.put(signalGroupNumber, mvmnt);
rseq.getMovements().add(mvmnt);
movements.put(karAddress, signalGroupMovement);
} else {
Map<Integer, Movement> signalGroupMovement = movements.get(karAddress);
if (!signalGroupMovement.containsKey(signalGroupNumber)) {
mvmnt = new Movement();
mvmnt.setRoadsideEquipment(rseq);
mvmnt.setNummer(rseq.getMovements().size() + 1);
signalGroupMovement.put(signalGroupNumber, mvmnt);
em.persist(mvmnt);
rseq.getMovements().add(mvmnt);
movements.put(karAddress, signalGroupMovement);
}
}
mvmnt = movements.get(karAddress).get(signalGroupNumber);
return mvmnt;
}
/**
*
* @param karAddres Haal de rseq op dat aangeduid wordt met een karAddress
* @return
*/
private RoadsideEquipment getRseq(Integer karAddres, DataOwner dataOwner, List<Message> messages) throws IllegalArgumentException{
RoadsideEquipment rseq = null;
if (!rseqs.containsKey(karAddres)) {
EntityManager em = Stripersist.getEntityManager();
List<RoadsideEquipment> rseqsList = em.createQuery("FROM RoadsideEquipment WHERE dataOwner = :do and karAddress = :karAddress", RoadsideEquipment.class).setParameter("do", dataOwner).setParameter("karAddress", karAddres).getResultList();
if (rseqsList.size() > 0) {
if (rseqsList.size() == 1) {
rseq = rseqsList.get(0);
if (rseq.getVehicleType() == null || rseq.getVehicleType().equals(VehicleType.VEHICLE_TYPE_OV)) {
messages.add(new SimpleMessage("Kruispunt met KAR-adres " + karAddres + " bestaat al, maar heeft nog geen hulpdienstpunten. Hulpdienstpunten worden toegevoegd."));
}else{
throw new IllegalArgumentException("Kruispunt met KAR-adres " + karAddres + " heeft al hulpdienst punten");
}
} else {
throw new IllegalArgumentException("Meerdere kruispunten gevonden voor KAR-adres " + karAddres + " en wegbeheerder " + dataOwner.getOmschrijving());
}
}
if (rseq == null) {
rseq = new RoadsideEquipment();
rseq.setKarAddress(karAddres);
rseq.setDataOwner(dataOwner);
rseq.setType(RoadsideEquipment.TYPE_CROSSING);
rseq.setValidFrom(new Date());
em.persist(rseq);
}
rseqs.put(karAddres, rseq);
}
rseq = rseqs.get(karAddres);
return rseq;
}
private DataOwner getDataOwner(String code) {
try{
EntityManager em = Stripersist.getEntityManager();
DataOwner dataOwner = (DataOwner) em.createQuery("from DataOwner where code = :code ").setParameter("code", code).getSingleResult();
return dataOwner;
}catch(NoResultException ex){
throw new NoResultException("Kan databeheerder niet ophalen voor code: "+ code);
}
}
/**
* Voeg een punt toe aan een lijstje voor een rseq met kar adres @karAddress. Voor latere verwerking tot centroïde voor de locatie van het rseq..
* @param karAddress
* @param p
*/
private void addPoint(Integer karAddress, Point p) {
if (!rseqLocations.containsKey(karAddress)) {
rseqLocations.put(karAddress, new ArrayList<Point>());
}
rseqLocations.get(karAddress).add(p);
}
private void getKarAttributes(JSONObject attributes, RoadsideEquipment rseq) throws JSONException{
for (Iterator it = attributes.keys(); it.hasNext();) {
String serviceType = (String) it.next();
JSONArray perCommandType = attributes.getJSONArray(serviceType);
KarAttributes ka = new KarAttributes(
serviceType,
ActivationPointSignal.COMMAND_INMELDPUNT,
perCommandType.getJSONArray(0));
if (ka.getUsedAttributesMask() != 0) {
rseq.getKarAttributes().add(ka);
}
ka = new KarAttributes(
serviceType,
ActivationPointSignal.COMMAND_UITMELDPUNT,
perCommandType.getJSONArray(1));
if (ka.getUsedAttributesMask() != 0) {
rseq.getKarAttributes().add(ka);
}
ka = new KarAttributes(
serviceType,
ActivationPointSignal.COMMAND_VOORINMELDPUNT,
perCommandType.getJSONArray(2));
if (ka.getUsedAttributesMask() != 0) {
rseq.getKarAttributes().add(ka);
}
}
}
}
| tjidde-nl/kargeotool | src/main/java/nl/b3p/incaa/IncaaImport.java | 4,573 | /**
*
* @param karAddres Haal de rseq op dat aangeduid wordt met een karAddress
* @return
*/ | block_comment | nl | /**
* KAR Geo Tool - applicatie voor het registreren van KAR meldpunten
*
* Copyright (C) 2009-2013 B3Partners B.V.
*
* 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 nl.b3p.incaa;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.PrecisionModel;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Message;
import net.sourceforge.stripes.action.SimpleMessage;
import net.sourceforge.stripes.validation.SimpleError;
import nl.b3p.kar.hibernate.ActivationPoint;
import nl.b3p.kar.hibernate.ActivationPointSignal;
import nl.b3p.kar.hibernate.DataOwner;
import nl.b3p.kar.hibernate.Gebruiker;
import nl.b3p.kar.hibernate.KarAttributes;
import nl.b3p.kar.hibernate.Movement;
import nl.b3p.kar.hibernate.MovementActivationPoint;
import nl.b3p.kar.hibernate.RoadsideEquipment;
import nl.b3p.kar.hibernate.VehicleType;
import nl.b3p.kar.imp.KV9ValidationError;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.stripesstuff.stripersist.Stripersist;
/**
*
* @author Meine Toonen [email protected]
*/
public class IncaaImport {
public IncaaImport() {
}
private static final int RIJKSDRIEHOEKSTELSEL = 28992;
// Intermediate format: Map<karrAddres, Map<signalGroupNumber, Movement>
private Map<Integer, Map<Integer, Movement>> movements;
// Opzoeklijstje obv karaddress
private Map<Integer, RoadsideEquipment> rseqs;
// Hou de Points per rseq bij, om later de positie van de rseq te genereren (centroïde)
private Map<Integer, List<Point>> rseqLocations;
/**
* Importeer een reader van een .ptx bestand.
* @param in Reader van een INCAA .ptx bestand.
* @param g Gebruiker om het voor te importeren
* @param context Context om meldingen terug te geven naar de gebruiker over rseqs die niet geimporteerd konden worden
* @return De lijst van geïmporteerde roadside equipments
* @throws Exception Wordt gegooid als het parsen/opslaan mis gaat.
*/
public List<RoadsideEquipment> importPtx(Reader in, Gebruiker g, ActionBeanContext context) throws Exception {
JSONObject profile = new JSONObject(g.getProfile());
JSONObject defaultKarAttributes = profile.getJSONObject("defaultKarAttributes");
// (Her)initialiseer de intermediate formats.
movements = new HashMap();
rseqs = new HashMap();
rseqLocations = new HashMap();
// Definieer een parser en parse de ptx file
CSVFormat format = CSVFormat.newFormat('\t');
format.withQuote('"');
format.withCommentMarker('#');
Iterable<CSVRecord> parser = format.parse(in);
//Iterable<CSVRecord> parser = CSVFormat.newBuilder().withCommentStart('#').withDelimiter('\t').withQuoteChar('"').parse(in);
List<Message> messages = new ArrayList<Message>();
for (CSVRecord csvRecord : parser) {
try{
parseRecord(csvRecord, messages);
}catch (IllegalArgumentException e){
context.getValidationErrors().add("Kruispunt mislukt", new SimpleError(e.getMessage()));
}
}
// Sla de boel op
EntityManager em = Stripersist.getEntityManager();
List<RoadsideEquipment> savedRseqs = new ArrayList();
// ??? XXX is rseqs niet altijd empty?
for (Integer karAddress : rseqs.keySet()) {
RoadsideEquipment rseq = rseqs.get(karAddress);
if(g.canEdit(rseq)){
// Maak van alle punten binnen een rseq een centroïde en gebruik dat als locatie van de rseq zelf
List<Point> points = rseqLocations.get(rseq.getKarAddress());
GeometryFactory gf = new GeometryFactory(new PrecisionModel(), RIJKSDRIEHOEKSTELSEL);
GeometryCollection gc = new GeometryCollection(points.toArray(new Point[points.size()]), gf);
rseq.setLocation(gc.getCentroid());
for (ActivationPoint point : rseq.getPoints()) {
em.persist(point);
}
rseq.setVehicleType(rseq.determineType());
int validationErrors = rseq.validateKV9(new ArrayList<KV9ValidationError>());
rseq.setValidationErrors(validationErrors);
getKarAttributes(defaultKarAttributes, rseq);
em.persist(rseq);
savedRseqs.add(rseq);
messages.add(new SimpleMessage("Kruispunt met KAR-adres " + rseq.getKarAddress() + " is geïmporteerd"));
}
}
context.getMessages().add(new SimpleMessage(("Er zijn " + rseqs.size() + " verkeerssystemen succesvol geïmporteerd.")));
context.getMessages().addAll(messages);
em.getTransaction().commit();
return savedRseqs;
}
private void parseRecord(CSVRecord record,List<Message> messages) throws IllegalArgumentException{
ActivationPoint ap = new ActivationPoint();
EntityManager em = Stripersist.getEntityManager();
// Haal de data uit het csv record
String beheercode = record.get(0);
String x = record.get(1);
String y = record.get(2);
Integer karAddress = Integer.parseInt(record.get(3));
Integer signalGroupNumber = Integer.parseInt(record.get(4));
Integer distanceTillStopline = Integer.parseInt(record.get(5));
Integer timeTillStopline = Integer.parseInt(record.get(6));
Integer commandType = Integer.parseInt(record.get(7));
Integer triggerType = 0;
try {
triggerType = Integer.parseInt(record.get(8));// Niet zeker. Mogelijke vertalingen: 0,1: forced, 2,3,4,5: manual
} catch (IndexOutOfBoundsException ex) {
// Niet nodig, optioneel veld
}
if(triggerType < 0 ||triggerType > 255){
throw new IllegalArgumentException("Triggertype not recognized: " + triggerType);
}
// Alleen vehicletypes behorende bij de groep hulpdiensten: ptx is voor hulpdiensten
List<VehicleType> vehicleTypes = em.createQuery("from VehicleType where groep = :h order by nummer")
.setParameter("h", VehicleType.VEHICLE_TYPE_HULPDIENSTEN)
.getResultList();
// Maak een ActivationPointSignal obv de gegevens uit de ptx
ActivationPointSignal aps = new ActivationPointSignal();
aps.setDistanceTillStopLine(distanceTillStopline);
aps.setSignalGroupNumber(signalGroupNumber);
aps.setKarCommandType(commandType);
aps.setTriggerType("" + triggerType);
aps.setVehicleTypes(vehicleTypes);
// Haal objecten op om aan elkaar te linken
DataOwner dataOwner = getDataOwner(beheercode);
Movement movement = getMovement(karAddress, signalGroupNumber, dataOwner, messages);
RoadsideEquipment rseq = movement.getRoadsideEquipment();
Set<ActivationPoint> ps = rseq.getPoints();
int maxNr = 0;
for(ActivationPoint p: ps) {
maxNr = Math.max(maxNr, p.getNummer());
}
ap.setNummer(maxNr + 1);
ps.add(ap);
// Maak geometrie
int xInt = Integer.parseInt(x);
int yInt = Integer.parseInt(y);
ap.setX(xInt);
ap.setY(yInt);
addPoint(karAddress, ap.getLocation());
ap.setRoadsideEquipment(rseq);
em.persist(ap);
// Maak MovementActivationPoint
MovementActivationPoint map = new MovementActivationPoint();
map.setPoint(ap);
map.setMovement(movement);
map.setBeginEndOrActivation(MovementActivationPoint.ACTIVATION); // geen begin/eindpunt in INCAA
map.setSignal(aps);
em.persist(map);
movement.getPoints().add(map);
}
/**
* Haal de movement op behorende bij het karAdress en signalGroupNumber. Binnen een .ptx gaan we ervan uit dat een karAdres 1 rseq
* vertegenwoordigd en een punten gegroepeerd op signalGroupNumber een movement vormen.
* Mocht deze movement nog niet bestaan, dan wordt hij aangemaakt.
* @param karAddress KarAddress dat binnen dit .ptx bestand een rseq vertegenwoordigd
* @param signalGroupNumber Signaalgroepnummer dat binnen de rseq van @karAddress een movement identificeert
* @return De movement binnen een rseq met karAddress @karAddres en met signaalgroepnummer @signalGroupNumber
*/
private Movement getMovement(Integer karAddress, Integer signalGroupNumber, DataOwner dataOwner,List<Message> messages) throws IllegalArgumentException{
Movement mvmnt = null;
RoadsideEquipment rseq = getRseq(karAddress,dataOwner, messages);
EntityManager em = Stripersist.getEntityManager();
if (!movements.containsKey(karAddress)) {
Map<Integer, Movement> signalGroupMovement = new HashMap<Integer, Movement>();
mvmnt = new Movement();
mvmnt.setRoadsideEquipment(rseq);
mvmnt.setNummer(rseq.getMovements().size() + 1);
em.persist(mvmnt);
signalGroupMovement.put(signalGroupNumber, mvmnt);
rseq.getMovements().add(mvmnt);
movements.put(karAddress, signalGroupMovement);
} else {
Map<Integer, Movement> signalGroupMovement = movements.get(karAddress);
if (!signalGroupMovement.containsKey(signalGroupNumber)) {
mvmnt = new Movement();
mvmnt.setRoadsideEquipment(rseq);
mvmnt.setNummer(rseq.getMovements().size() + 1);
signalGroupMovement.put(signalGroupNumber, mvmnt);
em.persist(mvmnt);
rseq.getMovements().add(mvmnt);
movements.put(karAddress, signalGroupMovement);
}
}
mvmnt = movements.get(karAddress).get(signalGroupNumber);
return mvmnt;
}
/**
*
* @param karAddres Haal<SUF>*/
private RoadsideEquipment getRseq(Integer karAddres, DataOwner dataOwner, List<Message> messages) throws IllegalArgumentException{
RoadsideEquipment rseq = null;
if (!rseqs.containsKey(karAddres)) {
EntityManager em = Stripersist.getEntityManager();
List<RoadsideEquipment> rseqsList = em.createQuery("FROM RoadsideEquipment WHERE dataOwner = :do and karAddress = :karAddress", RoadsideEquipment.class).setParameter("do", dataOwner).setParameter("karAddress", karAddres).getResultList();
if (rseqsList.size() > 0) {
if (rseqsList.size() == 1) {
rseq = rseqsList.get(0);
if (rseq.getVehicleType() == null || rseq.getVehicleType().equals(VehicleType.VEHICLE_TYPE_OV)) {
messages.add(new SimpleMessage("Kruispunt met KAR-adres " + karAddres + " bestaat al, maar heeft nog geen hulpdienstpunten. Hulpdienstpunten worden toegevoegd."));
}else{
throw new IllegalArgumentException("Kruispunt met KAR-adres " + karAddres + " heeft al hulpdienst punten");
}
} else {
throw new IllegalArgumentException("Meerdere kruispunten gevonden voor KAR-adres " + karAddres + " en wegbeheerder " + dataOwner.getOmschrijving());
}
}
if (rseq == null) {
rseq = new RoadsideEquipment();
rseq.setKarAddress(karAddres);
rseq.setDataOwner(dataOwner);
rseq.setType(RoadsideEquipment.TYPE_CROSSING);
rseq.setValidFrom(new Date());
em.persist(rseq);
}
rseqs.put(karAddres, rseq);
}
rseq = rseqs.get(karAddres);
return rseq;
}
private DataOwner getDataOwner(String code) {
try{
EntityManager em = Stripersist.getEntityManager();
DataOwner dataOwner = (DataOwner) em.createQuery("from DataOwner where code = :code ").setParameter("code", code).getSingleResult();
return dataOwner;
}catch(NoResultException ex){
throw new NoResultException("Kan databeheerder niet ophalen voor code: "+ code);
}
}
/**
* Voeg een punt toe aan een lijstje voor een rseq met kar adres @karAddress. Voor latere verwerking tot centroïde voor de locatie van het rseq..
* @param karAddress
* @param p
*/
private void addPoint(Integer karAddress, Point p) {
if (!rseqLocations.containsKey(karAddress)) {
rseqLocations.put(karAddress, new ArrayList<Point>());
}
rseqLocations.get(karAddress).add(p);
}
private void getKarAttributes(JSONObject attributes, RoadsideEquipment rseq) throws JSONException{
for (Iterator it = attributes.keys(); it.hasNext();) {
String serviceType = (String) it.next();
JSONArray perCommandType = attributes.getJSONArray(serviceType);
KarAttributes ka = new KarAttributes(
serviceType,
ActivationPointSignal.COMMAND_INMELDPUNT,
perCommandType.getJSONArray(0));
if (ka.getUsedAttributesMask() != 0) {
rseq.getKarAttributes().add(ka);
}
ka = new KarAttributes(
serviceType,
ActivationPointSignal.COMMAND_UITMELDPUNT,
perCommandType.getJSONArray(1));
if (ka.getUsedAttributesMask() != 0) {
rseq.getKarAttributes().add(ka);
}
ka = new KarAttributes(
serviceType,
ActivationPointSignal.COMMAND_VOORINMELDPUNT,
perCommandType.getJSONArray(2));
if (ka.getUsedAttributesMask() != 0) {
rseq.getKarAttributes().add(ka);
}
}
}
}
|
25603_6 | import EvaluateClass.*;
/**
* class Speler - geef hier een beschrijving van deze class
*
* @author Willem Vansimpsen
* @author Jorim Tielemans
* @version 24/11/2014
*/
public class Speler extends Voorwerp
{
@Intentional(ignoreSet=true)
private int spelerNr;
private int xCo, yCo; // coordinaten van de speler
private boolean vuur = false;
private boolean shiften; // kan de speler shiften?
private boolean kicken; // kan de speler kicken?
private Richting richting; // ONDER, BOVEN, LINKS, RECHTS
private int aantalBommen;
private static int standaardBommen = 1;
private static int maxBommen = 6;
private int hoeveelVuur;
private static int standaardVuur = 1;
private int maxVuur;
private int levens;
private static int standaardLevens = 3;
private static int maxLevens = 3;
private int snelheid;
private static int standaardSnelheid = 1;
private static int maxSnelheid = 6;
private Voorwerp vwOnderSpeler;
private Voorwerp s;
/**
* Constructor voor objects van class Speler
*
* @param spelerNr Het nummer van de speler.
* @param xCo De x-positie van het portaal.
* @param yCo De y-positie van het portaal.
*/
public Speler(int spelerNr, int xCo, int yCo, Voorwerp vwOnderSpeler)
{
this.spelerNr = spelerNr;
this.xCo = xCo;
this.yCo = yCo;
this.vwOnderSpeler = vwOnderSpeler;
shiften = false;
kicken = false;
richting = Richting.ONDER;
aantalBommen = standaardBommen;
hoeveelVuur = standaardVuur;
levens = standaardLevens;
snelheid = standaardSnelheid;
}
// getters
/**
* Hiermee vraag je het nummer van de speler op.
*
* @return het nummer van de speler.
*/
public int getSpelerNr()
{
return spelerNr;
}
/**
* Is de speler aan het ontploffen?
*
* @return True indien de speler aan het ontploffen is.
*
*/
public boolean isVuur()
{
return vuur;
}
/**
* Wat is de x-positie van de speler?
*
* @return De x-positie van de speler.
*/
public int getX()
{
return xCo;
}
/**
* Wat is de y-positie van de speler?
*
* @return De y-positie van de speler.
*/
public int getY()
{
return yCo;
}
/**
* Kan de speler bommen shiften?
*
* @return True als de speler bommen kan shiften.
*/
public boolean kanShiften()
{
return shiften;
}
/**
* Kan de speler bommen kicken?
*
* @return True als de speler bommen kan kicken.
*/
public boolean kanKicken()
{
return kicken;
}
/**
* Wat is de richting van de speler?
* ONDER, BOVEN, LINKS, RECHTS
*
* @return De richting van de speler.
*/
public Richting getRichting()
{
return richting;
}
/**
* Hoeveel bommen heeft de speler nog?
*
* @return het aantal bommen van de speler.
*/
public int getAantalBommen()
{
return aantalBommen;
}
/**
* Hoeveel bommen kan de speler maximum hebben?
*
* @return het maximum aantal bommen van de speler.
*/
public int getMaxBommen()
{
return maxBommen;
}
/**
* Hoe krachtig is de explosie van de speler?
*
* @return De 'krachtigheid' van de explosie van de speler.
*/
public int getHoeveelVuur()
{
return hoeveelVuur;
}
/**
* Hoe krachtig kan de explosie van de speler maximum zijn?
*
* @return De maximale 'krachtigheid' van de explosie van de speler.
*/
public int getMaxVuur()
{
return maxVuur;
}
/**
* Hoeveel levens heeft de speler nog?
*
* @return het aantal levens van de speler.
*/
public int getLevens()
{
return levens;
}
/**
* Hoeveel levens kan de speler maximum hebben?
*
* @return het maximum aantal levens van de speler.
*/
public int getMaxLevens()
{
return maxLevens;
}
/**
* Welke snelheid heeft de speler?
*
* @return snelheid De snelheid van de speler.
*/
public int getSnelheid()
{
return snelheid;
}
/**
* Welke snelheid kan de speler maximaal hebben?
*
* @return maxSnelheid De maximale snelheid van de speler.
*/
public int getMaxSnelheid()
{
return maxSnelheid;
}
/**
* Wat ligt er onder de speler in het veld?
*
* @return vwOnderSpeler Het voorwerp onder de speler.
*/
public Voorwerp getVwOnderSpeler()
{
return vwOnderSpeler;
}
/**
* Een niet nader omschreven Voorwerp s
*
* @return s Nog een voorwerp van de speler.
*/
public Voorwerp getS()
{
return s;
}
/**
* Is de Voorwerp betreedbaar?
*
* @return true indien betreedbaar.
*/
public boolean isBetreedbaar()
{
return true;
}
/**
* laat dit voorwerp vuur door van een bom?
*
* @return true indien het vuur doorlaat.
*/
public boolean isVuurDoorlaatbaar()
{
return true;
}
/**
* Is de Voorwerp breekbaar, ten gevolgen van een explosie?
*
* @return true indien breekbaar.
*/
public boolean isBreekbaar()
{
return true;
}
// setters
/**
* Hiermee stel je het nummer van de speler in.
*
* @param spelerNr Het nummer van de speler.
*/
public void setSpelerNr(int spelerNr)
{
this.spelerNr = spelerNr;
}
/**
* Laat de speler ontploffen.
*
* @param vuur True indien de speler aan het ontploffen is.
*
*/
public void maakVuur(boolean vuur)
{
this.vuur = vuur;
}
/**
* Stel de x-positie van de speler in.
*
* @param xCo De x-positie van de speler.
*/
public void setX(int xCo)
{
this.xCo = xCo;
}
/**
* Stel de y-positie van de speler in.
*
* @param yCo De y-positie van de speler.
*/
public void setY(int yCo)
{
this.yCo = yCo;
}
/**
* Laat de speler bommen shiften.
*
* @param shiften True als de speler bommen mag shiften.
*/
public void magShiften(boolean shiften)
{
this.shiften = shiften;
}
/**
* Laat de speler bommen kicken.
*
* @param kicken True als de speler bommen mag kicken.
*/
public void magKicken(boolean kicken)
{
this.kicken = kicken;
}
/**
* Geef de speler een richting.
* ONDER, BOVEN, LINKS, RECHTS
*
* @param richting De richting die de speler krijgt.
*/
public void setRichting(Richting richting)
{
this.richting = richting;
}
/**
* Hiermee pas je het aantal bommen van de speler aan.
*
* @param aantalBommen Het nieuwe aantal bommen voor de speler.
*/
public void setAantalBommen(int aantalBommen)
{
if (getAantalBommen() < getMaxBommen())
{
this.aantalBommen = aantalBommen;
}
else
{
this.aantalBommen = maxBommen;
}
}
/**
* Hiermee pas je de kracht van de explosie van de speler aan.
*
* @param hoeveelVuur De 'krachtigheid' van de explosie van de speler.
*/
public void setHoeveelVuur(int hoeveelVuur)
{
if (getHoeveelVuur() < getMaxVuur())
{
this.hoeveelVuur = hoeveelVuur;
}
else
{
this.hoeveelVuur = maxVuur;
}
}
/**
* Hiermee pas je de snelheid van de speler aan.
*
* @param snelheid De snelheid van de speler.
*/
public void setSnelheid(int snelheid)
{
if (getSnelheid() < getMaxSnelheid())
{
this.snelheid = snelheid;
}
else
{
this.snelheid = maxSnelheid;
}
}
/**
* Hoe krachtig kan de explosie van de speler maximum zijn?
*
* @param maxVuur De maximale 'krachtigheid' van de explosie van de speler.
*/
public void setMaxVuur(int maxVuur)
{
this.maxVuur = maxVuur;
}
/**
* Verander het voorwerp onder de speler.
*
* @param vwOnderSpeler Het nieuwe voorwerp dat je onder de speler wilt leggen.
*/
public void setVwOnderSpeler(Voorwerp vwOnderSpeler)
{
this.vwOnderSpeler = vwOnderSpeler;
}
/**
* Verander het niet nader omschreven Voorwerp s
*
* @param s Het nieuwe voorwerp van de speler.
*/
public void setS(Voorwerp s)
{
this.s = s;
}
/**
* Hiermee vermoord je de speler, het aantal levens wordt op nul gezet.
*/
public void maakDood()
{
this.levens = 0;
}
public void eenLevenMinder()
{
levens--;
}
public void eenLevenMeer()
{
if (getLevens() < getMaxLevens())
{
levens++;
}
else
{
this.levens = maxLevens;
}
}
} | tjorim/bomberboy | Speler.java | 3,244 | /**
* Hiermee vraag je het nummer van de speler op.
*
* @return het nummer van de speler.
*/ | block_comment | nl | import EvaluateClass.*;
/**
* class Speler - geef hier een beschrijving van deze class
*
* @author Willem Vansimpsen
* @author Jorim Tielemans
* @version 24/11/2014
*/
public class Speler extends Voorwerp
{
@Intentional(ignoreSet=true)
private int spelerNr;
private int xCo, yCo; // coordinaten van de speler
private boolean vuur = false;
private boolean shiften; // kan de speler shiften?
private boolean kicken; // kan de speler kicken?
private Richting richting; // ONDER, BOVEN, LINKS, RECHTS
private int aantalBommen;
private static int standaardBommen = 1;
private static int maxBommen = 6;
private int hoeveelVuur;
private static int standaardVuur = 1;
private int maxVuur;
private int levens;
private static int standaardLevens = 3;
private static int maxLevens = 3;
private int snelheid;
private static int standaardSnelheid = 1;
private static int maxSnelheid = 6;
private Voorwerp vwOnderSpeler;
private Voorwerp s;
/**
* Constructor voor objects van class Speler
*
* @param spelerNr Het nummer van de speler.
* @param xCo De x-positie van het portaal.
* @param yCo De y-positie van het portaal.
*/
public Speler(int spelerNr, int xCo, int yCo, Voorwerp vwOnderSpeler)
{
this.spelerNr = spelerNr;
this.xCo = xCo;
this.yCo = yCo;
this.vwOnderSpeler = vwOnderSpeler;
shiften = false;
kicken = false;
richting = Richting.ONDER;
aantalBommen = standaardBommen;
hoeveelVuur = standaardVuur;
levens = standaardLevens;
snelheid = standaardSnelheid;
}
// getters
/**
* Hiermee vraag je<SUF>*/
public int getSpelerNr()
{
return spelerNr;
}
/**
* Is de speler aan het ontploffen?
*
* @return True indien de speler aan het ontploffen is.
*
*/
public boolean isVuur()
{
return vuur;
}
/**
* Wat is de x-positie van de speler?
*
* @return De x-positie van de speler.
*/
public int getX()
{
return xCo;
}
/**
* Wat is de y-positie van de speler?
*
* @return De y-positie van de speler.
*/
public int getY()
{
return yCo;
}
/**
* Kan de speler bommen shiften?
*
* @return True als de speler bommen kan shiften.
*/
public boolean kanShiften()
{
return shiften;
}
/**
* Kan de speler bommen kicken?
*
* @return True als de speler bommen kan kicken.
*/
public boolean kanKicken()
{
return kicken;
}
/**
* Wat is de richting van de speler?
* ONDER, BOVEN, LINKS, RECHTS
*
* @return De richting van de speler.
*/
public Richting getRichting()
{
return richting;
}
/**
* Hoeveel bommen heeft de speler nog?
*
* @return het aantal bommen van de speler.
*/
public int getAantalBommen()
{
return aantalBommen;
}
/**
* Hoeveel bommen kan de speler maximum hebben?
*
* @return het maximum aantal bommen van de speler.
*/
public int getMaxBommen()
{
return maxBommen;
}
/**
* Hoe krachtig is de explosie van de speler?
*
* @return De 'krachtigheid' van de explosie van de speler.
*/
public int getHoeveelVuur()
{
return hoeveelVuur;
}
/**
* Hoe krachtig kan de explosie van de speler maximum zijn?
*
* @return De maximale 'krachtigheid' van de explosie van de speler.
*/
public int getMaxVuur()
{
return maxVuur;
}
/**
* Hoeveel levens heeft de speler nog?
*
* @return het aantal levens van de speler.
*/
public int getLevens()
{
return levens;
}
/**
* Hoeveel levens kan de speler maximum hebben?
*
* @return het maximum aantal levens van de speler.
*/
public int getMaxLevens()
{
return maxLevens;
}
/**
* Welke snelheid heeft de speler?
*
* @return snelheid De snelheid van de speler.
*/
public int getSnelheid()
{
return snelheid;
}
/**
* Welke snelheid kan de speler maximaal hebben?
*
* @return maxSnelheid De maximale snelheid van de speler.
*/
public int getMaxSnelheid()
{
return maxSnelheid;
}
/**
* Wat ligt er onder de speler in het veld?
*
* @return vwOnderSpeler Het voorwerp onder de speler.
*/
public Voorwerp getVwOnderSpeler()
{
return vwOnderSpeler;
}
/**
* Een niet nader omschreven Voorwerp s
*
* @return s Nog een voorwerp van de speler.
*/
public Voorwerp getS()
{
return s;
}
/**
* Is de Voorwerp betreedbaar?
*
* @return true indien betreedbaar.
*/
public boolean isBetreedbaar()
{
return true;
}
/**
* laat dit voorwerp vuur door van een bom?
*
* @return true indien het vuur doorlaat.
*/
public boolean isVuurDoorlaatbaar()
{
return true;
}
/**
* Is de Voorwerp breekbaar, ten gevolgen van een explosie?
*
* @return true indien breekbaar.
*/
public boolean isBreekbaar()
{
return true;
}
// setters
/**
* Hiermee stel je het nummer van de speler in.
*
* @param spelerNr Het nummer van de speler.
*/
public void setSpelerNr(int spelerNr)
{
this.spelerNr = spelerNr;
}
/**
* Laat de speler ontploffen.
*
* @param vuur True indien de speler aan het ontploffen is.
*
*/
public void maakVuur(boolean vuur)
{
this.vuur = vuur;
}
/**
* Stel de x-positie van de speler in.
*
* @param xCo De x-positie van de speler.
*/
public void setX(int xCo)
{
this.xCo = xCo;
}
/**
* Stel de y-positie van de speler in.
*
* @param yCo De y-positie van de speler.
*/
public void setY(int yCo)
{
this.yCo = yCo;
}
/**
* Laat de speler bommen shiften.
*
* @param shiften True als de speler bommen mag shiften.
*/
public void magShiften(boolean shiften)
{
this.shiften = shiften;
}
/**
* Laat de speler bommen kicken.
*
* @param kicken True als de speler bommen mag kicken.
*/
public void magKicken(boolean kicken)
{
this.kicken = kicken;
}
/**
* Geef de speler een richting.
* ONDER, BOVEN, LINKS, RECHTS
*
* @param richting De richting die de speler krijgt.
*/
public void setRichting(Richting richting)
{
this.richting = richting;
}
/**
* Hiermee pas je het aantal bommen van de speler aan.
*
* @param aantalBommen Het nieuwe aantal bommen voor de speler.
*/
public void setAantalBommen(int aantalBommen)
{
if (getAantalBommen() < getMaxBommen())
{
this.aantalBommen = aantalBommen;
}
else
{
this.aantalBommen = maxBommen;
}
}
/**
* Hiermee pas je de kracht van de explosie van de speler aan.
*
* @param hoeveelVuur De 'krachtigheid' van de explosie van de speler.
*/
public void setHoeveelVuur(int hoeveelVuur)
{
if (getHoeveelVuur() < getMaxVuur())
{
this.hoeveelVuur = hoeveelVuur;
}
else
{
this.hoeveelVuur = maxVuur;
}
}
/**
* Hiermee pas je de snelheid van de speler aan.
*
* @param snelheid De snelheid van de speler.
*/
public void setSnelheid(int snelheid)
{
if (getSnelheid() < getMaxSnelheid())
{
this.snelheid = snelheid;
}
else
{
this.snelheid = maxSnelheid;
}
}
/**
* Hoe krachtig kan de explosie van de speler maximum zijn?
*
* @param maxVuur De maximale 'krachtigheid' van de explosie van de speler.
*/
public void setMaxVuur(int maxVuur)
{
this.maxVuur = maxVuur;
}
/**
* Verander het voorwerp onder de speler.
*
* @param vwOnderSpeler Het nieuwe voorwerp dat je onder de speler wilt leggen.
*/
public void setVwOnderSpeler(Voorwerp vwOnderSpeler)
{
this.vwOnderSpeler = vwOnderSpeler;
}
/**
* Verander het niet nader omschreven Voorwerp s
*
* @param s Het nieuwe voorwerp van de speler.
*/
public void setS(Voorwerp s)
{
this.s = s;
}
/**
* Hiermee vermoord je de speler, het aantal levens wordt op nul gezet.
*/
public void maakDood()
{
this.levens = 0;
}
public void eenLevenMinder()
{
levens--;
}
public void eenLevenMeer()
{
if (getLevens() < getMaxLevens())
{
levens++;
}
else
{
this.levens = maxLevens;
}
}
} |
196031_0 | /*
* @lc app=leetcode.cn id=799 lang=java
*
* [799] Champagne Tower
*/
// @lc code=start
class Solution {
public double champagneTower(int poured, int query_row, int query_glass) {
// 动态规划
double[][] dp = new double[101][101];
dp[0][0] = poured;
for (int i = 1; i <= query_row; i++) {
for (int j = 0; j <= i; j++) {
if (dp[i - 1][j] > 1) {
dp[i][j] += (dp[i - 1][j] - 1) / 2;
dp[i][j + 1] += (dp[i - 1][j] - 1) / 2;
}
}
}
return dp[query_row][query_glass] > 1 ? 1 : dp[query_row][query_glass];
}
}
// @lc code=end | tjujingzong/Leetcode | leetcode/799.champagne-tower.java | 273 | /*
* @lc app=leetcode.cn id=799 lang=java
*
* [799] Champagne Tower
*/ | block_comment | nl | /*
* @lc app=leetcode.cn id=799<SUF>*/
// @lc code=start
class Solution {
public double champagneTower(int poured, int query_row, int query_glass) {
// 动态规划
double[][] dp = new double[101][101];
dp[0][0] = poured;
for (int i = 1; i <= query_row; i++) {
for (int j = 0; j <= i; j++) {
if (dp[i - 1][j] > 1) {
dp[i][j] += (dp[i - 1][j] - 1) / 2;
dp[i][j + 1] += (dp[i - 1][j] - 1) / 2;
}
}
}
return dp[query_row][query_glass] > 1 ? 1 : dp[query_row][query_glass];
}
}
// @lc code=end |
125791_0 | package champ.cards;
import champ.ChampMod;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import static com.megacrit.cardcrawl.cards.red.PerfectedStrike.countCards;
public class PerfectedStrike extends AbstractChampCard {
public final static String ID = makeID("PerfectedStrike");
//stupid intellij stuff attack, enemy, common
private static final int DAMAGE = 8;
private static final int MAGIC = 2;
private static final int UPG_MAGIC = 1;
public PerfectedStrike() {
super(ID, 2, CardType.ATTACK, CardRarity.COMMON, CardTarget.ENEMY);
baseDamage = DAMAGE;
baseMagicNumber = magicNumber = MAGIC;
tags.add(CardTags.STRIKE);
postInit();
}
public void calculateCardDamage(AbstractMonster mo) {
int realBaseDamage = this.baseDamage;
this.baseDamage += this.magicNumber * countCards();
super.calculateCardDamage(mo);
this.baseDamage = realBaseDamage;
this.isDamageModified = this.damage != this.baseDamage;
}
public void applyPowers() {
int realBaseDamage = this.baseDamage;
this.baseDamage += this.magicNumber * countCards();
super.applyPowers();
this.baseDamage = realBaseDamage;
this.isDamageModified = this.damage != this.baseDamage;
}
public void use(AbstractPlayer p, AbstractMonster m) {
dmg(m, AbstractGameAction.AttackEffect.SLASH_DIAGONAL);
}
public void upp() {
upgradeMagicNumber(UPG_MAGIC);
}
} | tldyl/EvilWithin | src/main/java/champ/cards/PerfectedStrike.java | 531 | //stupid intellij stuff attack, enemy, common | line_comment | nl | package champ.cards;
import champ.ChampMod;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import static com.megacrit.cardcrawl.cards.red.PerfectedStrike.countCards;
public class PerfectedStrike extends AbstractChampCard {
public final static String ID = makeID("PerfectedStrike");
//stupid intellij<SUF>
private static final int DAMAGE = 8;
private static final int MAGIC = 2;
private static final int UPG_MAGIC = 1;
public PerfectedStrike() {
super(ID, 2, CardType.ATTACK, CardRarity.COMMON, CardTarget.ENEMY);
baseDamage = DAMAGE;
baseMagicNumber = magicNumber = MAGIC;
tags.add(CardTags.STRIKE);
postInit();
}
public void calculateCardDamage(AbstractMonster mo) {
int realBaseDamage = this.baseDamage;
this.baseDamage += this.magicNumber * countCards();
super.calculateCardDamage(mo);
this.baseDamage = realBaseDamage;
this.isDamageModified = this.damage != this.baseDamage;
}
public void applyPowers() {
int realBaseDamage = this.baseDamage;
this.baseDamage += this.magicNumber * countCards();
super.applyPowers();
this.baseDamage = realBaseDamage;
this.isDamageModified = this.damage != this.baseDamage;
}
public void use(AbstractPlayer p, AbstractMonster m) {
dmg(m, AbstractGameAction.AttackEffect.SLASH_DIAGONAL);
}
public void upp() {
upgradeMagicNumber(UPG_MAGIC);
}
} |
22284_9 | package org.tlh.profile.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
* 标签模型
* </p>
*
* @author 离歌笑
* @since 2021-03-20
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class TbTagModel implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 标签ID(四级标签)
*/
private Long tagId;
/**
* 模型类型:1 匹配 2 统计 3 挖掘
*/
private Integer modelType;
/**
* 模型名称
*/
private String modelName;
/**
* 模型driver全限定名
*/
private String modelMain;
/**
* 模型在hdfs中的地址
*/
private String modelPath;
/**
* 模型jar包文件名
*/
private String modelJar;
/**
* 模型参数
*/
private String modelArgs;
/**
* spark的执行参数
*/
private String sparkOpts;
/**
* oozie的调度规则
*/
private String scheduleRule;
/**
* 操作人
*/
private String operator;
/**
* 操作类型
*/
private String operation;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
/**
* 状态
*/
private Integer state;
/**
* oozie调度任务ID
*/
private String oozieTaskId;
}
| tlhhup/litemall-dw | user-profile/profile-admin-api/src/main/java/org/tlh/profile/entity/TbTagModel.java | 532 | /**
* oozie的调度规则
*/ | block_comment | nl | package org.tlh.profile.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
* 标签模型
* </p>
*
* @author 离歌笑
* @since 2021-03-20
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class TbTagModel implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 标签ID(四级标签)
*/
private Long tagId;
/**
* 模型类型:1 匹配 2 统计 3 挖掘
*/
private Integer modelType;
/**
* 模型名称
*/
private String modelName;
/**
* 模型driver全限定名
*/
private String modelMain;
/**
* 模型在hdfs中的地址
*/
private String modelPath;
/**
* 模型jar包文件名
*/
private String modelJar;
/**
* 模型参数
*/
private String modelArgs;
/**
* spark的执行参数
*/
private String sparkOpts;
/**
* oozie的调度规则
<SUF>*/
private String scheduleRule;
/**
* 操作人
*/
private String operator;
/**
* 操作类型
*/
private String operation;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
/**
* 状态
*/
private Integer state;
/**
* oozie调度任务ID
*/
private String oozieTaskId;
}
|
102323_13 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.offene_pflege.op.system;
import de.offene_pflege.op.tools.SYSTools;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
/**
* @author tloehr
*/
public class PrinterForm {
private String name, label;
private String form, encoding;
//private HashMap attributes;
private HashMap<String, ArrayList> elemAttributes;
private final int LINECOUNTER = 0;
private final int CHARCOUNTER = 1;
private final int LEFT = 1;
private final int CENTER = 2;
private final int RIGHT = 3;
public PrinterForm(String name, String label, HashMap elemAttributes, String encoding) {
this.name = name;
this.label = label;
this.elemAttributes = elemAttributes;
this.encoding = encoding;
}
public String getLabel() {
return label;
}
public String getName() {
return name;
}
public void setFormtext(String form) {
this.form = form;
}
public String getFormtext(HashMap attributes) {
String myForm = form;
// this.attributes = attributes;
Iterator it = attributes.keySet().iterator();
// Diese Map behält die Übersicht, welche Elemente sich zur Zeit in welcher Zeile und bei welchem Zeichen befinden.
//HashMap<String, Integer[]> multilines = new HashMap<String, Integer[]>();
while (it.hasNext()) {
String providedAttribKey = it.next().toString();
if (elemAttributes.containsKey(providedAttribKey)) {
int currentCharForThisElement = 0;
// Für jede Zeile einer Multiline. Wenn keine Multiline, dann eben nur einmal.
for (int line = 0; line < elemAttributes.get(providedAttribKey).size(); line++) {
if (attributes.get(providedAttribKey) != null) {
// Wert für den Einsatz im Formular.
String replacement = attributes.get(providedAttribKey).toString();
// Parameter für das aktuelle Element
HashMap<String, String> attribs = (HashMap) elemAttributes.get(providedAttribKey).get(line);
// Defaults für die Parameter
int fixedlength = 0;
int maxlength = 0;
boolean multiline = false;
String fillchar = " ";
boolean toUpper = false;
boolean toLower = false;
int pad = RIGHT;
String dateformat = "dd.MM.yy";
if (attribs.containsKey("fixedlength")) {
fixedlength = Integer.parseInt(attribs.get("fixedlength"));
}
if (attribs.containsKey("maxlength")) {
maxlength = Integer.parseInt(attribs.get("maxlength"));
}
if (attribs.containsKey("multiline")) {
multiline = attribs.get("multiline").equalsIgnoreCase("true");
}
if (attribs.containsKey("fillchar")) {
fillchar = attribs.get("fillchar");
}
if (attribs.containsKey("toupper")) {
toUpper = attribs.get("toupper").equalsIgnoreCase("true");
}
if (attribs.containsKey("tolower")) {
toLower = attribs.get("tolower").equalsIgnoreCase("true");
}
if (attribs.containsKey("pad")) {
if (attribs.get("pad").equalsIgnoreCase("left")) {
pad = LEFT;
} else if (attribs.get("pad").equalsIgnoreCase("center")) {
pad = CENTER;
} else {
pad = RIGHT;
}
}
if (attribs.containsKey("dateformat")) {
dateformat = attribs.get("dateformat");
}
if (attributes.get(providedAttribKey) instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
replacement = sdf.format((Date) attributes.get(providedAttribKey));
}
if (maxlength > 0) {
replacement = substring(replacement, currentCharForThisElement, currentCharForThisElement + maxlength);
currentCharForThisElement += maxlength;
} else {
replacement = substring(replacement, currentCharForThisElement, replacement.length());
currentCharForThisElement += replacement.length();
}
// Egal was vorher gerechnet wurde. Nur bei Multiline ist das interessant.
if (!multiline) {
currentCharForThisElement = 0;
}
if (fixedlength > 0) {
if (pad == LEFT) {
replacement = SYSTools.padL(replacement, fixedlength, fillchar);
} else if (pad == CENTER) {
replacement = SYSTools.padC(replacement, fixedlength, fillchar);
} else {
replacement = SYSTools.padR(replacement, fixedlength, fillchar);
}
}
if (toUpper) {
replacement = replacement.toUpperCase();
}
if (toLower) {
replacement = replacement.toLowerCase();
}
// Hier wird ein Teil des Formulars ausgefüllt. Jeweils für ein Element und (wenn nötig) für eine weitere Zeile
// So werden Stück für Stück alle Platzhalter gegen die Werte erstetzt.
myForm = SYSTools.replace(myForm, "$" + providedAttribKey + (line + 1) + "$", replacement, false);
} else {
myForm = SYSTools.replace(myForm, "$" + providedAttribKey + (line + 1) + "$", "", false);
}
}
}
}
return myForm;
}
/**
* Bloss nicht vergessen zu dokumentieren.
*
* @param providedAttribKey
* @return
*/
private String getBaseFormAttrib(String providedAttribKey) {
String newAttrib = providedAttribKey;
// Das hier findet auch Schlüssel, die bei Multilines gebraucht werden.
// Dann stehen von den Namen jeweils die Zeilennummern davor.
// z.B. 1:produkt.bezeichnung
if (providedAttribKey.matches("[0-9]+:{1}.*")) {
int divider = providedAttribKey.indexOf(":");
newAttrib = providedAttribKey.substring(divider);
}
return newAttrib;
}
/**
* Mein eigener <i>substring</i>. Diese Version reagiert nicht mit einer Exception, wenn man
* versucht substrings zu erhalten, die ganz oder teilweise außerhalb der Quell Strings liegen.
* In diesem Fall wird einfach weniger oder gar nichts zurück gegeben.
*
* @param str Eingangs-String
* @param begin Stelle, ab der Substring beginnen soll.
* @param end Stelle, ab der Substring enden soll.
* @return substring. ggf. gekürzt oder ganz leer.
*/
private String substring(String str, int begin, int end) {
int stop = Math.min(end, str.length()); // Bereinigung bei Ende, das außerhalb des Strings liegt.
String result = "";
if (begin < str.length()) { // Start liegt vor dem Ende des Strings.
result = str.substring(begin, stop);
}
return result;
}
}
| tloehr/Offene-Pflege.de | src/main/java/de/offene_pflege/op/system/PrinterForm.java | 2,103 | /**
* Bloss nicht vergessen zu dokumentieren.
*
* @param providedAttribKey
* @return
*/ | block_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.offene_pflege.op.system;
import de.offene_pflege.op.tools.SYSTools;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
/**
* @author tloehr
*/
public class PrinterForm {
private String name, label;
private String form, encoding;
//private HashMap attributes;
private HashMap<String, ArrayList> elemAttributes;
private final int LINECOUNTER = 0;
private final int CHARCOUNTER = 1;
private final int LEFT = 1;
private final int CENTER = 2;
private final int RIGHT = 3;
public PrinterForm(String name, String label, HashMap elemAttributes, String encoding) {
this.name = name;
this.label = label;
this.elemAttributes = elemAttributes;
this.encoding = encoding;
}
public String getLabel() {
return label;
}
public String getName() {
return name;
}
public void setFormtext(String form) {
this.form = form;
}
public String getFormtext(HashMap attributes) {
String myForm = form;
// this.attributes = attributes;
Iterator it = attributes.keySet().iterator();
// Diese Map behält die Übersicht, welche Elemente sich zur Zeit in welcher Zeile und bei welchem Zeichen befinden.
//HashMap<String, Integer[]> multilines = new HashMap<String, Integer[]>();
while (it.hasNext()) {
String providedAttribKey = it.next().toString();
if (elemAttributes.containsKey(providedAttribKey)) {
int currentCharForThisElement = 0;
// Für jede Zeile einer Multiline. Wenn keine Multiline, dann eben nur einmal.
for (int line = 0; line < elemAttributes.get(providedAttribKey).size(); line++) {
if (attributes.get(providedAttribKey) != null) {
// Wert für den Einsatz im Formular.
String replacement = attributes.get(providedAttribKey).toString();
// Parameter für das aktuelle Element
HashMap<String, String> attribs = (HashMap) elemAttributes.get(providedAttribKey).get(line);
// Defaults für die Parameter
int fixedlength = 0;
int maxlength = 0;
boolean multiline = false;
String fillchar = " ";
boolean toUpper = false;
boolean toLower = false;
int pad = RIGHT;
String dateformat = "dd.MM.yy";
if (attribs.containsKey("fixedlength")) {
fixedlength = Integer.parseInt(attribs.get("fixedlength"));
}
if (attribs.containsKey("maxlength")) {
maxlength = Integer.parseInt(attribs.get("maxlength"));
}
if (attribs.containsKey("multiline")) {
multiline = attribs.get("multiline").equalsIgnoreCase("true");
}
if (attribs.containsKey("fillchar")) {
fillchar = attribs.get("fillchar");
}
if (attribs.containsKey("toupper")) {
toUpper = attribs.get("toupper").equalsIgnoreCase("true");
}
if (attribs.containsKey("tolower")) {
toLower = attribs.get("tolower").equalsIgnoreCase("true");
}
if (attribs.containsKey("pad")) {
if (attribs.get("pad").equalsIgnoreCase("left")) {
pad = LEFT;
} else if (attribs.get("pad").equalsIgnoreCase("center")) {
pad = CENTER;
} else {
pad = RIGHT;
}
}
if (attribs.containsKey("dateformat")) {
dateformat = attribs.get("dateformat");
}
if (attributes.get(providedAttribKey) instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat(dateformat);
replacement = sdf.format((Date) attributes.get(providedAttribKey));
}
if (maxlength > 0) {
replacement = substring(replacement, currentCharForThisElement, currentCharForThisElement + maxlength);
currentCharForThisElement += maxlength;
} else {
replacement = substring(replacement, currentCharForThisElement, replacement.length());
currentCharForThisElement += replacement.length();
}
// Egal was vorher gerechnet wurde. Nur bei Multiline ist das interessant.
if (!multiline) {
currentCharForThisElement = 0;
}
if (fixedlength > 0) {
if (pad == LEFT) {
replacement = SYSTools.padL(replacement, fixedlength, fillchar);
} else if (pad == CENTER) {
replacement = SYSTools.padC(replacement, fixedlength, fillchar);
} else {
replacement = SYSTools.padR(replacement, fixedlength, fillchar);
}
}
if (toUpper) {
replacement = replacement.toUpperCase();
}
if (toLower) {
replacement = replacement.toLowerCase();
}
// Hier wird ein Teil des Formulars ausgefüllt. Jeweils für ein Element und (wenn nötig) für eine weitere Zeile
// So werden Stück für Stück alle Platzhalter gegen die Werte erstetzt.
myForm = SYSTools.replace(myForm, "$" + providedAttribKey + (line + 1) + "$", replacement, false);
} else {
myForm = SYSTools.replace(myForm, "$" + providedAttribKey + (line + 1) + "$", "", false);
}
}
}
}
return myForm;
}
/**
* Bloss nicht vergessen<SUF>*/
private String getBaseFormAttrib(String providedAttribKey) {
String newAttrib = providedAttribKey;
// Das hier findet auch Schlüssel, die bei Multilines gebraucht werden.
// Dann stehen von den Namen jeweils die Zeilennummern davor.
// z.B. 1:produkt.bezeichnung
if (providedAttribKey.matches("[0-9]+:{1}.*")) {
int divider = providedAttribKey.indexOf(":");
newAttrib = providedAttribKey.substring(divider);
}
return newAttrib;
}
/**
* Mein eigener <i>substring</i>. Diese Version reagiert nicht mit einer Exception, wenn man
* versucht substrings zu erhalten, die ganz oder teilweise außerhalb der Quell Strings liegen.
* In diesem Fall wird einfach weniger oder gar nichts zurück gegeben.
*
* @param str Eingangs-String
* @param begin Stelle, ab der Substring beginnen soll.
* @param end Stelle, ab der Substring enden soll.
* @return substring. ggf. gekürzt oder ganz leer.
*/
private String substring(String str, int begin, int end) {
int stop = Math.min(end, str.length()); // Bereinigung bei Ende, das außerhalb des Strings liegt.
String result = "";
if (begin < str.length()) { // Start liegt vor dem Ende des Strings.
result = str.substring(begin, stop);
}
return result;
}
}
|
77823_6 | /*
* Title: tn5250J
* Copyright: Copyright (c) 2001
* Company:
*
* @author Kenneth J. Pouncey
* @version 0.4
* <p>
* Description:
* <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 2, or (at your option)
* any later version.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package org.tn5250j.connectdialog;
import java.awt.Component;
import java.awt.Container;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import org.tn5250j.TN5250jConstants;
import org.tn5250j.encoding.CharMappings;
import org.tn5250j.tools.AlignLayout;
import org.tn5250j.tools.LangTool;
class Configure {
private static Properties props = null;
// property input structures
private static JTextField systemName = null;
private static JTextField systemId = null;
private static JTextField port = null;
private static JTextField deviceName = null;
private static JTextField fpn = null;
private static JComboBox cpb = null;
private static JCheckBox jtb = null;
private static JCheckBox ec = null;
private static JCheckBox tc = null;
private static JCheckBox sdn = null;
private static JRadioButton sdNormal = null;
private static JCheckBox useProxy = null;
private static JTextField proxyHost = null;
private static JTextField proxyPort = null;
private static JCheckBox noEmbed = null;
private static JCheckBox deamon = null;
private static JCheckBox newJVM = null;
private static JComboBox sslType = null;
private static JCheckBox heartBeat = null;
private static JTabbedPane confTabs;
private static JDialog dialog = null;
private static Object[] options;
public static String doEntry(Frame parent, String propKey, Properties props2) {
props = props2;
confTabs = new JTabbedPane();
ec = new JCheckBox(LangTool.getString("conf.labelEnhanced"));
tc = new JCheckBox(LangTool.getString("conf.labelUseSystemName"));
sdn = new JCheckBox(LangTool.getString("conf.labelUseHostName"));
useProxy = new JCheckBox(LangTool.getString("conf.labelUseProxy"));
sdNormal = new JRadioButton(LangTool.getString("conf.label24"));
JRadioButton sdBig = new JRadioButton(LangTool.getString("conf.label27"));
noEmbed = new JCheckBox(LangTool.getString("conf.labelEmbed"));
deamon = new JCheckBox(LangTool.getString("conf.labelDeamon"));
newJVM = new JCheckBox(LangTool.getString("conf.labelNewJVM"));
heartBeat = new JCheckBox(LangTool.getString("conf.labelHeartBeat"));
jtb = new JCheckBox("AS/400 Toolbox");
jtb.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(ItemEvent e) {
doCPStateChanged(e);
}
});
cpb = new JComboBox();
String[] availCP = getAvailableCodePages();
cpb.addItem(LangTool.getString("conf.labelDefault"));
for (int x = 0; x < availCP.length; x++) {
cpb.addItem(availCP[x]);
}
sslType = new JComboBox();
for (int x = 0; x < TN5250jConstants.SSL_TYPES.length; x++) {
sslType.addItem(TN5250jConstants.SSL_TYPES[x]);
}
if (propKey == null) {
systemName = new JTextField(20);
systemId = new JTextField(20);
port = new JTextField("23", 5);
deviceName = new JTextField(20);
fpn = new JTextField(20);
proxyHost = new JTextField(20);
proxyPort = new JTextField("1080", 5);
ec.setSelected(true);
tc.setSelected(true);
jtb.setSelected(false);
sdNormal.setSelected(true);
deamon.setSelected(true);
newJVM.setEnabled(false);
noEmbed.setEnabled(false);
deamon.setEnabled(false);
systemName.setDocument(new SomethingEnteredDocument());
} else {
String[] args = new String[20];
parseArgs((String) props.get(propKey), args);
systemName = new JTextField(propKey, 20);
systemName.setEditable(false);
systemName.setEnabled(false);
systemId = new JTextField(args[0], 20);
if (isSpecified("-p", args)) {
port = new JTextField(getParm("-p", args), 5);
} else {
port = new JTextField("23", 5);
}
if (isSpecified("-sslType", args))
sslType.setSelectedItem(getParm("-sslType", args));
if (isSpecified("-sph", args))
proxyHost = new JTextField(getParm("-sph", args), 20);
else
proxyHost = new JTextField(20);
if (isSpecified("-f", args))
fpn = new JTextField(getParm("-f", args), 20);
else
fpn = new JTextField(20);
if (isSpecified("-cp", args)) {
String codepage = getParm("-cp", args);
String[] acps = CharMappings.getAvailableCodePages();
jtb.setSelected(true);
for (String acp : acps) {
if (acp.equals(codepage)) jtb.setSelected(false);
}
cpb.setSelectedItem(codepage);
}
if (isSpecified("-e", args))
ec.setSelected(true);
else
ec.setSelected(false);
if (isSpecified("-t", args))
tc.setSelected(true);
else
tc.setSelected(false);
if (isSpecified("-132", args))
sdBig.setSelected(true);
else
sdNormal.setSelected(true);
if (isSpecified("-dn", args))
deviceName = new JTextField(getParm("-dn", args), 20);
else
deviceName = new JTextField(20);
if (isSpecified("-dn=hostname", args)) {
sdn.setSelected(true);
deviceName.setEnabled(false);
} else {
sdn.setSelected(false);
deviceName.setEnabled(true);
}
if (isSpecified("-spp", args)) {
proxyPort = new JTextField(getParm("-spp", args), 5);
} else {
proxyPort = new JTextField("1080", 5);
}
if (isSpecified("-usp", args))
useProxy.setSelected(true);
else
useProxy.setSelected(false);
if (isSpecified("-noembed", args))
noEmbed.setSelected(true);
else
noEmbed.setSelected(false);
if (isSpecified("-d", args))
deamon.setSelected(true);
else
deamon.setSelected(false);
if (isSpecified("-nc", args))
newJVM.setSelected(true);
else
newJVM.setSelected(false);
if (isSpecified("-hb", args))
heartBeat.setSelected(true);
else
heartBeat.setSelected(false);
if (isSpecified("-hb", args))
heartBeat.setSelected(true);
else
heartBeat.setSelected(false);
}
//Create main attributes panel
JPanel mp = new JPanel();
BoxLayout mpLayout = new BoxLayout(mp, BoxLayout.Y_AXIS);
mp.setLayout(mpLayout);
//System Name panel
JPanel snp = new JPanel();
AlignLayout snpLayout = new AlignLayout(2, 5, 5);
snp.setLayout(snpLayout);
snp.setBorder(BorderFactory.createEtchedBorder());
addLabelComponent(LangTool.getString("conf.labelSystemName"),
systemName,
snp);
addLabelComponent(" ",
noEmbed,
snp);
addLabelComponent(" ",
deamon,
snp);
addLabelComponent(" ",
newJVM,
snp);
//System Id panel
JPanel sip = new JPanel();
AlignLayout al = new AlignLayout(2, 5, 5);
sip.setLayout(al);
sip.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelSystemIdTitle")));
addLabelComponent(LangTool.getString("conf.labelSystemId"),
systemId,
sip);
addLabelComponent(LangTool.getString("conf.labelPort"),
port,
sip);
addLabelComponent(LangTool.getString("conf.labelDeviceName"),
deviceName,
sip);
addLabelComponent("",
sdn,
sip);
sdn.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(ItemEvent e) {
doItemStateChanged(e);
}
});
addLabelComponent(LangTool.getString("conf.labelSSLType"),
sslType,
sip);
addLabelComponent("",
heartBeat,
sip);
// options panel
JPanel op = new JPanel();
BoxLayout opLayout = new BoxLayout(op, BoxLayout.Y_AXIS);
op.setLayout(opLayout);
op.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelOptionsTitle")));
// file name panel
JPanel fp = new JPanel();
BoxLayout fpLayout = new BoxLayout(fp, BoxLayout.Y_AXIS);
fp.setLayout(fpLayout);
fp.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelConfFile")));
fp.add(fpn);
// screen dimensions panel
JPanel sdp = new JPanel();
BoxLayout sdpLayout = new BoxLayout(sdp, BoxLayout.X_AXIS);
sdp.setLayout(sdpLayout);
sdp.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelDimensions")));
// Group the radio buttons.
ButtonGroup sdGroup = new ButtonGroup();
sdGroup.add(sdNormal);
sdGroup.add(sdBig);
sdp.add(sdNormal);
sdp.add(sdBig);
// code page panel
JPanel cp = new JPanel();
BoxLayout cpLayout = new BoxLayout(cp, BoxLayout.X_AXIS);
cp.setLayout(cpLayout);
cp.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelCodePage")));
cp.add(cpb);
cp.add(jtb);
// emulation mode panel
JPanel ep = new JPanel();
BoxLayout epLayout = new BoxLayout(ep, BoxLayout.X_AXIS);
ep.setLayout(epLayout);
ep.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelEmulateMode")));
ep.add(ec);
// title to be use panel
JPanel tp = new JPanel();
BoxLayout tpLayout = new BoxLayout(tp, BoxLayout.X_AXIS);
tp.setLayout(tpLayout);
tp.setBorder(BorderFactory.createTitledBorder(
""));
addLabelComponent("",
tc,
tp);
// add all options to Options panel
op.add(fp);
op.add(sdp);
op.add(cp);
op.add(ep);
op.add(tp);
//System Id panel
JPanel sprox = new JPanel();
AlignLayout spal = new AlignLayout(2, 5, 5);
sprox.setLayout(spal);
sprox.setBorder(BorderFactory.createEtchedBorder());
addLabelComponent("",
useProxy,
sprox);
addLabelComponent(LangTool.getString("conf.labelProxyHost"),
proxyHost,
sprox);
addLabelComponent(LangTool.getString("conf.labelProxyPort"),
proxyPort,
sprox);
confTabs.addTab(LangTool.getString("conf.tabGeneral"), snp);
confTabs.addTab(LangTool.getString("conf.tabTCP"), sip);
confTabs.addTab(LangTool.getString("conf.tabOptions"), op);
confTabs.addTab(LangTool.getString("conf.tabProxy"), sprox);
if (systemName.getText().trim().length() <= 0) {
confTabs.setEnabledAt(1, false);
confTabs.setEnabledAt(2, false);
confTabs.setEnabledAt(3, false);
}
systemName.setAlignmentX(Component.CENTER_ALIGNMENT);
systemId.setAlignmentX(Component.CENTER_ALIGNMENT);
fpn.setAlignmentX(Component.CENTER_ALIGNMENT);
cpb.setAlignmentX(Component.CENTER_ALIGNMENT);
Object[] message = new Object[1];
message[0] = confTabs;
options = new JButton[2];
String title;
final String propKey2 = propKey;
if (propKey2 == null) {
Action add = new AbstractAction(LangTool.getString("conf.optAdd")) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
doConfigureAction(propKey2);
}
};
options[0] = new JButton(add);
((JButton) options[0]).setEnabled(false);
title = LangTool.getString("conf.addEntryATitle");
} else {
Action edit = new AbstractAction(LangTool.getString("conf.optEdit")) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
doConfigureAction(propKey2);
}
};
options[0] = new JButton(edit);
title = LangTool.getString("conf.addEntryETitle");
}
Action cancel = new AbstractAction(LangTool.getString("conf.optCancel")) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
};
options[1] = new JButton(cancel);
JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE,
JOptionPane.DEFAULT_OPTION, null,
options, options[0]);
pane.setInitialValue(options[0]);
pane.setComponentOrientation(parent.getComponentOrientation());
dialog = pane.createDialog(parent, title); //, JRootPane.PLAIN_DIALOG);
dialog.setVisible(true);
return systemName.getText();
}
/**
* Return the list of available code pages depending on which character
* mapping flag is set.
*
* @return list of available code pages
*/
private static String[] getAvailableCodePages() {
return CharMappings.getAvailableCodePages();
}
/**
* React to the configuration action button to perform to Add or Edit the
* entry
*
* @param propKey - key to act upon
*/
private static void doConfigureAction(String propKey) {
if (propKey == null) {
props.put(systemName.getText(), toArgString());
} else {
props.setProperty(systemName.getText(), toArgString());
}
dialog.dispose();
}
/**
* React on the state change for radio buttons
*
* @param e Item event to react to
*/
private static void doItemStateChanged(ItemEvent e) {
deviceName.setEnabled(true);
if (e.getStateChange() == ItemEvent.SELECTED) {
if (sdn.isSelected()) {
deviceName.setEnabled(false);
}
}
}
/**
* Available Code Page selection state change
*
* @param e Item event to react to changes
*/
private static void doCPStateChanged(ItemEvent e) {
String[] availCP = getAvailableCodePages();
cpb.removeAllItems();
cpb.addItem(LangTool.getString("conf.labelDefault"));
for (int x = 0; x < availCP.length; x++) {
cpb.addItem(availCP[x]);
}
}
private static void addLabelComponent(String text, Component comp, Container container) {
JLabel label = new JLabel(text);
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setHorizontalTextPosition(JLabel.LEFT);
container.add(label);
container.add(comp);
}
private static String getParm(String parm, String[] args) {
for (int x = 0; x < args.length; x++) {
if (args[x].equals(parm))
return args[x + 1];
}
return null;
}
private static boolean isSpecified(String parm, String[] args) {
for (int x = 0; x < args.length; x++) {
if (args[x] != null && args[x].equals(parm))
return true;
}
return false;
}
private static void doSomethingEntered() {
confTabs.setEnabledAt(1, true);
confTabs.setEnabledAt(2, true);
confTabs.setEnabledAt(3, true);
((JButton) options[0]).setEnabled(true);
newJVM.setEnabled(true);
noEmbed.setEnabled(true);
deamon.setEnabled(true);
}
private static void doNothingEntered() {
confTabs.setEnabledAt(1, false);
confTabs.setEnabledAt(2, false);
confTabs.setEnabledAt(3, false);
((JButton) options[0]).setEnabled(false);
newJVM.setEnabled(false);
noEmbed.setEnabled(false);
deamon.setEnabled(false);
}
private static String toArgString() {
StringBuilder sb = new StringBuilder();
sb.append(systemId.getText());
// port
if (port.getText() != null)
if (port.getText().trim().length() > 0)
sb.append(" -p " + port.getText().trim());
if (fpn.getText() != null)
if (fpn.getText().length() > 0)
sb.append(" -f " + fpn.getText());
if (!LangTool.getString("conf.labelDefault").equals(
cpb.getSelectedItem()))
sb.append(" -cp " + (String) cpb.getSelectedItem());
if (!TN5250jConstants.SSL_TYPE_NONE.equals(sslType.getSelectedItem()))
sb.append(" -sslType " + (String) sslType.getSelectedItem());
if (ec.isSelected())
sb.append(" -e");
if (tc.isSelected())
sb.append(" -t");
if (!sdNormal.isSelected())
sb.append(" -132");
if (deviceName.getText() != null && !sdn.isSelected())
if (deviceName.getText().trim().length() > 0)
if (deviceName.getText().trim().length() > 10)
sb.append(" -dn " + deviceName.getText().trim().substring(0, 10).toUpperCase());
else
sb.append(" -dn " + deviceName.getText().trim().toUpperCase());
if (sdn.isSelected())
sb.append(" -dn=hostname");
if (useProxy.isSelected())
sb.append(" -usp");
if (proxyHost.getText() != null)
if (proxyHost.getText().length() > 0)
sb.append(" -sph " + proxyHost.getText());
if (proxyPort.getText() != null)
if (proxyPort.getText().length() > 0)
sb.append(" -spp " + proxyPort.getText());
if (noEmbed.isSelected())
sb.append(" -noembed ");
if (deamon.isSelected())
sb.append(" -d ");
if (newJVM.isSelected())
sb.append(" -nc ");
if (heartBeat.isSelected())
sb.append(" -hb ");
return sb.toString();
}
static void parseArgs(String theStringList, String[] s) {
int x = 0;
StringTokenizer tokenizer = new StringTokenizer(theStringList, " ");
while (tokenizer.hasMoreTokens()) {
s[x++] = tokenizer.nextToken();
}
}
private static class SomethingEnteredDocument extends PlainDocument {
private static final long serialVersionUID = 1L;
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
super.insertString(offs, str, a);
if (getText(0, getLength()).length() > 0)
doSomethingEntered();
}
public void remove(int offs, int len) throws BadLocationException {
super.remove(offs, len);
if (getText(0, getLength()).length() == 0)
doNothingEntered();
}
}
}
| tn5250j/tn5250j | src/org/tn5250j/connectdialog/Configure.java | 6,232 | // screen dimensions panel | line_comment | nl | /*
* Title: tn5250J
* Copyright: Copyright (c) 2001
* Company:
*
* @author Kenneth J. Pouncey
* @version 0.4
* <p>
* Description:
* <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 2, or (at your option)
* any later version.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package org.tn5250j.connectdialog;
import java.awt.Component;
import java.awt.Container;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import org.tn5250j.TN5250jConstants;
import org.tn5250j.encoding.CharMappings;
import org.tn5250j.tools.AlignLayout;
import org.tn5250j.tools.LangTool;
class Configure {
private static Properties props = null;
// property input structures
private static JTextField systemName = null;
private static JTextField systemId = null;
private static JTextField port = null;
private static JTextField deviceName = null;
private static JTextField fpn = null;
private static JComboBox cpb = null;
private static JCheckBox jtb = null;
private static JCheckBox ec = null;
private static JCheckBox tc = null;
private static JCheckBox sdn = null;
private static JRadioButton sdNormal = null;
private static JCheckBox useProxy = null;
private static JTextField proxyHost = null;
private static JTextField proxyPort = null;
private static JCheckBox noEmbed = null;
private static JCheckBox deamon = null;
private static JCheckBox newJVM = null;
private static JComboBox sslType = null;
private static JCheckBox heartBeat = null;
private static JTabbedPane confTabs;
private static JDialog dialog = null;
private static Object[] options;
public static String doEntry(Frame parent, String propKey, Properties props2) {
props = props2;
confTabs = new JTabbedPane();
ec = new JCheckBox(LangTool.getString("conf.labelEnhanced"));
tc = new JCheckBox(LangTool.getString("conf.labelUseSystemName"));
sdn = new JCheckBox(LangTool.getString("conf.labelUseHostName"));
useProxy = new JCheckBox(LangTool.getString("conf.labelUseProxy"));
sdNormal = new JRadioButton(LangTool.getString("conf.label24"));
JRadioButton sdBig = new JRadioButton(LangTool.getString("conf.label27"));
noEmbed = new JCheckBox(LangTool.getString("conf.labelEmbed"));
deamon = new JCheckBox(LangTool.getString("conf.labelDeamon"));
newJVM = new JCheckBox(LangTool.getString("conf.labelNewJVM"));
heartBeat = new JCheckBox(LangTool.getString("conf.labelHeartBeat"));
jtb = new JCheckBox("AS/400 Toolbox");
jtb.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(ItemEvent e) {
doCPStateChanged(e);
}
});
cpb = new JComboBox();
String[] availCP = getAvailableCodePages();
cpb.addItem(LangTool.getString("conf.labelDefault"));
for (int x = 0; x < availCP.length; x++) {
cpb.addItem(availCP[x]);
}
sslType = new JComboBox();
for (int x = 0; x < TN5250jConstants.SSL_TYPES.length; x++) {
sslType.addItem(TN5250jConstants.SSL_TYPES[x]);
}
if (propKey == null) {
systemName = new JTextField(20);
systemId = new JTextField(20);
port = new JTextField("23", 5);
deviceName = new JTextField(20);
fpn = new JTextField(20);
proxyHost = new JTextField(20);
proxyPort = new JTextField("1080", 5);
ec.setSelected(true);
tc.setSelected(true);
jtb.setSelected(false);
sdNormal.setSelected(true);
deamon.setSelected(true);
newJVM.setEnabled(false);
noEmbed.setEnabled(false);
deamon.setEnabled(false);
systemName.setDocument(new SomethingEnteredDocument());
} else {
String[] args = new String[20];
parseArgs((String) props.get(propKey), args);
systemName = new JTextField(propKey, 20);
systemName.setEditable(false);
systemName.setEnabled(false);
systemId = new JTextField(args[0], 20);
if (isSpecified("-p", args)) {
port = new JTextField(getParm("-p", args), 5);
} else {
port = new JTextField("23", 5);
}
if (isSpecified("-sslType", args))
sslType.setSelectedItem(getParm("-sslType", args));
if (isSpecified("-sph", args))
proxyHost = new JTextField(getParm("-sph", args), 20);
else
proxyHost = new JTextField(20);
if (isSpecified("-f", args))
fpn = new JTextField(getParm("-f", args), 20);
else
fpn = new JTextField(20);
if (isSpecified("-cp", args)) {
String codepage = getParm("-cp", args);
String[] acps = CharMappings.getAvailableCodePages();
jtb.setSelected(true);
for (String acp : acps) {
if (acp.equals(codepage)) jtb.setSelected(false);
}
cpb.setSelectedItem(codepage);
}
if (isSpecified("-e", args))
ec.setSelected(true);
else
ec.setSelected(false);
if (isSpecified("-t", args))
tc.setSelected(true);
else
tc.setSelected(false);
if (isSpecified("-132", args))
sdBig.setSelected(true);
else
sdNormal.setSelected(true);
if (isSpecified("-dn", args))
deviceName = new JTextField(getParm("-dn", args), 20);
else
deviceName = new JTextField(20);
if (isSpecified("-dn=hostname", args)) {
sdn.setSelected(true);
deviceName.setEnabled(false);
} else {
sdn.setSelected(false);
deviceName.setEnabled(true);
}
if (isSpecified("-spp", args)) {
proxyPort = new JTextField(getParm("-spp", args), 5);
} else {
proxyPort = new JTextField("1080", 5);
}
if (isSpecified("-usp", args))
useProxy.setSelected(true);
else
useProxy.setSelected(false);
if (isSpecified("-noembed", args))
noEmbed.setSelected(true);
else
noEmbed.setSelected(false);
if (isSpecified("-d", args))
deamon.setSelected(true);
else
deamon.setSelected(false);
if (isSpecified("-nc", args))
newJVM.setSelected(true);
else
newJVM.setSelected(false);
if (isSpecified("-hb", args))
heartBeat.setSelected(true);
else
heartBeat.setSelected(false);
if (isSpecified("-hb", args))
heartBeat.setSelected(true);
else
heartBeat.setSelected(false);
}
//Create main attributes panel
JPanel mp = new JPanel();
BoxLayout mpLayout = new BoxLayout(mp, BoxLayout.Y_AXIS);
mp.setLayout(mpLayout);
//System Name panel
JPanel snp = new JPanel();
AlignLayout snpLayout = new AlignLayout(2, 5, 5);
snp.setLayout(snpLayout);
snp.setBorder(BorderFactory.createEtchedBorder());
addLabelComponent(LangTool.getString("conf.labelSystemName"),
systemName,
snp);
addLabelComponent(" ",
noEmbed,
snp);
addLabelComponent(" ",
deamon,
snp);
addLabelComponent(" ",
newJVM,
snp);
//System Id panel
JPanel sip = new JPanel();
AlignLayout al = new AlignLayout(2, 5, 5);
sip.setLayout(al);
sip.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelSystemIdTitle")));
addLabelComponent(LangTool.getString("conf.labelSystemId"),
systemId,
sip);
addLabelComponent(LangTool.getString("conf.labelPort"),
port,
sip);
addLabelComponent(LangTool.getString("conf.labelDeviceName"),
deviceName,
sip);
addLabelComponent("",
sdn,
sip);
sdn.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(ItemEvent e) {
doItemStateChanged(e);
}
});
addLabelComponent(LangTool.getString("conf.labelSSLType"),
sslType,
sip);
addLabelComponent("",
heartBeat,
sip);
// options panel
JPanel op = new JPanel();
BoxLayout opLayout = new BoxLayout(op, BoxLayout.Y_AXIS);
op.setLayout(opLayout);
op.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelOptionsTitle")));
// file name panel
JPanel fp = new JPanel();
BoxLayout fpLayout = new BoxLayout(fp, BoxLayout.Y_AXIS);
fp.setLayout(fpLayout);
fp.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelConfFile")));
fp.add(fpn);
// screen dimensions<SUF>
JPanel sdp = new JPanel();
BoxLayout sdpLayout = new BoxLayout(sdp, BoxLayout.X_AXIS);
sdp.setLayout(sdpLayout);
sdp.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelDimensions")));
// Group the radio buttons.
ButtonGroup sdGroup = new ButtonGroup();
sdGroup.add(sdNormal);
sdGroup.add(sdBig);
sdp.add(sdNormal);
sdp.add(sdBig);
// code page panel
JPanel cp = new JPanel();
BoxLayout cpLayout = new BoxLayout(cp, BoxLayout.X_AXIS);
cp.setLayout(cpLayout);
cp.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelCodePage")));
cp.add(cpb);
cp.add(jtb);
// emulation mode panel
JPanel ep = new JPanel();
BoxLayout epLayout = new BoxLayout(ep, BoxLayout.X_AXIS);
ep.setLayout(epLayout);
ep.setBorder(BorderFactory.createTitledBorder(
LangTool.getString("conf.labelEmulateMode")));
ep.add(ec);
// title to be use panel
JPanel tp = new JPanel();
BoxLayout tpLayout = new BoxLayout(tp, BoxLayout.X_AXIS);
tp.setLayout(tpLayout);
tp.setBorder(BorderFactory.createTitledBorder(
""));
addLabelComponent("",
tc,
tp);
// add all options to Options panel
op.add(fp);
op.add(sdp);
op.add(cp);
op.add(ep);
op.add(tp);
//System Id panel
JPanel sprox = new JPanel();
AlignLayout spal = new AlignLayout(2, 5, 5);
sprox.setLayout(spal);
sprox.setBorder(BorderFactory.createEtchedBorder());
addLabelComponent("",
useProxy,
sprox);
addLabelComponent(LangTool.getString("conf.labelProxyHost"),
proxyHost,
sprox);
addLabelComponent(LangTool.getString("conf.labelProxyPort"),
proxyPort,
sprox);
confTabs.addTab(LangTool.getString("conf.tabGeneral"), snp);
confTabs.addTab(LangTool.getString("conf.tabTCP"), sip);
confTabs.addTab(LangTool.getString("conf.tabOptions"), op);
confTabs.addTab(LangTool.getString("conf.tabProxy"), sprox);
if (systemName.getText().trim().length() <= 0) {
confTabs.setEnabledAt(1, false);
confTabs.setEnabledAt(2, false);
confTabs.setEnabledAt(3, false);
}
systemName.setAlignmentX(Component.CENTER_ALIGNMENT);
systemId.setAlignmentX(Component.CENTER_ALIGNMENT);
fpn.setAlignmentX(Component.CENTER_ALIGNMENT);
cpb.setAlignmentX(Component.CENTER_ALIGNMENT);
Object[] message = new Object[1];
message[0] = confTabs;
options = new JButton[2];
String title;
final String propKey2 = propKey;
if (propKey2 == null) {
Action add = new AbstractAction(LangTool.getString("conf.optAdd")) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
doConfigureAction(propKey2);
}
};
options[0] = new JButton(add);
((JButton) options[0]).setEnabled(false);
title = LangTool.getString("conf.addEntryATitle");
} else {
Action edit = new AbstractAction(LangTool.getString("conf.optEdit")) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
doConfigureAction(propKey2);
}
};
options[0] = new JButton(edit);
title = LangTool.getString("conf.addEntryETitle");
}
Action cancel = new AbstractAction(LangTool.getString("conf.optCancel")) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
};
options[1] = new JButton(cancel);
JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE,
JOptionPane.DEFAULT_OPTION, null,
options, options[0]);
pane.setInitialValue(options[0]);
pane.setComponentOrientation(parent.getComponentOrientation());
dialog = pane.createDialog(parent, title); //, JRootPane.PLAIN_DIALOG);
dialog.setVisible(true);
return systemName.getText();
}
/**
* Return the list of available code pages depending on which character
* mapping flag is set.
*
* @return list of available code pages
*/
private static String[] getAvailableCodePages() {
return CharMappings.getAvailableCodePages();
}
/**
* React to the configuration action button to perform to Add or Edit the
* entry
*
* @param propKey - key to act upon
*/
private static void doConfigureAction(String propKey) {
if (propKey == null) {
props.put(systemName.getText(), toArgString());
} else {
props.setProperty(systemName.getText(), toArgString());
}
dialog.dispose();
}
/**
* React on the state change for radio buttons
*
* @param e Item event to react to
*/
private static void doItemStateChanged(ItemEvent e) {
deviceName.setEnabled(true);
if (e.getStateChange() == ItemEvent.SELECTED) {
if (sdn.isSelected()) {
deviceName.setEnabled(false);
}
}
}
/**
* Available Code Page selection state change
*
* @param e Item event to react to changes
*/
private static void doCPStateChanged(ItemEvent e) {
String[] availCP = getAvailableCodePages();
cpb.removeAllItems();
cpb.addItem(LangTool.getString("conf.labelDefault"));
for (int x = 0; x < availCP.length; x++) {
cpb.addItem(availCP[x]);
}
}
private static void addLabelComponent(String text, Component comp, Container container) {
JLabel label = new JLabel(text);
label.setAlignmentX(Component.LEFT_ALIGNMENT);
label.setHorizontalTextPosition(JLabel.LEFT);
container.add(label);
container.add(comp);
}
private static String getParm(String parm, String[] args) {
for (int x = 0; x < args.length; x++) {
if (args[x].equals(parm))
return args[x + 1];
}
return null;
}
private static boolean isSpecified(String parm, String[] args) {
for (int x = 0; x < args.length; x++) {
if (args[x] != null && args[x].equals(parm))
return true;
}
return false;
}
private static void doSomethingEntered() {
confTabs.setEnabledAt(1, true);
confTabs.setEnabledAt(2, true);
confTabs.setEnabledAt(3, true);
((JButton) options[0]).setEnabled(true);
newJVM.setEnabled(true);
noEmbed.setEnabled(true);
deamon.setEnabled(true);
}
private static void doNothingEntered() {
confTabs.setEnabledAt(1, false);
confTabs.setEnabledAt(2, false);
confTabs.setEnabledAt(3, false);
((JButton) options[0]).setEnabled(false);
newJVM.setEnabled(false);
noEmbed.setEnabled(false);
deamon.setEnabled(false);
}
private static String toArgString() {
StringBuilder sb = new StringBuilder();
sb.append(systemId.getText());
// port
if (port.getText() != null)
if (port.getText().trim().length() > 0)
sb.append(" -p " + port.getText().trim());
if (fpn.getText() != null)
if (fpn.getText().length() > 0)
sb.append(" -f " + fpn.getText());
if (!LangTool.getString("conf.labelDefault").equals(
cpb.getSelectedItem()))
sb.append(" -cp " + (String) cpb.getSelectedItem());
if (!TN5250jConstants.SSL_TYPE_NONE.equals(sslType.getSelectedItem()))
sb.append(" -sslType " + (String) sslType.getSelectedItem());
if (ec.isSelected())
sb.append(" -e");
if (tc.isSelected())
sb.append(" -t");
if (!sdNormal.isSelected())
sb.append(" -132");
if (deviceName.getText() != null && !sdn.isSelected())
if (deviceName.getText().trim().length() > 0)
if (deviceName.getText().trim().length() > 10)
sb.append(" -dn " + deviceName.getText().trim().substring(0, 10).toUpperCase());
else
sb.append(" -dn " + deviceName.getText().trim().toUpperCase());
if (sdn.isSelected())
sb.append(" -dn=hostname");
if (useProxy.isSelected())
sb.append(" -usp");
if (proxyHost.getText() != null)
if (proxyHost.getText().length() > 0)
sb.append(" -sph " + proxyHost.getText());
if (proxyPort.getText() != null)
if (proxyPort.getText().length() > 0)
sb.append(" -spp " + proxyPort.getText());
if (noEmbed.isSelected())
sb.append(" -noembed ");
if (deamon.isSelected())
sb.append(" -d ");
if (newJVM.isSelected())
sb.append(" -nc ");
if (heartBeat.isSelected())
sb.append(" -hb ");
return sb.toString();
}
static void parseArgs(String theStringList, String[] s) {
int x = 0;
StringTokenizer tokenizer = new StringTokenizer(theStringList, " ");
while (tokenizer.hasMoreTokens()) {
s[x++] = tokenizer.nextToken();
}
}
private static class SomethingEnteredDocument extends PlainDocument {
private static final long serialVersionUID = 1L;
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
super.insertString(offs, str, a);
if (getText(0, getLength()).length() > 0)
doSomethingEntered();
}
public void remove(int offs, int len) throws BadLocationException {
super.remove(offs, len);
if (getText(0, getLength()).length() == 0)
doNothingEntered();
}
}
}
|
29856_9 | /*
This file is part of the Fuzion language implementation.
The Fuzion language implementation 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, version 3 of the License.
The Fuzion language implementation 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 The
Fuzion language implementation. If not, see <https://www.gnu.org/licenses/>.
*/
/*-----------------------------------------------------------------------
*
* Tokiwa Software GmbH, Germany
*
* Source of class Case
*
*---------------------------------------------------------------------*/
package dev.flang.ast;
import dev.flang.util.ANY;
import dev.flang.util.Errors;
import dev.flang.util.List;
import dev.flang.util.SourcePosition;
/**
* FormalGenerics represents a list for formal generics argument.
*
* @author Fridtjof Siebert ([email protected])
*/
public class FormalGenerics extends ANY
{
/*---------------------------- constants ----------------------------*/
/**
* Convenience constant for an empty formal generics instance.
*/
public static final FormalGenerics NONE = new FormalGenerics(new List<>());
/*---------------------------- variables ----------------------------*/
/**
* Field with type from this.type created in case fieldName != null.
*
* This is private to prevent direct access that does not take care about
* isOpen.
*/
public final List<Generic> list;
/*-------------------------- constructors ---------------------------*/
/**
* Constructor for a FormalGenerics instance
*
* @param l the list of formal generics. May not be empty.
*/
public FormalGenerics(List<Generic> l)
{
list = l;
}
/*----------------------------- methods -----------------------------*/
/**
* true if the last formal generic in an open formal generics list.
*/
public boolean isOpen()
{
return !list.isEmpty() && list.getLast().isOpen();
}
/**
* Check if the number of actual generics provided as an argument matches the
* number of formal arguments required by this. This takes into account that
* the formal generics list might be open, i.e, the last argument can be
* repeated zero or more times.
*
* @param actualGenerics the list of actual generics.
*
* @return true iff the number of actual arguments fits with the number of
* expected arguments.
*/
public boolean sizeMatches(List<AbstractType> actualGenerics)
{
if (_asActuals == actualGenerics)
{
return true;
}
else if (isOpen())
{
return (list.size()-1) <= actualGenerics.size();
}
else
{
return list.size() == actualGenerics.size();
}
}
/**
* Check if the number of actualGenerics match this FormalGenerics. If not,
* create a compiler error.
*
* @param actualGenerics the actual generics to check
*
* @param pos the source code position at which the error should be reported
*
* @param detail1 part of the detail message to indicate where this happened,
* i.e., "call" or "type".
*
* @param detail2 optional extra lines of detail message giving further
* information, like "Calling feature: xyz.f\n" or "Type: Stack<bool,int>\n".
*
* @return true iff size and type of actualGenerics does match
*/
public boolean errorIfSizeDoesNotMatch(List<AbstractType> actualGenerics,
SourcePosition pos,
String detail1,
String detail2)
{
if (PRECONDITIONS) require
(Errors.any() || !actualGenerics.contains(Types.t_ERROR));
var result = sizeMatches(actualGenerics);
if (!result)
{
AstErrors.wrongNumberOfGenericArguments(this,
actualGenerics,
pos,
detail1,
detail2);
}
return result;
}
/**
* Convenience function to resolve all types in a list of actual generic
* arguments of a call or a type.
*
* @param generics the actual generic arguments that should be resolved
*
* @return a new array of the resolved generics
*/
public static List<AbstractType> resolve(Resolution res, List<AbstractType> generics, AbstractFeature outer)
{
if (!(generics instanceof FormalGenerics.AsActuals))
{
generics = generics.map(t -> t.resolve(res, outer));
}
return generics;
}
private List<AbstractType> _asActuals = null;
/**
* Wrapper class for result of asActuals(). This is used to quickly identify
* the generics list of formals used as actuals, e.g., in an outer reference,
* such that it can be replaced 1:1 by the actual generic arguments.
*/
class AsActuals extends List<AbstractType>
{
/**
* create AsActuals from FormalGenerics.this.list and freeze it.
*/
AsActuals()
{
// NYI: This is a bit ugly, can we avoid adding all these types
// here? They should never be used since AsActuals is only a
// placeholder for the actual generics.
for (Generic g : list)
{
add(g.type());
}
freeze();
}
/**
* Create non-frozen clone of from.
*/
AsActuals(AsActuals from)
{
super(from);
}
/**
* Create non-frozen clone of this.
*/
public List<AbstractType> clone()
{
return new AsActuals(this);
}
/**
* Check if this are the formal generics of f used as actuals.
*/
boolean actualsOf(AbstractFeature f) {
return f.generics() == FormalGenerics.this;
}
public boolean sizeMatches(List<AbstractType> actualGenerics)
{
return FormalGenerics.this.sizeMatches(actualGenerics);
}
};
/**
* Create the formal generics parameters for an outer reference for any inner
* feature declared within this formal generic's feature.
*
* @return actual generics that match these formal generics.
*/
public List<AbstractType> asActuals()
{
var result = _asActuals;
if (result == null)
{
if (this == FormalGenerics.NONE)
{
result = UnresolvedType.NONE;
}
else
{
result = new AsActuals();
}
_asActuals = result;
}
if (POSTCONDITIONS) ensure
(sizeMatches(result));
return result;
}
/**
* Add type parameter g to this list of formal generics.
*
* @param g the new type parameter
*/
FormalGenerics addTypeParameter(Generic g)
{
var result = this;
if (this == FormalGenerics.NONE)
{
result = new FormalGenerics(new List<>(g));
}
else
{
list.add(g);
if (_asActuals != null)
{
_asActuals.add(g.type());
}
}
return result;
}
/**
* Number of generic arguments expected as a text to be used in error messages
* about wrong number of actual generic arguments.
*
* @return
*/
public String sizeText()
{
int sz = isOpen() ? list.size() - 1
: list.size();
return
isOpen() && (sz == 0) ? "any number of generic arguments"
: isOpen() && (sz == 1) ? "at least one generic argument"
: isOpen() && (sz > 1) ? "at least " + sz + " generic arguments"
: !isOpen() && (sz == 0) ? "no generic arguments"
: !isOpen() && (sz == 1) ? "one generic argument"
: "" + sz + " generic arguments" ;
}
/**
* toString
*
* @return
*/
public String toString()
{
return !isOpen() && list.isEmpty() ? ""
: list + (isOpen() ? "..." : "");
}
}
| tokiwa-software/fuzion | src/dev/flang/ast/FormalGenerics.java | 2,352 | /*----------------------------- methods -----------------------------*/ | block_comment | nl | /*
This file is part of the Fuzion language implementation.
The Fuzion language implementation 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, version 3 of the License.
The Fuzion language implementation 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 The
Fuzion language implementation. If not, see <https://www.gnu.org/licenses/>.
*/
/*-----------------------------------------------------------------------
*
* Tokiwa Software GmbH, Germany
*
* Source of class Case
*
*---------------------------------------------------------------------*/
package dev.flang.ast;
import dev.flang.util.ANY;
import dev.flang.util.Errors;
import dev.flang.util.List;
import dev.flang.util.SourcePosition;
/**
* FormalGenerics represents a list for formal generics argument.
*
* @author Fridtjof Siebert ([email protected])
*/
public class FormalGenerics extends ANY
{
/*---------------------------- constants ----------------------------*/
/**
* Convenience constant for an empty formal generics instance.
*/
public static final FormalGenerics NONE = new FormalGenerics(new List<>());
/*---------------------------- variables ----------------------------*/
/**
* Field with type from this.type created in case fieldName != null.
*
* This is private to prevent direct access that does not take care about
* isOpen.
*/
public final List<Generic> list;
/*-------------------------- constructors ---------------------------*/
/**
* Constructor for a FormalGenerics instance
*
* @param l the list of formal generics. May not be empty.
*/
public FormalGenerics(List<Generic> l)
{
list = l;
}
/*----------------------------- methods<SUF>*/
/**
* true if the last formal generic in an open formal generics list.
*/
public boolean isOpen()
{
return !list.isEmpty() && list.getLast().isOpen();
}
/**
* Check if the number of actual generics provided as an argument matches the
* number of formal arguments required by this. This takes into account that
* the formal generics list might be open, i.e, the last argument can be
* repeated zero or more times.
*
* @param actualGenerics the list of actual generics.
*
* @return true iff the number of actual arguments fits with the number of
* expected arguments.
*/
public boolean sizeMatches(List<AbstractType> actualGenerics)
{
if (_asActuals == actualGenerics)
{
return true;
}
else if (isOpen())
{
return (list.size()-1) <= actualGenerics.size();
}
else
{
return list.size() == actualGenerics.size();
}
}
/**
* Check if the number of actualGenerics match this FormalGenerics. If not,
* create a compiler error.
*
* @param actualGenerics the actual generics to check
*
* @param pos the source code position at which the error should be reported
*
* @param detail1 part of the detail message to indicate where this happened,
* i.e., "call" or "type".
*
* @param detail2 optional extra lines of detail message giving further
* information, like "Calling feature: xyz.f\n" or "Type: Stack<bool,int>\n".
*
* @return true iff size and type of actualGenerics does match
*/
public boolean errorIfSizeDoesNotMatch(List<AbstractType> actualGenerics,
SourcePosition pos,
String detail1,
String detail2)
{
if (PRECONDITIONS) require
(Errors.any() || !actualGenerics.contains(Types.t_ERROR));
var result = sizeMatches(actualGenerics);
if (!result)
{
AstErrors.wrongNumberOfGenericArguments(this,
actualGenerics,
pos,
detail1,
detail2);
}
return result;
}
/**
* Convenience function to resolve all types in a list of actual generic
* arguments of a call or a type.
*
* @param generics the actual generic arguments that should be resolved
*
* @return a new array of the resolved generics
*/
public static List<AbstractType> resolve(Resolution res, List<AbstractType> generics, AbstractFeature outer)
{
if (!(generics instanceof FormalGenerics.AsActuals))
{
generics = generics.map(t -> t.resolve(res, outer));
}
return generics;
}
private List<AbstractType> _asActuals = null;
/**
* Wrapper class for result of asActuals(). This is used to quickly identify
* the generics list of formals used as actuals, e.g., in an outer reference,
* such that it can be replaced 1:1 by the actual generic arguments.
*/
class AsActuals extends List<AbstractType>
{
/**
* create AsActuals from FormalGenerics.this.list and freeze it.
*/
AsActuals()
{
// NYI: This is a bit ugly, can we avoid adding all these types
// here? They should never be used since AsActuals is only a
// placeholder for the actual generics.
for (Generic g : list)
{
add(g.type());
}
freeze();
}
/**
* Create non-frozen clone of from.
*/
AsActuals(AsActuals from)
{
super(from);
}
/**
* Create non-frozen clone of this.
*/
public List<AbstractType> clone()
{
return new AsActuals(this);
}
/**
* Check if this are the formal generics of f used as actuals.
*/
boolean actualsOf(AbstractFeature f) {
return f.generics() == FormalGenerics.this;
}
public boolean sizeMatches(List<AbstractType> actualGenerics)
{
return FormalGenerics.this.sizeMatches(actualGenerics);
}
};
/**
* Create the formal generics parameters for an outer reference for any inner
* feature declared within this formal generic's feature.
*
* @return actual generics that match these formal generics.
*/
public List<AbstractType> asActuals()
{
var result = _asActuals;
if (result == null)
{
if (this == FormalGenerics.NONE)
{
result = UnresolvedType.NONE;
}
else
{
result = new AsActuals();
}
_asActuals = result;
}
if (POSTCONDITIONS) ensure
(sizeMatches(result));
return result;
}
/**
* Add type parameter g to this list of formal generics.
*
* @param g the new type parameter
*/
FormalGenerics addTypeParameter(Generic g)
{
var result = this;
if (this == FormalGenerics.NONE)
{
result = new FormalGenerics(new List<>(g));
}
else
{
list.add(g);
if (_asActuals != null)
{
_asActuals.add(g.type());
}
}
return result;
}
/**
* Number of generic arguments expected as a text to be used in error messages
* about wrong number of actual generic arguments.
*
* @return
*/
public String sizeText()
{
int sz = isOpen() ? list.size() - 1
: list.size();
return
isOpen() && (sz == 0) ? "any number of generic arguments"
: isOpen() && (sz == 1) ? "at least one generic argument"
: isOpen() && (sz > 1) ? "at least " + sz + " generic arguments"
: !isOpen() && (sz == 0) ? "no generic arguments"
: !isOpen() && (sz == 1) ? "one generic argument"
: "" + sz + " generic arguments" ;
}
/**
* toString
*
* @return
*/
public String toString()
{
return !isOpen() && list.isEmpty() ? ""
: list + (isOpen() ? "..." : "");
}
}
|
6380_0 | package com.tom.cpm.web.client.java;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import com.google.gwt.core.client.JavaScriptException;
import com.tom.cpm.web.client.resources.Resources;
import elemental2.core.Global;
import elemental2.core.JsArray;
import elemental2.core.JsNumber;
import elemental2.core.JsObject;
import elemental2.core.JsRegExp;
import elemental2.core.JsString;
import elemental2.dom.DomGlobal;
import elemental2.promise.Promise;
import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import jsinterop.base.Js;
public class Java {
private static SimpleDateFormat year = new SimpleDateFormat("yyyy");
private static SimpleDateFormat month = new SimpleDateFormat("MM");
private static SimpleDateFormat day = new SimpleDateFormat("dd");
private static SimpleDateFormat hour = new SimpleDateFormat("HH");
private static SimpleDateFormat minute = new SimpleDateFormat("mm");
private static SimpleDateFormat second = new SimpleDateFormat("ss");
private static final JsRegExp formatRegex = new JsRegExp("%(?:(\\d)+\\$)?([-#+ 0,(]+)?(\\d+)?(?:\\.(\\d)+)?([bBhHsScCoxXeEfgGaAn%]|[tT][HIklMSLNpzZsQBbhAaCYyjmdeRTrDTc])", "g");
private static final JsRegExp replaceRegex = new JsRegExp("\\${(.*?)}", "g");
public static String format(final String format, final Object... args) {
int[] inc = new int[1];
return doFormat(format, (argIn, flags, width, prec, mode) -> {
if(mode.equals("%"))return "%";
int arg = argIn.isEmpty() ? inc[0] : (Integer.parseInt(argIn) - 1);
inc[0]++;
switch (mode) {
case "s":
return String.valueOf(args[arg]);
case "f":
if(!prec.isEmpty())
return fixed(((Number)args[arg]).floatValue(), Integer.parseInt(prec));
return String.valueOf(args[arg]);
case "X":
{
JsString s = Js.uncheckedCast(new JsNumber(((Number)args[arg]).intValue()).toString(16));
return s.padStart(width.isEmpty() ? 0 : Integer.parseInt(width), "0");
}
case "tY":
return year.format(new Date(((Number)args[arg]).longValue()));
case "tm":
return month.format(new Date(((Number)args[arg]).longValue()));
case "td":
return day.format(new Date(((Number)args[arg]).longValue()));
case "tH":
return hour.format(new Date(((Number)args[arg]).longValue()));
case "tM":
return minute.format(new Date(((Number)args[arg]).longValue()));
case "tS":
return second.format(new Date(((Number)args[arg]).longValue()));
default:
throw new RuntimeException("Format mode unknown: " + mode);
}
});
}
private static String doFormat(String format, FormatCallback cb) {
JsString str = Js.uncheckedCast(format);
StringEx stre = Js.uncheckedCast(str.replace(formatRegex, "$${$1:$2:$3:$4:$5}"));
return stre.replace(replaceRegex, (x, fmt) -> {
String[] sp = fmt.toString().split(":");
return cb.exec(sp[0], sp[1], sp[2], sp[3], sp[4]);
});
}
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "String")
public static class StringEx {
public native String replace(JsRegExp replaceregex, ReplaceCallback object);
}
@JsFunction
public interface ReplaceCallback {
String getReplacement(String fullText, String capture);
}
public interface FormatCallback {
String exec(String arg, String flags, String width, String prec, String mode);
}
public static String fixed(float n, int w) {
return new JsNumber(n).toFixed(w);
}
public static int parseUnsignedInt(String s, int radix)
throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
int len = s.length();
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar == '-') {
throw new
NumberFormatException(String.format("Illegal leading minus sign " +
"on unsigned string %s.", s));
} else {
if (len <= 5 || // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits
(radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
return Integer.parseInt(s, radix);
} else {
long ell = Long.parseLong(s, radix);
if ((ell & 0xffff_ffff_0000_0000L) == 0) {
return (int) ell;
} else {
throw new
NumberFormatException(String.format("String value %s exceeds " +
"range of unsigned int.", s));
}
}
}
} else {
throw new NumberFormatException("For input string: \"" + s + "\"");
}
}
public static InputStream getResourceAsStream(String path) {
path = path.substring(1);
String dt = Resources.getResource(path);
if(dt != null) {
return new ResourceInputStream(path, Base64.getDecoder().decode(dt));
}
System.err.println("Resource not found: " + path);
return null;
}
public static class ResourceInputStream extends ByteArrayInputStream {
public final String path;
public ResourceInputStream(String path, byte[] buf) {
super(buf);
this.path = path;
}
}
public static int toUnsignedInt(byte x) {
return (x) & 0xff;
}
public static String getQueryVariable(String key) {
if(DomGlobal.window.location.search.isEmpty())return null;
String query = DomGlobal.window.location.search.substring(1);
String[] vars = query.split("&");
for (int i = 0; i < vars.length; i++) {
String[] pair = vars[i].split("=");
if (Global.decodeURIComponent(pair[0]).equals(key)) {
return Global.decodeURIComponent(pair[1]);
}
}
return null;
}
public static void removeQueryVariable(String key) {
if(DomGlobal.window.location.search.isEmpty())return;
String newUrl = DomGlobal.window.location.protocol + "//" + DomGlobal.window.location.host + DomGlobal.window.location.pathname;
List<String> q = new ArrayList<>();
String query = DomGlobal.window.location.search.substring(1);
if(query.isEmpty())return;
String[] vars = query.split("&");
for (int i = 0; i < vars.length; i++) {
String[] pair = vars[i].split("=");
if (!Global.decodeURIComponent(pair[0]).equals(key)) {
q.add(vars[i]);
}
}
if(!q.isEmpty()) {
newUrl += q.stream().collect(Collectors.joining("&", "?", ""));
}
DomGlobal.window.history.pushState(new JsObject(), "", newUrl);
}
public static String getPlatform() {
String ua = DomGlobal.navigator.userAgent;
JsString jua = Js.uncheckedCast(ua);
JsArray<String> M = jua.match(new JsRegExp("(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*(\\d+)", "i"));
JsArray<String> tem;
if(Js.isFalsy(M))M = new JsArray<>();
if(new JsRegExp("trident", "i").test(M.getAt(1))) {
tem = new JsRegExp("\\brv[ :]+(\\d+)", "g").exec(ua);
if(Js.isFalsy(tem))tem = new JsArray<>();
String v = tem.getAt(1);
if(Js.isFalsy(v))v = "";
return "IE " + v;
}
if("Chrome".equals(M.getAt(1))) {
tem = jua.match(new JsRegExp("\\bOPR|Edge\\/(\\d+)"));
if(tem != null) { return "Opera " + tem.getAt(1); }
}
M = Js.isTruthy(M.getAt(2)) ? JsArray.of(M.getAt(1), M.getAt(2)) : JsArray.of(DomGlobal.navigator.appName, DomGlobal.navigator.appVersion, "-?");
if((tem = jua.match(new JsRegExp("version\\/(\\d+)", "i"))) != null) {M.splice(1, 1, tem.getAt(1));}
return M.getAt(0) + " " + M.getAt(1);
}
public static <T> void promiseToCf(Promise<T> pr, CompletableFuture<T> cf) {
pr.then(i -> {
cf.complete(i);
return null;
}).catch_(e -> {
cf.completeExceptionally(e instanceof Throwable ? (Throwable) e : new JavaScriptException(e));
return null;
});
}
}
| tom5454/CustomPlayerModels | Web/src/main/java/com/tom/cpm/web/client/java/Java.java | 2,693 | // Integer.MAX_VALUE in Character.MAX_RADIX is 6 digits | line_comment | nl | package com.tom.cpm.web.client.java;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import com.google.gwt.core.client.JavaScriptException;
import com.tom.cpm.web.client.resources.Resources;
import elemental2.core.Global;
import elemental2.core.JsArray;
import elemental2.core.JsNumber;
import elemental2.core.JsObject;
import elemental2.core.JsRegExp;
import elemental2.core.JsString;
import elemental2.dom.DomGlobal;
import elemental2.promise.Promise;
import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import jsinterop.base.Js;
public class Java {
private static SimpleDateFormat year = new SimpleDateFormat("yyyy");
private static SimpleDateFormat month = new SimpleDateFormat("MM");
private static SimpleDateFormat day = new SimpleDateFormat("dd");
private static SimpleDateFormat hour = new SimpleDateFormat("HH");
private static SimpleDateFormat minute = new SimpleDateFormat("mm");
private static SimpleDateFormat second = new SimpleDateFormat("ss");
private static final JsRegExp formatRegex = new JsRegExp("%(?:(\\d)+\\$)?([-#+ 0,(]+)?(\\d+)?(?:\\.(\\d)+)?([bBhHsScCoxXeEfgGaAn%]|[tT][HIklMSLNpzZsQBbhAaCYyjmdeRTrDTc])", "g");
private static final JsRegExp replaceRegex = new JsRegExp("\\${(.*?)}", "g");
public static String format(final String format, final Object... args) {
int[] inc = new int[1];
return doFormat(format, (argIn, flags, width, prec, mode) -> {
if(mode.equals("%"))return "%";
int arg = argIn.isEmpty() ? inc[0] : (Integer.parseInt(argIn) - 1);
inc[0]++;
switch (mode) {
case "s":
return String.valueOf(args[arg]);
case "f":
if(!prec.isEmpty())
return fixed(((Number)args[arg]).floatValue(), Integer.parseInt(prec));
return String.valueOf(args[arg]);
case "X":
{
JsString s = Js.uncheckedCast(new JsNumber(((Number)args[arg]).intValue()).toString(16));
return s.padStart(width.isEmpty() ? 0 : Integer.parseInt(width), "0");
}
case "tY":
return year.format(new Date(((Number)args[arg]).longValue()));
case "tm":
return month.format(new Date(((Number)args[arg]).longValue()));
case "td":
return day.format(new Date(((Number)args[arg]).longValue()));
case "tH":
return hour.format(new Date(((Number)args[arg]).longValue()));
case "tM":
return minute.format(new Date(((Number)args[arg]).longValue()));
case "tS":
return second.format(new Date(((Number)args[arg]).longValue()));
default:
throw new RuntimeException("Format mode unknown: " + mode);
}
});
}
private static String doFormat(String format, FormatCallback cb) {
JsString str = Js.uncheckedCast(format);
StringEx stre = Js.uncheckedCast(str.replace(formatRegex, "$${$1:$2:$3:$4:$5}"));
return stre.replace(replaceRegex, (x, fmt) -> {
String[] sp = fmt.toString().split(":");
return cb.exec(sp[0], sp[1], sp[2], sp[3], sp[4]);
});
}
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "String")
public static class StringEx {
public native String replace(JsRegExp replaceregex, ReplaceCallback object);
}
@JsFunction
public interface ReplaceCallback {
String getReplacement(String fullText, String capture);
}
public interface FormatCallback {
String exec(String arg, String flags, String width, String prec, String mode);
}
public static String fixed(float n, int w) {
return new JsNumber(n).toFixed(w);
}
public static int parseUnsignedInt(String s, int radix)
throws NumberFormatException {
if (s == null) {
throw new NumberFormatException("null");
}
int len = s.length();
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar == '-') {
throw new
NumberFormatException(String.format("Illegal leading minus sign " +
"on unsigned string %s.", s));
} else {
if (len <= 5 || // Integer.MAX_VALUE in<SUF>
(radix == 10 && len <= 9) ) { // Integer.MAX_VALUE in base 10 is 10 digits
return Integer.parseInt(s, radix);
} else {
long ell = Long.parseLong(s, radix);
if ((ell & 0xffff_ffff_0000_0000L) == 0) {
return (int) ell;
} else {
throw new
NumberFormatException(String.format("String value %s exceeds " +
"range of unsigned int.", s));
}
}
}
} else {
throw new NumberFormatException("For input string: \"" + s + "\"");
}
}
public static InputStream getResourceAsStream(String path) {
path = path.substring(1);
String dt = Resources.getResource(path);
if(dt != null) {
return new ResourceInputStream(path, Base64.getDecoder().decode(dt));
}
System.err.println("Resource not found: " + path);
return null;
}
public static class ResourceInputStream extends ByteArrayInputStream {
public final String path;
public ResourceInputStream(String path, byte[] buf) {
super(buf);
this.path = path;
}
}
public static int toUnsignedInt(byte x) {
return (x) & 0xff;
}
public static String getQueryVariable(String key) {
if(DomGlobal.window.location.search.isEmpty())return null;
String query = DomGlobal.window.location.search.substring(1);
String[] vars = query.split("&");
for (int i = 0; i < vars.length; i++) {
String[] pair = vars[i].split("=");
if (Global.decodeURIComponent(pair[0]).equals(key)) {
return Global.decodeURIComponent(pair[1]);
}
}
return null;
}
public static void removeQueryVariable(String key) {
if(DomGlobal.window.location.search.isEmpty())return;
String newUrl = DomGlobal.window.location.protocol + "//" + DomGlobal.window.location.host + DomGlobal.window.location.pathname;
List<String> q = new ArrayList<>();
String query = DomGlobal.window.location.search.substring(1);
if(query.isEmpty())return;
String[] vars = query.split("&");
for (int i = 0; i < vars.length; i++) {
String[] pair = vars[i].split("=");
if (!Global.decodeURIComponent(pair[0]).equals(key)) {
q.add(vars[i]);
}
}
if(!q.isEmpty()) {
newUrl += q.stream().collect(Collectors.joining("&", "?", ""));
}
DomGlobal.window.history.pushState(new JsObject(), "", newUrl);
}
public static String getPlatform() {
String ua = DomGlobal.navigator.userAgent;
JsString jua = Js.uncheckedCast(ua);
JsArray<String> M = jua.match(new JsRegExp("(opera|chrome|safari|firefox|msie|trident(?=\\/))\\/?\\s*(\\d+)", "i"));
JsArray<String> tem;
if(Js.isFalsy(M))M = new JsArray<>();
if(new JsRegExp("trident", "i").test(M.getAt(1))) {
tem = new JsRegExp("\\brv[ :]+(\\d+)", "g").exec(ua);
if(Js.isFalsy(tem))tem = new JsArray<>();
String v = tem.getAt(1);
if(Js.isFalsy(v))v = "";
return "IE " + v;
}
if("Chrome".equals(M.getAt(1))) {
tem = jua.match(new JsRegExp("\\bOPR|Edge\\/(\\d+)"));
if(tem != null) { return "Opera " + tem.getAt(1); }
}
M = Js.isTruthy(M.getAt(2)) ? JsArray.of(M.getAt(1), M.getAt(2)) : JsArray.of(DomGlobal.navigator.appName, DomGlobal.navigator.appVersion, "-?");
if((tem = jua.match(new JsRegExp("version\\/(\\d+)", "i"))) != null) {M.splice(1, 1, tem.getAt(1));}
return M.getAt(0) + " " + M.getAt(1);
}
public static <T> void promiseToCf(Promise<T> pr, CompletableFuture<T> cf) {
pr.then(i -> {
cf.complete(i);
return null;
}).catch_(e -> {
cf.completeExceptionally(e instanceof Throwable ? (Throwable) e : new JavaScriptException(e));
return null;
});
}
}
|
14330_12 | // Daniel Shiffman
// The Nature of Code, Fall 2006
// Neural Network
// Class to describe the entire network
// Arrays for input neurons, hidden neurons, and output neuron
// Need to update this so that it would work with an array out outputs
// Rather silly that I didn't do this initially
// Also need to build in a "Layer" class so that there can easily
// be more than one hidden layer
package nn;
import java.util.ArrayList;
public class Network {
// Layers
InputNeuron[] input;
HiddenNeuron[] hidden;
OutputNeuron output;
public static final float LEARNING_CONSTANT = 0.5f;
// Only One output now to start!!! (i can do better, really. . .)
// Constructor makes the entire network based on number of inputs & number of neurons in hidden layer
// Only One hidden layer!!! (fix this dood)
public Network(int inputs, int hiddentotal) {
input = new InputNeuron[inputs+1]; // Got to add a bias input
hidden = new HiddenNeuron[hiddentotal+1];
// Make input neurons
for (int i = 0; i < input.length-1; i++) {
input[i] = new InputNeuron();
}
// Make hidden neurons
for (int i = 0; i < hidden.length-1; i++) {
hidden[i] = new HiddenNeuron();
}
// Make bias neurons
input[input.length-1] = new InputNeuron(1);
hidden[hidden.length-1] = new HiddenNeuron(1);
// Make output neuron
output = new OutputNeuron();
// Connect input layer to hidden layer
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < hidden.length-1; j++) {
// Create the connection object and put it in both neurons
Connection c = new Connection(input[i],hidden[j]);
input[i].addConnection(c);
hidden[j].addConnection(c);
}
}
// Connect the hidden layer to the output neuron
for (int i = 0; i < hidden.length; i++) {
Connection c = new Connection(hidden[i],output);
hidden[i].addConnection(c);
output.addConnection(c);
}
}
public float feedForward(float[] inputVals) {
// Feed the input with an array of inputs
for (int i = 0; i < inputVals.length; i++) {
input[i].input(inputVals[i]);
}
// Have the hidden layer calculate its output
for (int i = 0; i < hidden.length-1; i++) {
hidden[i].calcOutput();
}
// Calculate the output of the output neuron
output.calcOutput();
// Return output
return output.getOutput();
}
public float train(float[] inputs, float answer) {
float result = feedForward(inputs);
// This is where the error correction all starts
// Derivative of sigmoid output function * diff between known and guess
float deltaOutput = result*(1-result) * (answer-result);
// BACKPROPOGATION
// This is easier b/c we just have one output
// Apply Delta to connections between hidden and output
ArrayList connections = output.getConnections();
for (int i = 0; i < connections.size(); i++) {
Connection c = (Connection) connections.get(i);
Neuron neuron = c.getFrom();
float output = neuron.getOutput();
float deltaWeight = output*deltaOutput;
c.adjustWeight(LEARNING_CONSTANT*deltaWeight);
}
// ADJUST HIDDEN WEIGHTS
for (int i = 0; i < hidden.length; i++) {
connections = hidden[i].getConnections();
float sum = 0;
// Sum output delta * hidden layer connections (just one output)
for (int j = 0; j < connections.size(); j++) {
Connection c = (Connection) connections.get(j);
// Is this a connection from hidden layer to next layer (output)?
if (c.getFrom() == hidden[i]) {
sum += c.getWeight()*deltaOutput;
}
}
// Then adjust the weights coming in based:
// Above sum * derivative of sigmoid output function for hidden neurons
for (int j = 0; j < connections.size(); j++) {
Connection c = (Connection) connections.get(j);
// Is this a connection from previous layer (input) to hidden layer?
if (c.getTo() == hidden[i]) {
float output = hidden[i].getOutput();
float deltaHidden = output * (1 - output); // Derivative of sigmoid(x)
deltaHidden *= sum; // Would sum for all outputs if more than one output
Neuron neuron = c.getFrom();
float deltaWeight = neuron.getOutput()*deltaHidden;
c.adjustWeight(LEARNING_CONSTANT*deltaWeight);
}
}
}
return result;
}
}
| tomekwier/The-Nature-of-Code-Examples | chp10_nn/xor/code/src/Network.java | 1,367 | // Make hidden neurons | line_comment | nl | // Daniel Shiffman
// The Nature of Code, Fall 2006
// Neural Network
// Class to describe the entire network
// Arrays for input neurons, hidden neurons, and output neuron
// Need to update this so that it would work with an array out outputs
// Rather silly that I didn't do this initially
// Also need to build in a "Layer" class so that there can easily
// be more than one hidden layer
package nn;
import java.util.ArrayList;
public class Network {
// Layers
InputNeuron[] input;
HiddenNeuron[] hidden;
OutputNeuron output;
public static final float LEARNING_CONSTANT = 0.5f;
// Only One output now to start!!! (i can do better, really. . .)
// Constructor makes the entire network based on number of inputs & number of neurons in hidden layer
// Only One hidden layer!!! (fix this dood)
public Network(int inputs, int hiddentotal) {
input = new InputNeuron[inputs+1]; // Got to add a bias input
hidden = new HiddenNeuron[hiddentotal+1];
// Make input neurons
for (int i = 0; i < input.length-1; i++) {
input[i] = new InputNeuron();
}
// Make hidden<SUF>
for (int i = 0; i < hidden.length-1; i++) {
hidden[i] = new HiddenNeuron();
}
// Make bias neurons
input[input.length-1] = new InputNeuron(1);
hidden[hidden.length-1] = new HiddenNeuron(1);
// Make output neuron
output = new OutputNeuron();
// Connect input layer to hidden layer
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < hidden.length-1; j++) {
// Create the connection object and put it in both neurons
Connection c = new Connection(input[i],hidden[j]);
input[i].addConnection(c);
hidden[j].addConnection(c);
}
}
// Connect the hidden layer to the output neuron
for (int i = 0; i < hidden.length; i++) {
Connection c = new Connection(hidden[i],output);
hidden[i].addConnection(c);
output.addConnection(c);
}
}
public float feedForward(float[] inputVals) {
// Feed the input with an array of inputs
for (int i = 0; i < inputVals.length; i++) {
input[i].input(inputVals[i]);
}
// Have the hidden layer calculate its output
for (int i = 0; i < hidden.length-1; i++) {
hidden[i].calcOutput();
}
// Calculate the output of the output neuron
output.calcOutput();
// Return output
return output.getOutput();
}
public float train(float[] inputs, float answer) {
float result = feedForward(inputs);
// This is where the error correction all starts
// Derivative of sigmoid output function * diff between known and guess
float deltaOutput = result*(1-result) * (answer-result);
// BACKPROPOGATION
// This is easier b/c we just have one output
// Apply Delta to connections between hidden and output
ArrayList connections = output.getConnections();
for (int i = 0; i < connections.size(); i++) {
Connection c = (Connection) connections.get(i);
Neuron neuron = c.getFrom();
float output = neuron.getOutput();
float deltaWeight = output*deltaOutput;
c.adjustWeight(LEARNING_CONSTANT*deltaWeight);
}
// ADJUST HIDDEN WEIGHTS
for (int i = 0; i < hidden.length; i++) {
connections = hidden[i].getConnections();
float sum = 0;
// Sum output delta * hidden layer connections (just one output)
for (int j = 0; j < connections.size(); j++) {
Connection c = (Connection) connections.get(j);
// Is this a connection from hidden layer to next layer (output)?
if (c.getFrom() == hidden[i]) {
sum += c.getWeight()*deltaOutput;
}
}
// Then adjust the weights coming in based:
// Above sum * derivative of sigmoid output function for hidden neurons
for (int j = 0; j < connections.size(); j++) {
Connection c = (Connection) connections.get(j);
// Is this a connection from previous layer (input) to hidden layer?
if (c.getTo() == hidden[i]) {
float output = hidden[i].getOutput();
float deltaHidden = output * (1 - output); // Derivative of sigmoid(x)
deltaHidden *= sum; // Would sum for all outputs if more than one output
Neuron neuron = c.getFrom();
float deltaWeight = neuron.getOutput()*deltaHidden;
c.adjustWeight(LEARNING_CONSTANT*deltaWeight);
}
}
}
return result;
}
}
|
131463_4 | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR 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.
******************************************************************************/
package org.jbox2d.collision;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Rot;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Transform;
import org.jbox2d.common.Vec2;
/** This is used to compute the current state of a contact manifold.
*
* @author daniel */
public class WorldManifold {
/** World vector pointing from A to B */
public final Vec2 normal;
/** World contact point (point of intersection) */
public final Vec2[] points;
/** A negative value indicates overlap, in meters. */
public final float[] separations;
public WorldManifold () {
normal = new Vec2();
points = new Vec2[Settings.maxManifoldPoints];
separations = new float[Settings.maxManifoldPoints];
for (int i = 0; i < Settings.maxManifoldPoints; i++) {
points[i] = new Vec2();
}
}
private final Vec2 pool3 = new Vec2();
private final Vec2 pool4 = new Vec2();
public final void initialize (final Manifold manifold, final Transform xfA, float radiusA, final Transform xfB,
float radiusB) {
if (manifold.pointCount == 0) {
return;
}
switch (manifold.type) {
case CIRCLES: {
final Vec2 pointA = pool3;
final Vec2 pointB = pool4;
normal.x = 1;
normal.y = 0;
Vec2 v = manifold.localPoint;
// Transform.mulToOutUnsafe(xfA, manifold.localPoint, pointA);
// Transform.mulToOutUnsafe(xfB, manifold.points[0].localPoint, pointB);
pointA.x = (xfA.q.c * v.x - xfA.q.s * v.y) + xfA.p.x;
pointA.y = (xfA.q.s * v.x + xfA.q.c * v.y) + xfA.p.y;
Vec2 mp0p = manifold.points[0].localPoint;
pointB.x = (xfB.q.c * mp0p.x - xfB.q.s * mp0p.y) + xfB.p.x;
pointB.y = (xfB.q.s * mp0p.x + xfB.q.c * mp0p.y) + xfB.p.y;
if (MathUtils.distanceSquared(pointA, pointB) > Settings.EPSILON * Settings.EPSILON) {
normal.x = pointB.x - pointA.x;
normal.y = pointB.y - pointA.y;
normal.normalize();
}
final float cAx = normal.x * radiusA + pointA.x;
final float cAy = normal.y * radiusA + pointA.y;
final float cBx = -normal.x * radiusB + pointB.x;
final float cBy = -normal.y * radiusB + pointB.y;
points[0].x = (cAx + cBx) * .5f;
points[0].y = (cAy + cBy) * .5f;
separations[0] = (cBx - cAx) * normal.x + (cBy - cAy) * normal.y;
}
break;
case FACE_A: {
final Vec2 planePoint = pool3;
Rot.mulToOutUnsafe(xfA.q, manifold.localNormal, normal);
Transform.mulToOut(xfA, manifold.localPoint, planePoint);
final Vec2 clipPoint = pool4;
for (int i = 0; i < manifold.pointCount; i++) {
// b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint);
// b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint,
// normal)) * normal;
// b2Vec2 cB = clipPoint - radiusB * normal;
// points[i] = 0.5f * (cA + cB);
Transform.mulToOut(xfB, manifold.points[i].localPoint, clipPoint);
// use cA as temporary for now
// cA.set(clipPoint).subLocal(planePoint);
// float scalar = radiusA - Vec2.dot(cA, normal);
// cA.set(normal).mulLocal(scalar).addLocal(clipPoint);
// cB.set(normal).mulLocal(radiusB).subLocal(clipPoint).negateLocal();
// points[i].set(cA).addLocal(cB).mulLocal(0.5f);
final float scalar = radiusA - ((clipPoint.x - planePoint.x) * normal.x + (clipPoint.y - planePoint.y) * normal.y);
final float cAx = normal.x * scalar + clipPoint.x;
final float cAy = normal.y * scalar + clipPoint.y;
final float cBx = -normal.x * radiusB + clipPoint.x;
final float cBy = -normal.y * radiusB + clipPoint.y;
points[i].x = (cAx + cBx) * .5f;
points[i].y = (cAy + cBy) * .5f;
separations[i] = (cBx - cAx) * normal.x + (cBy - cAy) * normal.y;
}
}
break;
case FACE_B:
final Vec2 planePoint = pool3;
Rot.mulToOutUnsafe(xfB.q, manifold.localNormal, normal);
Transform.mulToOut(xfB, manifold.localPoint, planePoint);
// final Mat22 R = xfB.q;
// normal.x = R.ex.x * manifold.localNormal.x + R.ey.x * manifold.localNormal.y;
// normal.y = R.ex.y * manifold.localNormal.x + R.ey.y * manifold.localNormal.y;
// final Vec2 v = manifold.localPoint;
// planePoint.x = xfB.p.x + xfB.q.ex.x * v.x + xfB.q.ey.x * v.y;
// planePoint.y = xfB.p.y + xfB.q.ex.y * v.x + xfB.q.ey.y * v.y;
final Vec2 clipPoint = pool4;
for (int i = 0; i < manifold.pointCount; i++) {
// b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint);
// b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint,
// normal)) * normal;
// b2Vec2 cA = clipPoint - radiusA * normal;
// points[i] = 0.5f * (cA + cB);
Transform.mulToOut(xfA, manifold.points[i].localPoint, clipPoint);
// cB.set(clipPoint).subLocal(planePoint);
// float scalar = radiusB - Vec2.dot(cB, normal);
// cB.set(normal).mulLocal(scalar).addLocal(clipPoint);
// cA.set(normal).mulLocal(radiusA).subLocal(clipPoint).negateLocal();
// points[i].set(cA).addLocal(cB).mulLocal(0.5f);
// points[i] = 0.5f * (cA + cB);
//
// clipPoint.x = xfA.p.x + xfA.q.ex.x * manifold.points[i].localPoint.x + xfA.q.ey.x *
// manifold.points[i].localPoint.y;
// clipPoint.y = xfA.p.y + xfA.q.ex.y * manifold.points[i].localPoint.x + xfA.q.ey.y *
// manifold.points[i].localPoint.y;
final float scalar = radiusB - ((clipPoint.x - planePoint.x) * normal.x + (clipPoint.y - planePoint.y) * normal.y);
final float cBx = normal.x * scalar + clipPoint.x;
final float cBy = normal.y * scalar + clipPoint.y;
final float cAx = -normal.x * radiusA + clipPoint.x;
final float cAy = -normal.y * radiusA + clipPoint.y;
points[i].x = (cAx + cBx) * .5f;
points[i].y = (cAy + cBy) * .5f;
separations[i] = (cAx - cBx) * normal.x + (cAy - cBy) * normal.y;
}
// Ensure normal points from A to B.
normal.x = -normal.x;
normal.y = -normal.y;
break;
}
}
}
| tommyettinger/libgdx | extensions/gdx-box2d/gdx-box2d-gwt/src/com/badlogic/gdx/physics/box2d/gwt/emu/org/jbox2d/collision/WorldManifold.java | 2,823 | /** A negative value indicates overlap, in meters. */ | block_comment | nl | /*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR 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.
******************************************************************************/
package org.jbox2d.collision;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Rot;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Transform;
import org.jbox2d.common.Vec2;
/** This is used to compute the current state of a contact manifold.
*
* @author daniel */
public class WorldManifold {
/** World vector pointing from A to B */
public final Vec2 normal;
/** World contact point (point of intersection) */
public final Vec2[] points;
/** A negative value<SUF>*/
public final float[] separations;
public WorldManifold () {
normal = new Vec2();
points = new Vec2[Settings.maxManifoldPoints];
separations = new float[Settings.maxManifoldPoints];
for (int i = 0; i < Settings.maxManifoldPoints; i++) {
points[i] = new Vec2();
}
}
private final Vec2 pool3 = new Vec2();
private final Vec2 pool4 = new Vec2();
public final void initialize (final Manifold manifold, final Transform xfA, float radiusA, final Transform xfB,
float radiusB) {
if (manifold.pointCount == 0) {
return;
}
switch (manifold.type) {
case CIRCLES: {
final Vec2 pointA = pool3;
final Vec2 pointB = pool4;
normal.x = 1;
normal.y = 0;
Vec2 v = manifold.localPoint;
// Transform.mulToOutUnsafe(xfA, manifold.localPoint, pointA);
// Transform.mulToOutUnsafe(xfB, manifold.points[0].localPoint, pointB);
pointA.x = (xfA.q.c * v.x - xfA.q.s * v.y) + xfA.p.x;
pointA.y = (xfA.q.s * v.x + xfA.q.c * v.y) + xfA.p.y;
Vec2 mp0p = manifold.points[0].localPoint;
pointB.x = (xfB.q.c * mp0p.x - xfB.q.s * mp0p.y) + xfB.p.x;
pointB.y = (xfB.q.s * mp0p.x + xfB.q.c * mp0p.y) + xfB.p.y;
if (MathUtils.distanceSquared(pointA, pointB) > Settings.EPSILON * Settings.EPSILON) {
normal.x = pointB.x - pointA.x;
normal.y = pointB.y - pointA.y;
normal.normalize();
}
final float cAx = normal.x * radiusA + pointA.x;
final float cAy = normal.y * radiusA + pointA.y;
final float cBx = -normal.x * radiusB + pointB.x;
final float cBy = -normal.y * radiusB + pointB.y;
points[0].x = (cAx + cBx) * .5f;
points[0].y = (cAy + cBy) * .5f;
separations[0] = (cBx - cAx) * normal.x + (cBy - cAy) * normal.y;
}
break;
case FACE_A: {
final Vec2 planePoint = pool3;
Rot.mulToOutUnsafe(xfA.q, manifold.localNormal, normal);
Transform.mulToOut(xfA, manifold.localPoint, planePoint);
final Vec2 clipPoint = pool4;
for (int i = 0; i < manifold.pointCount; i++) {
// b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint);
// b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint,
// normal)) * normal;
// b2Vec2 cB = clipPoint - radiusB * normal;
// points[i] = 0.5f * (cA + cB);
Transform.mulToOut(xfB, manifold.points[i].localPoint, clipPoint);
// use cA as temporary for now
// cA.set(clipPoint).subLocal(planePoint);
// float scalar = radiusA - Vec2.dot(cA, normal);
// cA.set(normal).mulLocal(scalar).addLocal(clipPoint);
// cB.set(normal).mulLocal(radiusB).subLocal(clipPoint).negateLocal();
// points[i].set(cA).addLocal(cB).mulLocal(0.5f);
final float scalar = radiusA - ((clipPoint.x - planePoint.x) * normal.x + (clipPoint.y - planePoint.y) * normal.y);
final float cAx = normal.x * scalar + clipPoint.x;
final float cAy = normal.y * scalar + clipPoint.y;
final float cBx = -normal.x * radiusB + clipPoint.x;
final float cBy = -normal.y * radiusB + clipPoint.y;
points[i].x = (cAx + cBx) * .5f;
points[i].y = (cAy + cBy) * .5f;
separations[i] = (cBx - cAx) * normal.x + (cBy - cAy) * normal.y;
}
}
break;
case FACE_B:
final Vec2 planePoint = pool3;
Rot.mulToOutUnsafe(xfB.q, manifold.localNormal, normal);
Transform.mulToOut(xfB, manifold.localPoint, planePoint);
// final Mat22 R = xfB.q;
// normal.x = R.ex.x * manifold.localNormal.x + R.ey.x * manifold.localNormal.y;
// normal.y = R.ex.y * manifold.localNormal.x + R.ey.y * manifold.localNormal.y;
// final Vec2 v = manifold.localPoint;
// planePoint.x = xfB.p.x + xfB.q.ex.x * v.x + xfB.q.ey.x * v.y;
// planePoint.y = xfB.p.y + xfB.q.ex.y * v.x + xfB.q.ey.y * v.y;
final Vec2 clipPoint = pool4;
for (int i = 0; i < manifold.pointCount; i++) {
// b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint);
// b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint,
// normal)) * normal;
// b2Vec2 cA = clipPoint - radiusA * normal;
// points[i] = 0.5f * (cA + cB);
Transform.mulToOut(xfA, manifold.points[i].localPoint, clipPoint);
// cB.set(clipPoint).subLocal(planePoint);
// float scalar = radiusB - Vec2.dot(cB, normal);
// cB.set(normal).mulLocal(scalar).addLocal(clipPoint);
// cA.set(normal).mulLocal(radiusA).subLocal(clipPoint).negateLocal();
// points[i].set(cA).addLocal(cB).mulLocal(0.5f);
// points[i] = 0.5f * (cA + cB);
//
// clipPoint.x = xfA.p.x + xfA.q.ex.x * manifold.points[i].localPoint.x + xfA.q.ey.x *
// manifold.points[i].localPoint.y;
// clipPoint.y = xfA.p.y + xfA.q.ex.y * manifold.points[i].localPoint.x + xfA.q.ey.y *
// manifold.points[i].localPoint.y;
final float scalar = radiusB - ((clipPoint.x - planePoint.x) * normal.x + (clipPoint.y - planePoint.y) * normal.y);
final float cBx = normal.x * scalar + clipPoint.x;
final float cBy = normal.y * scalar + clipPoint.y;
final float cAx = -normal.x * radiusA + clipPoint.x;
final float cAy = -normal.y * radiusA + clipPoint.y;
points[i].x = (cAx + cBx) * .5f;
points[i].y = (cAy + cBy) * .5f;
separations[i] = (cAx - cBx) * normal.x + (cAy - cBy) * normal.y;
}
// Ensure normal points from A to B.
normal.x = -normal.x;
normal.y = -normal.y;
break;
}
}
}
|
50068_40 | /**
* Copyright 2009 Tilburg University. All rights reserved.
*
* This file is part of Presto.
*
* Presto 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.
*
* Presto 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 Presto. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jeroenjanssens.presto.sailing;
import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.geom.LatLon;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.globes.Earth;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import com.jeroenjanssens.presto.model.BezierVertex;
import com.jeroenjanssens.presto.model.Track;
import com.jeroenjanssens.presto.model.Waypoint;
/**
* @author Jeroen Janssens
* @created June 6, 2009
*/
public class TrackTools {
public static double KNOT_TO_MS = 0.514444444;
public static synchronized ArrayList<BezierVertex> recalculateVertices(Waypoint waypoint, Position endPosition) {
//waypoint.getVertices().clear();
ArrayList<BezierVertex> vertices = new ArrayList<BezierVertex>();
//Waypoint nextWaypoint = waypoint.getTrack().getNextWaypoint(waypoint);
//the begin and end control points
Position posA = waypoint.getPosition();
Position posD = endPosition;
//Determine the second and third control point
Angle segmentAzimuth = null;
Angle segmentDistance = LatLon.greatCircleDistance(posA.getLatLon(), posD.getLatLon());
LatLon posB, posC = null;
if(waypoint.isFirst()) {
//posB is heel klein en in het verlengde van de hemelsbrede lijn
segmentAzimuth = LatLon.greatCircleAzimuth(posA.getLatLon(), posD.getLatLon());
segmentDistance = LatLon.greatCircleDistance(posA.getLatLon(), posD.getLatLon());
posB = LatLon.greatCircleEndPosition(posA.getLatLon(), segmentAzimuth, Angle.fromDegrees(0.000001));
} else {
//posB haaks enzo
Waypoint previousWaypoint = waypoint.getTrack().getPreviousWaypoint(waypoint);
Angle aCwNw = LatLon.greatCircleAzimuth(posA.getLatLon(), posD.getLatLon());
Angle aCwPw = LatLon.greatCircleAzimuth(posA.getLatLon(), previousWaypoint.getPosition().getLatLon());
Angle sum = aCwNw.subtract(aCwPw);
Angle handle;
double d = sum.degrees;
if(d < -180) {
//System.out.println("(1) d < -180");
handle = aCwNw.addDegrees((Math.abs(d)-180)/2);
} else if(d < 0) {
//System.out.println("(2) -180 > d < 0");
handle = aCwNw.subtractDegrees((180-Math.abs(d))/2);
//handle = aCwNw.subtractDegrees(((360-d)-180)/2);
} else if(d < 180) {
//System.out.println("(3) 0 > d < 180");
handle = aCwNw.addDegrees(((360-d)-180)/2);
} else {
//System.out.println("(4) d >= 180");
handle = aCwNw.subtractDegrees((d-180)/2);
}
//System.out.println("The corner is: " + d);
posB = LatLon.greatCircleEndPosition(posA.getLatLon(), handle, Angle.fromDegrees(waypoint.getAngle()+0.000001));
}
//posC is heel klein en in het verlengde van de hemelsbrede lijn
segmentAzimuth = LatLon.greatCircleAzimuth(posD.getLatLon(), posA.getLatLon());
segmentDistance = LatLon.greatCircleDistance(posD.getLatLon(), posA.getLatLon());
posC = LatLon.greatCircleEndPosition(posD.getLatLon(), segmentAzimuth, Angle.fromDegrees(0.001));
BezierVertex vecA = geodeticToCartesian(posA.getLatLon(), 200);
BezierVertex vecB = geodeticToCartesian(posB, 200);
BezierVertex vecC = geodeticToCartesian(posC, 200);
BezierVertex vecD = geodeticToCartesian(posD.getLatLon(), 200);
double x, y, z;
double k = segmentDistance.degrees / 0.005;
if (k > 200) k = 200;
if (k < 20) k = 20;
k = 1 / k;
for(double t=0;t<1;t+=k){
x=(vecA.x+t*(-vecA.x*3+t*(3*vecA.x-vecA.x*t)))+t*(3*vecB.x+t*(-6*vecB.x+vecB.x*3*t))+t*t*(vecC.x*3-vecC.x*3*t)+vecD.x*t*t*t;
y=(vecA.y+t*(-vecA.y*3+t*(3*vecA.y-vecA.y*t)))+t*(3*vecB.y+t*(-6*vecB.y+vecB.y*3*t))+t*t*(vecC.y*3-vecC.y*3*t)+vecD.y*t*t*t;
z=(vecA.z+t*(-vecA.z*3+t*(3*vecA.z-vecA.z*t)))+t*(3*vecB.z+t*(-6*vecB.z+vecB.z*3*t))+t*t*(vecC.z*3-vecC.z*3*t)+vecD.z*t*t*t;
vertices.add(cartesianToGeodetic(x, y, z));
}
return vertices;
}
public static void recalculateVertices(Track track) {
//kan nog wat sneller door meteen latlon te nemen van PosA en PosD
track.setStatus(TrackStatus.DIRTY_VERTICES_AND_DIRTY_TIMES);
double t;
for(Waypoint waypoint : track.getWaypoints()) {
waypoint.getVertices().clear();
if(waypoint.isLast()) {
waypoint.getVertices().add(geodeticToCartesian(waypoint.getPosition().getLatLon(), 100));
waypoint.setTotalDistance(0);
} else {
Waypoint nextWaypoint = waypoint.getTrack().getNextWaypoint(waypoint);
//the begin and end control points
Position posA = waypoint.getPosition();
Position posD = nextWaypoint.getPosition();
//Determine the second and third control point
Angle segmentAzimuth = null;
Angle segmentDistance = LatLon.greatCircleDistance(posA.getLatLon(), posD.getLatLon());
LatLon posB, posC = null;
if(waypoint.isFirst()) {
//posB is heel klein en in het verlengde van de hemelsbrede lijn
segmentAzimuth = LatLon.greatCircleAzimuth(posA.getLatLon(), posD.getLatLon());
segmentDistance = LatLon.greatCircleDistance(posA.getLatLon(), posD.getLatLon());
posB = LatLon.greatCircleEndPosition(posA.getLatLon(), segmentAzimuth, Angle.fromDegrees(0.000001));
} else {
//posB haaks enzo
Waypoint previousWaypoint = waypoint.getTrack().getPreviousWaypoint(waypoint);
Angle aCwNw = LatLon.greatCircleAzimuth(posA.getLatLon(), posD.getLatLon());
Angle aCwPw = LatLon.greatCircleAzimuth(posA.getLatLon(), previousWaypoint.getPosition().getLatLon());
Angle sum = aCwNw.subtract(aCwPw);
Angle handle;
double d = sum.degrees;
if(d < -180) {
//System.out.println("(1) d < -180");
handle = aCwNw.addDegrees((Math.abs(d)-180)/2);
} else if(d < 0) {
//System.out.println("(2) -180 > d < 0");
handle = aCwNw.subtractDegrees((180-Math.abs(d))/2);
//handle = aCwNw.subtractDegrees(((360-d)-180)/2);
} else if(d < 180) {
//System.out.println("(3) 0 > d < 180");
handle = aCwNw.addDegrees(((360-d)-180)/2);
} else {
//System.out.println("(4) d >= 180");
handle = aCwNw.subtractDegrees((d-180)/2);
}
//System.out.println("The corner is: " + d);
posB = LatLon.greatCircleEndPosition(posA.getLatLon(), handle, Angle.fromDegrees(waypoint.getAngle()+0.000001));
}
if(nextWaypoint.isLast()) {
//posC is heel klein en in het verlengde van de hemelsbrede lijn
segmentAzimuth = LatLon.greatCircleAzimuth(posD.getLatLon(), posA.getLatLon());
segmentDistance = LatLon.greatCircleDistance(posD.getLatLon(), posA.getLatLon());
posC = LatLon.greatCircleEndPosition(posD.getLatLon(), segmentAzimuth, Angle.fromDegrees(0.001));
} else {
//posC haaks enzo
Waypoint secondNextWaypoint = nextWaypoint.getTrack().getNextWaypoint(nextWaypoint);
Angle aNwSw = LatLon.greatCircleAzimuth(posD.getLatLon(), secondNextWaypoint.getPosition().getLatLon());
Angle aNwCw = LatLon.greatCircleAzimuth(posD.getLatLon(), posA.getLatLon());
Angle sum = aNwCw.subtract(aNwSw);
Angle handle;
double d = sum.degrees;
if(d < -180) {
//System.out.println("(1) d < -180");
handle = aNwCw.addDegrees((Math.abs(d)-180)/2);
} else if(d < 0) {
//System.out.println("(2) -180 > d < 0");
handle = aNwCw.subtractDegrees((180-Math.abs(d))/2);
} else if(d < 180) {
//System.out.println("(3) 0 > d < 180");
handle = aNwCw.addDegrees(((360-d)-180)/2);
} else {
//System.out.println("(4) d >= 180");
handle = aNwCw.subtractDegrees((d-180)/2);
}
//System.out.println("The corner is: " + d);
posC = LatLon.greatCircleEndPosition(posD.getLatLon(), handle, Angle.fromDegrees(nextWaypoint.getAngle()+0.001));
}
BezierVertex vecA = geodeticToCartesian(posA.getLatLon(), 100);
BezierVertex vecB = geodeticToCartesian(posB, 100);
BezierVertex vecC = geodeticToCartesian(posC, 100);
BezierVertex vecD = geodeticToCartesian(posD.getLatLon(), 100);
double x, y, z;
double k = segmentDistance.degrees / 0.005;
if (k > 200) k = 200;
if (k < 20) k = 20;
k = 1 / k;
waypoint.getVertices().add(geodeticToCartesian(waypoint.getPosition().getLatLon(), 100));
for(t=0;t<=1;t+=k){
x=(vecA.x+t*(-vecA.x*3+t*(3*vecA.x-vecA.x*t)))+t*(3*vecB.x+t*(-6*vecB.x+vecB.x*3*t))+t*t*(vecC.x*3-vecC.x*3*t)+vecD.x*t*t*t;
y=(vecA.y+t*(-vecA.y*3+t*(3*vecA.y-vecA.y*t)))+t*(3*vecB.y+t*(-6*vecB.y+vecB.y*3*t))+t*t*(vecC.y*3-vecC.y*3*t)+vecD.y*t*t*t;
z=(vecA.z+t*(-vecA.z*3+t*(3*vecA.z-vecA.z*t)))+t*(3*vecB.z+t*(-6*vecB.z+vecB.z*3*t))+t*t*(vecC.z*3-vecC.z*3*t)+vecD.z*t*t*t;
waypoint.getVertices().add(cartesianToGeodetic(x, y, z));
}
waypoint.getVertices().add(geodeticToCartesian(nextWaypoint.getPosition().getLatLon(), 100));
CopyOnWriteArrayList<BezierVertex> vertices = waypoint.getVertices();
double totalDistance = 0;
for(int i = 0; i < vertices.size()-1; i++) {
LatLon l1 = LatLon.fromDegrees(vertices.get(i).latitude, vertices.get(i).longitude);
LatLon l2 = LatLon.fromDegrees(vertices.get(i+1).latitude, vertices.get(i+1).longitude);
double totalVertexDistance = LatLon.ellipsoidalDistance(l1, l2, Earth.WGS84_EQUATORIAL_RADIUS, Earth.WGS84_POLAR_RADIUS);
if(Double.isNaN(totalVertexDistance)) totalVertexDistance = 0;
vertices.get(i).distanceToNextVertex = totalVertexDistance;
totalDistance += totalVertexDistance;
}
waypoint.setTotalDistance(totalDistance);
}
}
track.setStatus(TrackStatus.CLEAN_VERTICES_AND_DIRTY_TIMES);
}
private static BezierVertex cartesianToGeodetic(double myx, double myy, double myz) {
double ra2 = 1 / (Earth.WGS84_EQUATORIAL_RADIUS * Earth.WGS84_EQUATORIAL_RADIUS);
double X = myz;
double Y = myx;
double Z = myy;
double e2 = Earth.WGS84_ES;
double e4 = e2 * e2;
double XXpYY = X * X + Y * Y;
double sqrtXXpYY = Math.sqrt(XXpYY);
double p = XXpYY * ra2;
double q = Z * Z * (1 - e2) * ra2;
double r = 1 / 6.0 * (p + q - e4);
double s = e4 * p * q / (4 * r * r * r);
double t = Math.pow(1 + s + Math.sqrt(s * (2 + s)), 1 / 3.0);
double u = r * (1 + t + 1 / t);
double v = Math.sqrt(u * u + e4 * q);
double w = e2 * (u + v - q) / (2 * v);
double k = Math.sqrt(u + v + w * w) - w;
double D = k * sqrtXXpYY / (k + e2);
double lon = 2 * Math.atan2(Y, X + sqrtXXpYY);
double sqrtDDpZZ = Math.sqrt(D * D + Z * Z);
double lat = 2 * Math.atan2(Z, D + sqrtDDpZZ);
//double elevation = (k + e2 - 1) * sqrtDDpZZ / k;
return geodeticToCartesian(LatLon.fromRadians(lat, lon), 100);
}
private static LatLon bezierVertexToLatLon(BezierVertex vertex) {
double ra2 = 1 / (Earth.WGS84_EQUATORIAL_RADIUS * Earth.WGS84_EQUATORIAL_RADIUS);
double X = vertex.z;
double Y = vertex.x;
double Z = vertex.y;
double e2 = Earth.WGS84_ES;
double e4 = e2 * e2;
double XXpYY = X * X + Y * Y;
double sqrtXXpYY = Math.sqrt(XXpYY);
double p = XXpYY * ra2;
double q = Z * Z * (1 - e2) * ra2;
double r = 1 / 6.0 * (p + q - e4);
double s = e4 * p * q / (4 * r * r * r);
double t = Math.pow(1 + s + Math.sqrt(s * (2 + s)), 1 / 3.0);
double u = r * (1 + t + 1 / t);
double v = Math.sqrt(u * u + e4 * q);
double w = e2 * (u + v - q) / (2 * v);
double k = Math.sqrt(u + v + w * w) - w;
double D = k * sqrtXXpYY / (k + e2);
double lon = 2 * Math.atan2(Y, X + sqrtXXpYY);
double sqrtDDpZZ = Math.sqrt(D * D + Z * Z);
double lat = 2 * Math.atan2(Z, D + sqrtDDpZZ);
//double elevation = (k + e2 - 1) * sqrtDDpZZ / k;
return LatLon.fromRadians(lat, lon);
}
public static BezierVertex geodeticToCartesian(LatLon latLon, double metersElevation) {
double cosLat = Math.cos(latLon.getLatitude().radians);
double sinLat = Math.sin(latLon.getLatitude().radians);
double cosLon = Math.cos(latLon.getLongitude().radians);
double sinLon = Math.sin(latLon.getLongitude().radians);
double rpm = Earth.WGS84_EQUATORIAL_RADIUS / Math.sqrt(1.0 - Earth.WGS84_ES * sinLat * sinLat);
double x = (rpm + metersElevation) * cosLat * sinLon;
double y = (rpm * (1.0 - Earth.WGS84_ES) + metersElevation) * sinLat;
double z = (rpm + metersElevation) * cosLat * cosLon;
BezierVertex v = new BezierVertex(x, y, z);
v.latitude = latLon.getLatitude().degrees;
v.longitude = latLon.getLongitude().degrees;
return v;
}
public static Position getInsertPosition(Track track, Position p, boolean insert) {
if(track == null) return null;
if(p == null) return null;
BezierVertex vi = geodeticToCartesian(p.getLatLon(), 100);
double bestDifference = 1000000;
BezierVertex bestBezierVertex1 = null;
BezierVertex bestBezierVertex2 = null;
Waypoint bestWaypoint = null;
for(int j = 0; j < track.getWaypoints().size()-1; j++) {
Waypoint waypoint = track.getWaypoint(j);
for(int i = 0; i < waypoint.getVertices().size()-1; i++) {
BezierVertex v1 = waypoint.getBezierVertex(i);
BezierVertex v2 = waypoint.getBezierVertex(i+1);
double distance1 = distanceBetweenBezierVertices(v1, v2);
double distance2 = distanceBetweenBezierVertices(v1, vi) + distanceBetweenBezierVertices(vi, v2);
double difference = distance2 - distance1;
if(difference < bestDifference) {
//System.out.println("bestDifference: " + )
bestBezierVertex1 = v1;
bestBezierVertex2 = v2;
bestWaypoint = waypoint;
bestDifference = difference;
}
}
}
if(bestBezierVertex1 == null) return null;
if(bestBezierVertex2 == null) return null;
if(bestWaypoint == null) return null;
//System.out.println("bestWaypoint: " + bestWaypoint.getId());
int bestIndex = bestWaypoint.getId();
//Compute the location of the new vertex on the line
//In order to keep the line straight
//The two positions of the old segment
LatLon a = bezierVertexToLatLon(bestBezierVertex1);
LatLon e = bezierVertexToLatLon(bestBezierVertex2);
//The clicked position
LatLon b = p.getLatLon();
//Compute angels between them
//Angle azAB = LatLon.rhumbAzimuth(a, b);
//Angle azAE = LatLon.rhumbAzimuth(a, e);
Angle azAB = LatLon.greatCircleAzimuth(a, b);
Angle azAE = LatLon.greatCircleAzimuth(a, e);
Angle diffABAE = azAB.subtract(azAE);
//Compute the position opposite to b
//Angle dis = LatLon.rhumbDistance(a, b);
//LatLon c = LatLon.rhumbEndPosition(a, (azAB.subtract(diffABAE)).subtract(diffABAE), dis);
Angle dis = LatLon.greatCircleDistance(a, b);
LatLon c = LatLon.greatCircleEndPosition(a, (azAB.subtract(diffABAE)).subtract(diffABAE), dis);
//Get the point that is in between them
LatLon d = LatLon.interpolate(0.5, b, c);
//Insert the vertex at the appropirate location
Position insertPosition = Position.fromDegrees(d.getLatitude().degrees, d.getLongitude().degrees, 100);
if(insert) {
track.addWaypoint(bestIndex+1, new Waypoint(track, d.getLatitude().degrees, d.getLongitude().degrees, bestWaypoint.getSpeed(), bestWaypoint.getAngle()));
}
return insertPosition;
}
public static double distanceBetweenBezierVertices(BezierVertex v1, BezierVertex v2) {
double tmp;
double result = 0.0;
tmp = v1.x - v2.x;
result += tmp * tmp;
tmp = v1.y - v2.y;
result += tmp * tmp;
tmp = v1.z - v2.z;
result += tmp * tmp;
return result;
}
public static String colorToHex(Color color) {
String r = Integer.toHexString(color.getRed());
String g = Integer.toHexString(color.getGreen());
String b = Integer.toHexString(color.getBlue());
if(r.length() < 2) r = "0" + r;
if(g.length() < 2) g = "0" + g;
if(b.length() < 2) b = "0" + b;
return "#" + r + g + b;
}
public static Color hexToColor(String hex) {
int r = Integer.parseInt(hex.substring(1, 3), 16);
int g = Integer.parseInt(hex.substring(3, 5), 16);
int b = Integer.parseInt(hex.substring(5, 7), 16);
return new Color(Display.getDefault(), r, g, b);
}
}
| tomregelink/presto | src/com/jeroenjanssens/presto/sailing/TrackTools.java | 7,107 | //Compute angels between them
| line_comment | nl | /**
* Copyright 2009 Tilburg University. All rights reserved.
*
* This file is part of Presto.
*
* Presto 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.
*
* Presto 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 Presto. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jeroenjanssens.presto.sailing;
import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.geom.LatLon;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.globes.Earth;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import com.jeroenjanssens.presto.model.BezierVertex;
import com.jeroenjanssens.presto.model.Track;
import com.jeroenjanssens.presto.model.Waypoint;
/**
* @author Jeroen Janssens
* @created June 6, 2009
*/
public class TrackTools {
public static double KNOT_TO_MS = 0.514444444;
public static synchronized ArrayList<BezierVertex> recalculateVertices(Waypoint waypoint, Position endPosition) {
//waypoint.getVertices().clear();
ArrayList<BezierVertex> vertices = new ArrayList<BezierVertex>();
//Waypoint nextWaypoint = waypoint.getTrack().getNextWaypoint(waypoint);
//the begin and end control points
Position posA = waypoint.getPosition();
Position posD = endPosition;
//Determine the second and third control point
Angle segmentAzimuth = null;
Angle segmentDistance = LatLon.greatCircleDistance(posA.getLatLon(), posD.getLatLon());
LatLon posB, posC = null;
if(waypoint.isFirst()) {
//posB is heel klein en in het verlengde van de hemelsbrede lijn
segmentAzimuth = LatLon.greatCircleAzimuth(posA.getLatLon(), posD.getLatLon());
segmentDistance = LatLon.greatCircleDistance(posA.getLatLon(), posD.getLatLon());
posB = LatLon.greatCircleEndPosition(posA.getLatLon(), segmentAzimuth, Angle.fromDegrees(0.000001));
} else {
//posB haaks enzo
Waypoint previousWaypoint = waypoint.getTrack().getPreviousWaypoint(waypoint);
Angle aCwNw = LatLon.greatCircleAzimuth(posA.getLatLon(), posD.getLatLon());
Angle aCwPw = LatLon.greatCircleAzimuth(posA.getLatLon(), previousWaypoint.getPosition().getLatLon());
Angle sum = aCwNw.subtract(aCwPw);
Angle handle;
double d = sum.degrees;
if(d < -180) {
//System.out.println("(1) d < -180");
handle = aCwNw.addDegrees((Math.abs(d)-180)/2);
} else if(d < 0) {
//System.out.println("(2) -180 > d < 0");
handle = aCwNw.subtractDegrees((180-Math.abs(d))/2);
//handle = aCwNw.subtractDegrees(((360-d)-180)/2);
} else if(d < 180) {
//System.out.println("(3) 0 > d < 180");
handle = aCwNw.addDegrees(((360-d)-180)/2);
} else {
//System.out.println("(4) d >= 180");
handle = aCwNw.subtractDegrees((d-180)/2);
}
//System.out.println("The corner is: " + d);
posB = LatLon.greatCircleEndPosition(posA.getLatLon(), handle, Angle.fromDegrees(waypoint.getAngle()+0.000001));
}
//posC is heel klein en in het verlengde van de hemelsbrede lijn
segmentAzimuth = LatLon.greatCircleAzimuth(posD.getLatLon(), posA.getLatLon());
segmentDistance = LatLon.greatCircleDistance(posD.getLatLon(), posA.getLatLon());
posC = LatLon.greatCircleEndPosition(posD.getLatLon(), segmentAzimuth, Angle.fromDegrees(0.001));
BezierVertex vecA = geodeticToCartesian(posA.getLatLon(), 200);
BezierVertex vecB = geodeticToCartesian(posB, 200);
BezierVertex vecC = geodeticToCartesian(posC, 200);
BezierVertex vecD = geodeticToCartesian(posD.getLatLon(), 200);
double x, y, z;
double k = segmentDistance.degrees / 0.005;
if (k > 200) k = 200;
if (k < 20) k = 20;
k = 1 / k;
for(double t=0;t<1;t+=k){
x=(vecA.x+t*(-vecA.x*3+t*(3*vecA.x-vecA.x*t)))+t*(3*vecB.x+t*(-6*vecB.x+vecB.x*3*t))+t*t*(vecC.x*3-vecC.x*3*t)+vecD.x*t*t*t;
y=(vecA.y+t*(-vecA.y*3+t*(3*vecA.y-vecA.y*t)))+t*(3*vecB.y+t*(-6*vecB.y+vecB.y*3*t))+t*t*(vecC.y*3-vecC.y*3*t)+vecD.y*t*t*t;
z=(vecA.z+t*(-vecA.z*3+t*(3*vecA.z-vecA.z*t)))+t*(3*vecB.z+t*(-6*vecB.z+vecB.z*3*t))+t*t*(vecC.z*3-vecC.z*3*t)+vecD.z*t*t*t;
vertices.add(cartesianToGeodetic(x, y, z));
}
return vertices;
}
public static void recalculateVertices(Track track) {
//kan nog wat sneller door meteen latlon te nemen van PosA en PosD
track.setStatus(TrackStatus.DIRTY_VERTICES_AND_DIRTY_TIMES);
double t;
for(Waypoint waypoint : track.getWaypoints()) {
waypoint.getVertices().clear();
if(waypoint.isLast()) {
waypoint.getVertices().add(geodeticToCartesian(waypoint.getPosition().getLatLon(), 100));
waypoint.setTotalDistance(0);
} else {
Waypoint nextWaypoint = waypoint.getTrack().getNextWaypoint(waypoint);
//the begin and end control points
Position posA = waypoint.getPosition();
Position posD = nextWaypoint.getPosition();
//Determine the second and third control point
Angle segmentAzimuth = null;
Angle segmentDistance = LatLon.greatCircleDistance(posA.getLatLon(), posD.getLatLon());
LatLon posB, posC = null;
if(waypoint.isFirst()) {
//posB is heel klein en in het verlengde van de hemelsbrede lijn
segmentAzimuth = LatLon.greatCircleAzimuth(posA.getLatLon(), posD.getLatLon());
segmentDistance = LatLon.greatCircleDistance(posA.getLatLon(), posD.getLatLon());
posB = LatLon.greatCircleEndPosition(posA.getLatLon(), segmentAzimuth, Angle.fromDegrees(0.000001));
} else {
//posB haaks enzo
Waypoint previousWaypoint = waypoint.getTrack().getPreviousWaypoint(waypoint);
Angle aCwNw = LatLon.greatCircleAzimuth(posA.getLatLon(), posD.getLatLon());
Angle aCwPw = LatLon.greatCircleAzimuth(posA.getLatLon(), previousWaypoint.getPosition().getLatLon());
Angle sum = aCwNw.subtract(aCwPw);
Angle handle;
double d = sum.degrees;
if(d < -180) {
//System.out.println("(1) d < -180");
handle = aCwNw.addDegrees((Math.abs(d)-180)/2);
} else if(d < 0) {
//System.out.println("(2) -180 > d < 0");
handle = aCwNw.subtractDegrees((180-Math.abs(d))/2);
//handle = aCwNw.subtractDegrees(((360-d)-180)/2);
} else if(d < 180) {
//System.out.println("(3) 0 > d < 180");
handle = aCwNw.addDegrees(((360-d)-180)/2);
} else {
//System.out.println("(4) d >= 180");
handle = aCwNw.subtractDegrees((d-180)/2);
}
//System.out.println("The corner is: " + d);
posB = LatLon.greatCircleEndPosition(posA.getLatLon(), handle, Angle.fromDegrees(waypoint.getAngle()+0.000001));
}
if(nextWaypoint.isLast()) {
//posC is heel klein en in het verlengde van de hemelsbrede lijn
segmentAzimuth = LatLon.greatCircleAzimuth(posD.getLatLon(), posA.getLatLon());
segmentDistance = LatLon.greatCircleDistance(posD.getLatLon(), posA.getLatLon());
posC = LatLon.greatCircleEndPosition(posD.getLatLon(), segmentAzimuth, Angle.fromDegrees(0.001));
} else {
//posC haaks enzo
Waypoint secondNextWaypoint = nextWaypoint.getTrack().getNextWaypoint(nextWaypoint);
Angle aNwSw = LatLon.greatCircleAzimuth(posD.getLatLon(), secondNextWaypoint.getPosition().getLatLon());
Angle aNwCw = LatLon.greatCircleAzimuth(posD.getLatLon(), posA.getLatLon());
Angle sum = aNwCw.subtract(aNwSw);
Angle handle;
double d = sum.degrees;
if(d < -180) {
//System.out.println("(1) d < -180");
handle = aNwCw.addDegrees((Math.abs(d)-180)/2);
} else if(d < 0) {
//System.out.println("(2) -180 > d < 0");
handle = aNwCw.subtractDegrees((180-Math.abs(d))/2);
} else if(d < 180) {
//System.out.println("(3) 0 > d < 180");
handle = aNwCw.addDegrees(((360-d)-180)/2);
} else {
//System.out.println("(4) d >= 180");
handle = aNwCw.subtractDegrees((d-180)/2);
}
//System.out.println("The corner is: " + d);
posC = LatLon.greatCircleEndPosition(posD.getLatLon(), handle, Angle.fromDegrees(nextWaypoint.getAngle()+0.001));
}
BezierVertex vecA = geodeticToCartesian(posA.getLatLon(), 100);
BezierVertex vecB = geodeticToCartesian(posB, 100);
BezierVertex vecC = geodeticToCartesian(posC, 100);
BezierVertex vecD = geodeticToCartesian(posD.getLatLon(), 100);
double x, y, z;
double k = segmentDistance.degrees / 0.005;
if (k > 200) k = 200;
if (k < 20) k = 20;
k = 1 / k;
waypoint.getVertices().add(geodeticToCartesian(waypoint.getPosition().getLatLon(), 100));
for(t=0;t<=1;t+=k){
x=(vecA.x+t*(-vecA.x*3+t*(3*vecA.x-vecA.x*t)))+t*(3*vecB.x+t*(-6*vecB.x+vecB.x*3*t))+t*t*(vecC.x*3-vecC.x*3*t)+vecD.x*t*t*t;
y=(vecA.y+t*(-vecA.y*3+t*(3*vecA.y-vecA.y*t)))+t*(3*vecB.y+t*(-6*vecB.y+vecB.y*3*t))+t*t*(vecC.y*3-vecC.y*3*t)+vecD.y*t*t*t;
z=(vecA.z+t*(-vecA.z*3+t*(3*vecA.z-vecA.z*t)))+t*(3*vecB.z+t*(-6*vecB.z+vecB.z*3*t))+t*t*(vecC.z*3-vecC.z*3*t)+vecD.z*t*t*t;
waypoint.getVertices().add(cartesianToGeodetic(x, y, z));
}
waypoint.getVertices().add(geodeticToCartesian(nextWaypoint.getPosition().getLatLon(), 100));
CopyOnWriteArrayList<BezierVertex> vertices = waypoint.getVertices();
double totalDistance = 0;
for(int i = 0; i < vertices.size()-1; i++) {
LatLon l1 = LatLon.fromDegrees(vertices.get(i).latitude, vertices.get(i).longitude);
LatLon l2 = LatLon.fromDegrees(vertices.get(i+1).latitude, vertices.get(i+1).longitude);
double totalVertexDistance = LatLon.ellipsoidalDistance(l1, l2, Earth.WGS84_EQUATORIAL_RADIUS, Earth.WGS84_POLAR_RADIUS);
if(Double.isNaN(totalVertexDistance)) totalVertexDistance = 0;
vertices.get(i).distanceToNextVertex = totalVertexDistance;
totalDistance += totalVertexDistance;
}
waypoint.setTotalDistance(totalDistance);
}
}
track.setStatus(TrackStatus.CLEAN_VERTICES_AND_DIRTY_TIMES);
}
private static BezierVertex cartesianToGeodetic(double myx, double myy, double myz) {
double ra2 = 1 / (Earth.WGS84_EQUATORIAL_RADIUS * Earth.WGS84_EQUATORIAL_RADIUS);
double X = myz;
double Y = myx;
double Z = myy;
double e2 = Earth.WGS84_ES;
double e4 = e2 * e2;
double XXpYY = X * X + Y * Y;
double sqrtXXpYY = Math.sqrt(XXpYY);
double p = XXpYY * ra2;
double q = Z * Z * (1 - e2) * ra2;
double r = 1 / 6.0 * (p + q - e4);
double s = e4 * p * q / (4 * r * r * r);
double t = Math.pow(1 + s + Math.sqrt(s * (2 + s)), 1 / 3.0);
double u = r * (1 + t + 1 / t);
double v = Math.sqrt(u * u + e4 * q);
double w = e2 * (u + v - q) / (2 * v);
double k = Math.sqrt(u + v + w * w) - w;
double D = k * sqrtXXpYY / (k + e2);
double lon = 2 * Math.atan2(Y, X + sqrtXXpYY);
double sqrtDDpZZ = Math.sqrt(D * D + Z * Z);
double lat = 2 * Math.atan2(Z, D + sqrtDDpZZ);
//double elevation = (k + e2 - 1) * sqrtDDpZZ / k;
return geodeticToCartesian(LatLon.fromRadians(lat, lon), 100);
}
private static LatLon bezierVertexToLatLon(BezierVertex vertex) {
double ra2 = 1 / (Earth.WGS84_EQUATORIAL_RADIUS * Earth.WGS84_EQUATORIAL_RADIUS);
double X = vertex.z;
double Y = vertex.x;
double Z = vertex.y;
double e2 = Earth.WGS84_ES;
double e4 = e2 * e2;
double XXpYY = X * X + Y * Y;
double sqrtXXpYY = Math.sqrt(XXpYY);
double p = XXpYY * ra2;
double q = Z * Z * (1 - e2) * ra2;
double r = 1 / 6.0 * (p + q - e4);
double s = e4 * p * q / (4 * r * r * r);
double t = Math.pow(1 + s + Math.sqrt(s * (2 + s)), 1 / 3.0);
double u = r * (1 + t + 1 / t);
double v = Math.sqrt(u * u + e4 * q);
double w = e2 * (u + v - q) / (2 * v);
double k = Math.sqrt(u + v + w * w) - w;
double D = k * sqrtXXpYY / (k + e2);
double lon = 2 * Math.atan2(Y, X + sqrtXXpYY);
double sqrtDDpZZ = Math.sqrt(D * D + Z * Z);
double lat = 2 * Math.atan2(Z, D + sqrtDDpZZ);
//double elevation = (k + e2 - 1) * sqrtDDpZZ / k;
return LatLon.fromRadians(lat, lon);
}
public static BezierVertex geodeticToCartesian(LatLon latLon, double metersElevation) {
double cosLat = Math.cos(latLon.getLatitude().radians);
double sinLat = Math.sin(latLon.getLatitude().radians);
double cosLon = Math.cos(latLon.getLongitude().radians);
double sinLon = Math.sin(latLon.getLongitude().radians);
double rpm = Earth.WGS84_EQUATORIAL_RADIUS / Math.sqrt(1.0 - Earth.WGS84_ES * sinLat * sinLat);
double x = (rpm + metersElevation) * cosLat * sinLon;
double y = (rpm * (1.0 - Earth.WGS84_ES) + metersElevation) * sinLat;
double z = (rpm + metersElevation) * cosLat * cosLon;
BezierVertex v = new BezierVertex(x, y, z);
v.latitude = latLon.getLatitude().degrees;
v.longitude = latLon.getLongitude().degrees;
return v;
}
public static Position getInsertPosition(Track track, Position p, boolean insert) {
if(track == null) return null;
if(p == null) return null;
BezierVertex vi = geodeticToCartesian(p.getLatLon(), 100);
double bestDifference = 1000000;
BezierVertex bestBezierVertex1 = null;
BezierVertex bestBezierVertex2 = null;
Waypoint bestWaypoint = null;
for(int j = 0; j < track.getWaypoints().size()-1; j++) {
Waypoint waypoint = track.getWaypoint(j);
for(int i = 0; i < waypoint.getVertices().size()-1; i++) {
BezierVertex v1 = waypoint.getBezierVertex(i);
BezierVertex v2 = waypoint.getBezierVertex(i+1);
double distance1 = distanceBetweenBezierVertices(v1, v2);
double distance2 = distanceBetweenBezierVertices(v1, vi) + distanceBetweenBezierVertices(vi, v2);
double difference = distance2 - distance1;
if(difference < bestDifference) {
//System.out.println("bestDifference: " + )
bestBezierVertex1 = v1;
bestBezierVertex2 = v2;
bestWaypoint = waypoint;
bestDifference = difference;
}
}
}
if(bestBezierVertex1 == null) return null;
if(bestBezierVertex2 == null) return null;
if(bestWaypoint == null) return null;
//System.out.println("bestWaypoint: " + bestWaypoint.getId());
int bestIndex = bestWaypoint.getId();
//Compute the location of the new vertex on the line
//In order to keep the line straight
//The two positions of the old segment
LatLon a = bezierVertexToLatLon(bestBezierVertex1);
LatLon e = bezierVertexToLatLon(bestBezierVertex2);
//The clicked position
LatLon b = p.getLatLon();
//Compute angels<SUF>
//Angle azAB = LatLon.rhumbAzimuth(a, b);
//Angle azAE = LatLon.rhumbAzimuth(a, e);
Angle azAB = LatLon.greatCircleAzimuth(a, b);
Angle azAE = LatLon.greatCircleAzimuth(a, e);
Angle diffABAE = azAB.subtract(azAE);
//Compute the position opposite to b
//Angle dis = LatLon.rhumbDistance(a, b);
//LatLon c = LatLon.rhumbEndPosition(a, (azAB.subtract(diffABAE)).subtract(diffABAE), dis);
Angle dis = LatLon.greatCircleDistance(a, b);
LatLon c = LatLon.greatCircleEndPosition(a, (azAB.subtract(diffABAE)).subtract(diffABAE), dis);
//Get the point that is in between them
LatLon d = LatLon.interpolate(0.5, b, c);
//Insert the vertex at the appropirate location
Position insertPosition = Position.fromDegrees(d.getLatitude().degrees, d.getLongitude().degrees, 100);
if(insert) {
track.addWaypoint(bestIndex+1, new Waypoint(track, d.getLatitude().degrees, d.getLongitude().degrees, bestWaypoint.getSpeed(), bestWaypoint.getAngle()));
}
return insertPosition;
}
public static double distanceBetweenBezierVertices(BezierVertex v1, BezierVertex v2) {
double tmp;
double result = 0.0;
tmp = v1.x - v2.x;
result += tmp * tmp;
tmp = v1.y - v2.y;
result += tmp * tmp;
tmp = v1.z - v2.z;
result += tmp * tmp;
return result;
}
public static String colorToHex(Color color) {
String r = Integer.toHexString(color.getRed());
String g = Integer.toHexString(color.getGreen());
String b = Integer.toHexString(color.getBlue());
if(r.length() < 2) r = "0" + r;
if(g.length() < 2) g = "0" + g;
if(b.length() < 2) b = "0" + b;
return "#" + r + g + b;
}
public static Color hexToColor(String hex) {
int r = Integer.parseInt(hex.substring(1, 3), 16);
int g = Integer.parseInt(hex.substring(3, 5), 16);
int b = Integer.parseInt(hex.substring(5, 7), 16);
return new Color(Display.getDefault(), r, g, b);
}
}
|
17684_41 | /*
* Copyright (C) 2014-2015 OpenKeeper
*
* OpenKeeper 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.
*
* OpenKeeper 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 OpenKeeper. If not, see <http://www.gnu.org/licenses/>.
*/
package toniarts.openkeeper.tools.convert.map;
import java.awt.Color;
import java.util.EnumSet;
import toniarts.openkeeper.game.data.IFpsSoundable;
import toniarts.openkeeper.game.data.ISoundable;
import toniarts.openkeeper.tools.convert.IFlagEnum;
/**
* Container class for the Terrain & TerrainBlock
*
* @author Wizand Petteri Loisko [email protected], Toni Helenius
* <[email protected]>
*
* Thank you https://github.com/werkt
*/
public class Terrain implements Comparable<Terrain>, ISoundable, IFpsSoundable {
/**
* Terrain flags
*/
public enum TerrainFlag implements IFlagEnum {
SOLID(0x00000001),
IMPENETRABLE(0x00000002),
OWNABLE(0x00000004),
TAGGABLE(0x00000008),
ROOM(0x00000010), // is room terrain
ATTACKABLE(0x00000020),
TORCH(0x00000040), // has torch?
WATER(0x00000080),
LAVA(0x00000100),
ALWAYS_EXPLORED(0x00000200),
PLAYER_COLOURED_PATH(0x00000400),
PLAYER_COLOURED_WALL(0x00000800),
CONSTRUCTION_TYPE_WATER(0x00001000),
CONSTRUCTION_TYPE_QUAD(0x00002000),
UNEXPLORE_IF_DUG_BY_ANOTHER_PLAYER(0x00004000),
FILL_INABLE(0x00008000),
ALLOW_ROOM_WALLS(0x00010000),
DECAY(0x00020000),
RANDOM_TEXTURE(0x00040000),
TERRAIN_COLOR_RED(0x00080000), // If this is set, add 256 to the red value of terrain light
TERRAIN_COLOR_GREEN(0x00100000), // If this is set, add 256 to the green value of terrain light
TERRAIN_COLOR_BLUE(0x00200000), // If this is set, add 256 to the blue value of terrain light
DWARF_CAN_DIG_THROUGH(0x00800000),
REVEAL_THROUGH_FOG_OF_WAR(0x01000000),
AMBIENT_COLOR_RED(0x02000000), // If this is set, add 256 to the red value of ambient light
AMBIENT_COLOR_GREEN(0x04000000), // If this is set, add 256 to the green value of ambient light
AMBIENT_COLOR_BLUE(0x08000000), // If this is set, add 256 to the blue value of ambient light
TERRAIN_LIGHT(0x10000000),
AMBIENT_LIGHT(0x20000000);
private final long flagValue;
private TerrainFlag(long flagValue) {
this.flagValue = flagValue;
}
@Override
public long getFlagValue() {
return flagValue;
}
};
//
// struct Terrain { char name[32]; /* 0
//
// ArtResource complete; /* 20 */
// ArtResource side; /* 74 */
// ArtResource top; /* c8 */
// ArtResource tagged; /* 11c */
// StringIds string_ids; /* 170 */
// uint32_t unk188; /* 188 */
// uint32_t light_height; /* 18c */
// uint32_t flags; /* 190 */
// uint16_t damage; /* 194 */
// uint16_t editorTextureId; /* 196 */
// uint16_t unk198; /* 198 */
// uint16_t gold_value; /* 19a */
// uint16_t mana_gain; /* 19c */
// uint16_t max_mana_gain; /* 19e */
// uint16_t unk1a0; /* 1a0 */
// uint16_t unk1a2; /* 1a2 */
// uint16_t unk1a4; /* 1a4 */
// uint16_t unk1a6; /* 1a6 */
// uint16_t unk1a8; /* 1a8 */
// uint16_t unk1aa; /* 1aa */
// uint16_t unk1ac; /* 1ac */
// uint16_t unk1ae[16]; /* 1ae */
// uint8_t wibble_h; /* 1ce */
// uint8_t lean_h[3]; /* 1cf */
// uint8_t wibble_v; /* 1d2 */
// uint8_t lean_v[3]; /* 1d3 */
// uint8_t id; /* 1d6 */
// uint16_t starting_health; /* 1d7 */
// uint8_t max_health_type; /* 1d9 */
// uint8_t destroyed_type; /* 1da */
// uint8_t terrain_light[3]; /* 1db */
// uint8_t texture_frames; /* 1de */
// char str1[32]; /* 1df */
// uint16_t max_health; /* 1ff */
// uint8_t ambient_light[3]; /* 201 */
// char str2[32]; /* 204 */
// uint32_t unk224; /* 224 */
//};
private String name;
private ArtResource completeResource; // 20
private ArtResource sideResource; // 74
private ArtResource topResource; // c8
private ArtResource taggedTopResource; // 11c
private StringId stringIds; // 170
private float depth; // 188
private float lightHeight; // 18c, fixed point
private EnumSet<TerrainFlag> flags; // 190
private int damage; // 194
private int editorTextureId; // 196 Data\editor\Graphics\TerrainIcons.bmp
private int unk198; // 198
private int goldValue; // 19a
private int manaGain; // 19c
private int maxManaGain; // 19e
private int tooltipStringId; // 1a0
private int nameStringId; // 1a2
private int maxHealthEffectId; // 1a4
private int destroyedEffectId; // 1a6
private int generalDescriptionStringId; // 1a8
private int strengthStringId; // 1aa
private int weaknessStringId; // 1ac
private int[] unk1ae; // 1ae
private short wibbleH; // 1ce
private short[] leanH; // 1cf
private short wibbleV; // 1d2
private short[] leanV; // 1d3
private short terrainId; // 1d6
private int startingHealth; // 1d7
private short maxHealthTypeTerrainId; // 1d9
private short destroyedTypeTerrainId; // 1da
private Color terrainLight; // 1db
private short textureFrames; // 1de
private String soundCategory; // 1df
private int maxHealth; // 1ff
private Color ambientLight; // 201
private String soundCategoryFirstPerson; // 204
private int unk224; // 224
public String getName() {
return name;
}
protected void setName(String name) {
this.name = name;
}
public float getDepth() {
return depth;
}
protected void setDepth(float depth) {
this.depth = depth;
}
public float getLightHeight() {
return lightHeight;
}
protected void setLightHeight(float lightHeight) {
this.lightHeight = lightHeight;
}
public EnumSet<TerrainFlag> getFlags() {
return flags;
}
protected void setFlags(EnumSet<TerrainFlag> flags) {
this.flags = flags;
}
public int getDamage() {
return damage;
}
protected void setDamage(int damage) {
this.damage = damage;
}
public int getEditorTextureId() {
return editorTextureId;
}
protected void setEditorTextureId(int editorTextureId) {
this.editorTextureId = editorTextureId;
}
public int getUnk198() {
return unk198;
}
protected void setUnk198(int unk198) {
this.unk198 = unk198;
}
public int getGoldValue() {
return goldValue;
}
protected void setGoldValue(int goldValue) {
this.goldValue = goldValue;
}
public int getManaGain() {
return manaGain;
}
protected void setManaGain(int manaGain) {
this.manaGain = manaGain;
}
public int getMaxManaGain() {
return maxManaGain;
}
protected void setMaxManaGain(int maxManaGain) {
this.maxManaGain = maxManaGain;
}
public int getTooltipStringId() {
return tooltipStringId;
}
protected void setTooltipStringId(int tooltipStringId) {
this.tooltipStringId = tooltipStringId;
}
public int getNameStringId() {
return nameStringId;
}
protected void setNameStringId(int nameStringId) {
this.nameStringId = nameStringId;
}
public int getMaxHealthEffectId() {
return maxHealthEffectId;
}
protected void setMaxHealthEffectId(int maxHealthEffectId) {
this.maxHealthEffectId = maxHealthEffectId;
}
public int getDestroyedEffectId() {
return destroyedEffectId;
}
protected void setDestroyedEffectId(int destroyedEffectId) {
this.destroyedEffectId = destroyedEffectId;
}
public int getGeneralDescriptionStringId() {
return generalDescriptionStringId;
}
protected void setGeneralDescriptionStringId(int generalDescriptionStringId) {
this.generalDescriptionStringId = generalDescriptionStringId;
}
public int getStrengthStringId() {
return strengthStringId;
}
protected void setStrengthStringId(int strengthStringId) {
this.strengthStringId = strengthStringId;
}
public int getWeaknessStringId() {
return weaknessStringId;
}
protected void setWeaknessStringId(int weaknessStringId) {
this.weaknessStringId = weaknessStringId;
}
public int[] getUnk1ae() {
return unk1ae;
}
protected void setUnk1ae(int[] unk1ae) {
this.unk1ae = unk1ae;
}
public short getWibbleH() {
return wibbleH;
}
protected void setWibbleH(short wibbleH) {
this.wibbleH = wibbleH;
}
public short[] getLeanH() {
return leanH;
}
protected void setLeanH(short[] leanH) {
this.leanH = leanH;
}
public short getWibbleV() {
return wibbleV;
}
protected void setWibbleV(short wibbleV) {
this.wibbleV = wibbleV;
}
public short[] getLeanV() {
return leanV;
}
protected void setLeanV(short[] leanV) {
this.leanV = leanV;
}
public short getTerrainId() {
return terrainId;
}
protected void setTerrainId(short terrainId) {
this.terrainId = terrainId;
}
public int getStartingHealth() {
return startingHealth;
}
protected void setStartingHealth(int startingHealth) {
this.startingHealth = startingHealth;
}
public short getMaxHealthTypeTerrainId() {
return maxHealthTypeTerrainId;
}
protected void setMaxHealthTypeTerrainId(short maxHealthTypeTerrainId) {
this.maxHealthTypeTerrainId = maxHealthTypeTerrainId;
}
public short getDestroyedTypeTerrainId() {
return destroyedTypeTerrainId;
}
protected void setDestroyedTypeTerrainId(short destroyedTypeTerrainId) {
this.destroyedTypeTerrainId = destroyedTypeTerrainId;
}
public Color getTerrainLight() {
return terrainLight;
}
protected void setTerrainLight(Color terrainLight) {
this.terrainLight = terrainLight;
}
public short getTextureFrames() {
return textureFrames;
}
protected void setTextureFrames(short textureFrames) {
this.textureFrames = textureFrames;
}
@Override
public String getSoundCategory() {
return soundCategory;
}
protected void setSoundCategory(String soundCategory) {
this.soundCategory = soundCategory;
}
public int getMaxHealth() {
return maxHealth;
}
protected void setMaxHealth(int maxHealth) {
this.maxHealth = maxHealth;
}
public Color getAmbientLight() {
return ambientLight;
}
protected void setAmbientLight(Color ambientLight) {
this.ambientLight = ambientLight;
}
@Override
public String getSoundCategoryFirstPerson() {
return soundCategoryFirstPerson;
}
protected void setSoundCategoryFirstPerson(String soundCategoryFirstPerson) {
this.soundCategoryFirstPerson = soundCategoryFirstPerson;
}
public int getUnk224() {
return unk224;
}
protected void setUnk224(int unk224) {
this.unk224 = unk224;
}
public ArtResource getCompleteResource() {
return completeResource;
}
protected void setCompleteResource(ArtResource completeResource) {
this.completeResource = completeResource;
}
public ArtResource getSideResource() {
return sideResource;
}
protected void setSideResource(ArtResource sideResource) {
this.sideResource = sideResource;
}
public ArtResource getTopResource() {
return topResource;
}
protected void setTopResource(ArtResource topResource) {
this.topResource = topResource;
}
public ArtResource getTaggedTopResource() {
return taggedTopResource;
}
protected void setTaggedTopResource(ArtResource taggedTopResource) {
this.taggedTopResource = taggedTopResource;
}
public StringId getStringIds() {
return stringIds;
}
protected void setStringIds(StringId stringIds) {
this.stringIds = stringIds;
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(Terrain o) {
return Short.compare(terrainId, o.terrainId);
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + this.terrainId;
return hash;
}
@Override
public boolean equals(java.lang.Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Terrain other = (Terrain) obj;
if (this.terrainId != other.terrainId) {
return false;
}
return true;
}
}
| tonihele/OpenKeeper | src/toniarts/openkeeper/tools/convert/map/Terrain.java | 4,345 | // uint8_t terrain_light[3]; /* 1db */ | line_comment | nl | /*
* Copyright (C) 2014-2015 OpenKeeper
*
* OpenKeeper 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.
*
* OpenKeeper 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 OpenKeeper. If not, see <http://www.gnu.org/licenses/>.
*/
package toniarts.openkeeper.tools.convert.map;
import java.awt.Color;
import java.util.EnumSet;
import toniarts.openkeeper.game.data.IFpsSoundable;
import toniarts.openkeeper.game.data.ISoundable;
import toniarts.openkeeper.tools.convert.IFlagEnum;
/**
* Container class for the Terrain & TerrainBlock
*
* @author Wizand Petteri Loisko [email protected], Toni Helenius
* <[email protected]>
*
* Thank you https://github.com/werkt
*/
public class Terrain implements Comparable<Terrain>, ISoundable, IFpsSoundable {
/**
* Terrain flags
*/
public enum TerrainFlag implements IFlagEnum {
SOLID(0x00000001),
IMPENETRABLE(0x00000002),
OWNABLE(0x00000004),
TAGGABLE(0x00000008),
ROOM(0x00000010), // is room terrain
ATTACKABLE(0x00000020),
TORCH(0x00000040), // has torch?
WATER(0x00000080),
LAVA(0x00000100),
ALWAYS_EXPLORED(0x00000200),
PLAYER_COLOURED_PATH(0x00000400),
PLAYER_COLOURED_WALL(0x00000800),
CONSTRUCTION_TYPE_WATER(0x00001000),
CONSTRUCTION_TYPE_QUAD(0x00002000),
UNEXPLORE_IF_DUG_BY_ANOTHER_PLAYER(0x00004000),
FILL_INABLE(0x00008000),
ALLOW_ROOM_WALLS(0x00010000),
DECAY(0x00020000),
RANDOM_TEXTURE(0x00040000),
TERRAIN_COLOR_RED(0x00080000), // If this is set, add 256 to the red value of terrain light
TERRAIN_COLOR_GREEN(0x00100000), // If this is set, add 256 to the green value of terrain light
TERRAIN_COLOR_BLUE(0x00200000), // If this is set, add 256 to the blue value of terrain light
DWARF_CAN_DIG_THROUGH(0x00800000),
REVEAL_THROUGH_FOG_OF_WAR(0x01000000),
AMBIENT_COLOR_RED(0x02000000), // If this is set, add 256 to the red value of ambient light
AMBIENT_COLOR_GREEN(0x04000000), // If this is set, add 256 to the green value of ambient light
AMBIENT_COLOR_BLUE(0x08000000), // If this is set, add 256 to the blue value of ambient light
TERRAIN_LIGHT(0x10000000),
AMBIENT_LIGHT(0x20000000);
private final long flagValue;
private TerrainFlag(long flagValue) {
this.flagValue = flagValue;
}
@Override
public long getFlagValue() {
return flagValue;
}
};
//
// struct Terrain { char name[32]; /* 0
//
// ArtResource complete; /* 20 */
// ArtResource side; /* 74 */
// ArtResource top; /* c8 */
// ArtResource tagged; /* 11c */
// StringIds string_ids; /* 170 */
// uint32_t unk188; /* 188 */
// uint32_t light_height; /* 18c */
// uint32_t flags; /* 190 */
// uint16_t damage; /* 194 */
// uint16_t editorTextureId; /* 196 */
// uint16_t unk198; /* 198 */
// uint16_t gold_value; /* 19a */
// uint16_t mana_gain; /* 19c */
// uint16_t max_mana_gain; /* 19e */
// uint16_t unk1a0; /* 1a0 */
// uint16_t unk1a2; /* 1a2 */
// uint16_t unk1a4; /* 1a4 */
// uint16_t unk1a6; /* 1a6 */
// uint16_t unk1a8; /* 1a8 */
// uint16_t unk1aa; /* 1aa */
// uint16_t unk1ac; /* 1ac */
// uint16_t unk1ae[16]; /* 1ae */
// uint8_t wibble_h; /* 1ce */
// uint8_t lean_h[3]; /* 1cf */
// uint8_t wibble_v; /* 1d2 */
// uint8_t lean_v[3]; /* 1d3 */
// uint8_t id; /* 1d6 */
// uint16_t starting_health; /* 1d7 */
// uint8_t max_health_type; /* 1d9 */
// uint8_t destroyed_type; /* 1da */
// uint8_t terrain_light[3];<SUF>
// uint8_t texture_frames; /* 1de */
// char str1[32]; /* 1df */
// uint16_t max_health; /* 1ff */
// uint8_t ambient_light[3]; /* 201 */
// char str2[32]; /* 204 */
// uint32_t unk224; /* 224 */
//};
private String name;
private ArtResource completeResource; // 20
private ArtResource sideResource; // 74
private ArtResource topResource; // c8
private ArtResource taggedTopResource; // 11c
private StringId stringIds; // 170
private float depth; // 188
private float lightHeight; // 18c, fixed point
private EnumSet<TerrainFlag> flags; // 190
private int damage; // 194
private int editorTextureId; // 196 Data\editor\Graphics\TerrainIcons.bmp
private int unk198; // 198
private int goldValue; // 19a
private int manaGain; // 19c
private int maxManaGain; // 19e
private int tooltipStringId; // 1a0
private int nameStringId; // 1a2
private int maxHealthEffectId; // 1a4
private int destroyedEffectId; // 1a6
private int generalDescriptionStringId; // 1a8
private int strengthStringId; // 1aa
private int weaknessStringId; // 1ac
private int[] unk1ae; // 1ae
private short wibbleH; // 1ce
private short[] leanH; // 1cf
private short wibbleV; // 1d2
private short[] leanV; // 1d3
private short terrainId; // 1d6
private int startingHealth; // 1d7
private short maxHealthTypeTerrainId; // 1d9
private short destroyedTypeTerrainId; // 1da
private Color terrainLight; // 1db
private short textureFrames; // 1de
private String soundCategory; // 1df
private int maxHealth; // 1ff
private Color ambientLight; // 201
private String soundCategoryFirstPerson; // 204
private int unk224; // 224
public String getName() {
return name;
}
protected void setName(String name) {
this.name = name;
}
public float getDepth() {
return depth;
}
protected void setDepth(float depth) {
this.depth = depth;
}
public float getLightHeight() {
return lightHeight;
}
protected void setLightHeight(float lightHeight) {
this.lightHeight = lightHeight;
}
public EnumSet<TerrainFlag> getFlags() {
return flags;
}
protected void setFlags(EnumSet<TerrainFlag> flags) {
this.flags = flags;
}
public int getDamage() {
return damage;
}
protected void setDamage(int damage) {
this.damage = damage;
}
public int getEditorTextureId() {
return editorTextureId;
}
protected void setEditorTextureId(int editorTextureId) {
this.editorTextureId = editorTextureId;
}
public int getUnk198() {
return unk198;
}
protected void setUnk198(int unk198) {
this.unk198 = unk198;
}
public int getGoldValue() {
return goldValue;
}
protected void setGoldValue(int goldValue) {
this.goldValue = goldValue;
}
public int getManaGain() {
return manaGain;
}
protected void setManaGain(int manaGain) {
this.manaGain = manaGain;
}
public int getMaxManaGain() {
return maxManaGain;
}
protected void setMaxManaGain(int maxManaGain) {
this.maxManaGain = maxManaGain;
}
public int getTooltipStringId() {
return tooltipStringId;
}
protected void setTooltipStringId(int tooltipStringId) {
this.tooltipStringId = tooltipStringId;
}
public int getNameStringId() {
return nameStringId;
}
protected void setNameStringId(int nameStringId) {
this.nameStringId = nameStringId;
}
public int getMaxHealthEffectId() {
return maxHealthEffectId;
}
protected void setMaxHealthEffectId(int maxHealthEffectId) {
this.maxHealthEffectId = maxHealthEffectId;
}
public int getDestroyedEffectId() {
return destroyedEffectId;
}
protected void setDestroyedEffectId(int destroyedEffectId) {
this.destroyedEffectId = destroyedEffectId;
}
public int getGeneralDescriptionStringId() {
return generalDescriptionStringId;
}
protected void setGeneralDescriptionStringId(int generalDescriptionStringId) {
this.generalDescriptionStringId = generalDescriptionStringId;
}
public int getStrengthStringId() {
return strengthStringId;
}
protected void setStrengthStringId(int strengthStringId) {
this.strengthStringId = strengthStringId;
}
public int getWeaknessStringId() {
return weaknessStringId;
}
protected void setWeaknessStringId(int weaknessStringId) {
this.weaknessStringId = weaknessStringId;
}
public int[] getUnk1ae() {
return unk1ae;
}
protected void setUnk1ae(int[] unk1ae) {
this.unk1ae = unk1ae;
}
public short getWibbleH() {
return wibbleH;
}
protected void setWibbleH(short wibbleH) {
this.wibbleH = wibbleH;
}
public short[] getLeanH() {
return leanH;
}
protected void setLeanH(short[] leanH) {
this.leanH = leanH;
}
public short getWibbleV() {
return wibbleV;
}
protected void setWibbleV(short wibbleV) {
this.wibbleV = wibbleV;
}
public short[] getLeanV() {
return leanV;
}
protected void setLeanV(short[] leanV) {
this.leanV = leanV;
}
public short getTerrainId() {
return terrainId;
}
protected void setTerrainId(short terrainId) {
this.terrainId = terrainId;
}
public int getStartingHealth() {
return startingHealth;
}
protected void setStartingHealth(int startingHealth) {
this.startingHealth = startingHealth;
}
public short getMaxHealthTypeTerrainId() {
return maxHealthTypeTerrainId;
}
protected void setMaxHealthTypeTerrainId(short maxHealthTypeTerrainId) {
this.maxHealthTypeTerrainId = maxHealthTypeTerrainId;
}
public short getDestroyedTypeTerrainId() {
return destroyedTypeTerrainId;
}
protected void setDestroyedTypeTerrainId(short destroyedTypeTerrainId) {
this.destroyedTypeTerrainId = destroyedTypeTerrainId;
}
public Color getTerrainLight() {
return terrainLight;
}
protected void setTerrainLight(Color terrainLight) {
this.terrainLight = terrainLight;
}
public short getTextureFrames() {
return textureFrames;
}
protected void setTextureFrames(short textureFrames) {
this.textureFrames = textureFrames;
}
@Override
public String getSoundCategory() {
return soundCategory;
}
protected void setSoundCategory(String soundCategory) {
this.soundCategory = soundCategory;
}
public int getMaxHealth() {
return maxHealth;
}
protected void setMaxHealth(int maxHealth) {
this.maxHealth = maxHealth;
}
public Color getAmbientLight() {
return ambientLight;
}
protected void setAmbientLight(Color ambientLight) {
this.ambientLight = ambientLight;
}
@Override
public String getSoundCategoryFirstPerson() {
return soundCategoryFirstPerson;
}
protected void setSoundCategoryFirstPerson(String soundCategoryFirstPerson) {
this.soundCategoryFirstPerson = soundCategoryFirstPerson;
}
public int getUnk224() {
return unk224;
}
protected void setUnk224(int unk224) {
this.unk224 = unk224;
}
public ArtResource getCompleteResource() {
return completeResource;
}
protected void setCompleteResource(ArtResource completeResource) {
this.completeResource = completeResource;
}
public ArtResource getSideResource() {
return sideResource;
}
protected void setSideResource(ArtResource sideResource) {
this.sideResource = sideResource;
}
public ArtResource getTopResource() {
return topResource;
}
protected void setTopResource(ArtResource topResource) {
this.topResource = topResource;
}
public ArtResource getTaggedTopResource() {
return taggedTopResource;
}
protected void setTaggedTopResource(ArtResource taggedTopResource) {
this.taggedTopResource = taggedTopResource;
}
public StringId getStringIds() {
return stringIds;
}
protected void setStringIds(StringId stringIds) {
this.stringIds = stringIds;
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(Terrain o) {
return Short.compare(terrainId, o.terrainId);
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + this.terrainId;
return hash;
}
@Override
public boolean equals(java.lang.Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Terrain other = (Terrain) obj;
if (this.terrainId != other.terrainId) {
return false;
}
return true;
}
}
|
165337_0 | package org.jabref.logic.msbib;
import org.jabref.logic.msbib.MSBibConverter;
import org.jabref.logic.msbib.MSBibEntry;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.FieldName;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
// Test voor import in MS Word
public class MSBibEntryTest {
BibEntry entry;
BibEntry entry1;
MSBibEntry msBibEntry;
MSBibEntry msBibEntry1;
@Before
public void setup() {
entry = new BibEntry();
entry1 = new BibEntry();
msBibEntry = new MSBibEntry();
msBibEntry1 = new MSBibEntry();
}
@Test
public void MsBibEntryTypeTest() {
entry.setField("title", "Dikke paarden");
entry.setType("Patent");
msBibEntry = MSBibConverter.convert(entry);
Assert.assertEquals("Patent", msBibEntry.getType());
}
@Test
public void MsBibEntryNoTypetest(){
entry1.setField("title","Dode mensen klagen niet");
msBibEntry1 = MSBibConverter.convert(entry1);
Assert.assertEquals("Misc",msBibEntry1.getType());
}
}
| tonny23/jabref | src/test/java/org/jabref/ASV/MSBibEntryTest.java | 379 | // Test voor import in MS Word | line_comment | nl | package org.jabref.logic.msbib;
import org.jabref.logic.msbib.MSBibConverter;
import org.jabref.logic.msbib.MSBibEntry;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.FieldName;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
// Test voor<SUF>
public class MSBibEntryTest {
BibEntry entry;
BibEntry entry1;
MSBibEntry msBibEntry;
MSBibEntry msBibEntry1;
@Before
public void setup() {
entry = new BibEntry();
entry1 = new BibEntry();
msBibEntry = new MSBibEntry();
msBibEntry1 = new MSBibEntry();
}
@Test
public void MsBibEntryTypeTest() {
entry.setField("title", "Dikke paarden");
entry.setType("Patent");
msBibEntry = MSBibConverter.convert(entry);
Assert.assertEquals("Patent", msBibEntry.getType());
}
@Test
public void MsBibEntryNoTypetest(){
entry1.setField("title","Dode mensen klagen niet");
msBibEntry1 = MSBibConverter.convert(entry1);
Assert.assertEquals("Misc",msBibEntry1.getType());
}
}
|
26864_4 | /*
* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.runtime.tree.xpath;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.LexerNoViableAltException;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.Vocabulary;
import org.antlr.v4.runtime.VocabularyImpl;
import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.misc.Interval;
/** Mimic the old XPathLexer from .g4 file */
public class XPathLexer extends Lexer {
public static final int
TOKEN_REF=1, RULE_REF=2, ANYWHERE=3, ROOT=4, WILDCARD=5, BANG=6, ID=7,
STRING=8;
public final static String[] modeNames = {
"DEFAULT_MODE"
};
public static final String[] ruleNames = {
"ANYWHERE", "ROOT", "WILDCARD", "BANG", "ID", "NameChar", "NameStartChar",
"STRING"
};
private static final String[] _LITERAL_NAMES = {
null, null, null, "'//'", "'/'", "'*'", "'!'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, "TOKEN_REF", "RULE_REF", "ANYWHERE", "ROOT", "WILDCARD", "BANG",
"ID", "STRING"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
public String getGrammarFileName() { return "XPathLexer.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public ATN getATN() {
return null;
}
protected int line = 1;
protected int charPositionInLine = 0;
public XPathLexer(CharStream input) {
super(input);
}
@Override
public Token nextToken() {
_tokenStartCharIndex = _input.index();
CommonToken t = null;
while ( t==null ) {
switch ( _input.LA(1) ) {
case '/':
consume();
if ( _input.LA(1)=='/' ) {
consume();
t = new CommonToken(ANYWHERE, "//");
}
else {
t = new CommonToken(ROOT, "/");
}
break;
case '*':
consume();
t = new CommonToken(WILDCARD, "*");
break;
case '!':
consume();
t = new CommonToken(BANG, "!");
break;
case '\'':
String s = matchString();
t = new CommonToken(STRING, s);
break;
case CharStream.EOF :
return new CommonToken(EOF, "<EOF>");
default:
if ( isNameStartChar(_input.LA(1)) ) {
String id = matchID();
if ( Character.isUpperCase(id.charAt(0)) ) t = new CommonToken(TOKEN_REF, id);
else t = new CommonToken(RULE_REF, id);
}
else {
throw new LexerNoViableAltException(this, _input, _tokenStartCharIndex, null);
}
break;
}
}
t.setStartIndex(_tokenStartCharIndex);
t.setCharPositionInLine(_tokenStartCharIndex);
t.setLine(line);
return t;
}
public void consume() {
int curChar = _input.LA(1);
if ( curChar=='\n' ) {
line++;
charPositionInLine=0;
}
else {
charPositionInLine++;
}
_input.consume();
}
@Override
public int getCharPositionInLine() {
return charPositionInLine;
}
public String matchID() {
int start = _input.index();
consume(); // drop start char
while ( isNameChar(_input.LA(1)) ) {
consume();
}
return _input.getText(Interval.of(start,_input.index()-1));
}
public String matchString() {
int start = _input.index();
consume(); // drop first quote
while ( _input.LA(1)!='\'' ) {
consume();
}
consume(); // drop last quote
return _input.getText(Interval.of(start,_input.index()-1));
}
public boolean isNameChar(int c) { return Character.isUnicodeIdentifierPart(c); }
public boolean isNameStartChar(int c) { return Character.isUnicodeIdentifierStart(c); }
}
| tonyarnold/antlr4 | runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathLexer.java | 1,647 | // drop start char | line_comment | nl | /*
* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
package org.antlr.v4.runtime.tree.xpath;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.LexerNoViableAltException;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.Vocabulary;
import org.antlr.v4.runtime.VocabularyImpl;
import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.misc.Interval;
/** Mimic the old XPathLexer from .g4 file */
public class XPathLexer extends Lexer {
public static final int
TOKEN_REF=1, RULE_REF=2, ANYWHERE=3, ROOT=4, WILDCARD=5, BANG=6, ID=7,
STRING=8;
public final static String[] modeNames = {
"DEFAULT_MODE"
};
public static final String[] ruleNames = {
"ANYWHERE", "ROOT", "WILDCARD", "BANG", "ID", "NameChar", "NameStartChar",
"STRING"
};
private static final String[] _LITERAL_NAMES = {
null, null, null, "'//'", "'/'", "'*'", "'!'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, "TOKEN_REF", "RULE_REF", "ANYWHERE", "ROOT", "WILDCARD", "BANG",
"ID", "STRING"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
public String getGrammarFileName() { return "XPathLexer.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
@Override
public ATN getATN() {
return null;
}
protected int line = 1;
protected int charPositionInLine = 0;
public XPathLexer(CharStream input) {
super(input);
}
@Override
public Token nextToken() {
_tokenStartCharIndex = _input.index();
CommonToken t = null;
while ( t==null ) {
switch ( _input.LA(1) ) {
case '/':
consume();
if ( _input.LA(1)=='/' ) {
consume();
t = new CommonToken(ANYWHERE, "//");
}
else {
t = new CommonToken(ROOT, "/");
}
break;
case '*':
consume();
t = new CommonToken(WILDCARD, "*");
break;
case '!':
consume();
t = new CommonToken(BANG, "!");
break;
case '\'':
String s = matchString();
t = new CommonToken(STRING, s);
break;
case CharStream.EOF :
return new CommonToken(EOF, "<EOF>");
default:
if ( isNameStartChar(_input.LA(1)) ) {
String id = matchID();
if ( Character.isUpperCase(id.charAt(0)) ) t = new CommonToken(TOKEN_REF, id);
else t = new CommonToken(RULE_REF, id);
}
else {
throw new LexerNoViableAltException(this, _input, _tokenStartCharIndex, null);
}
break;
}
}
t.setStartIndex(_tokenStartCharIndex);
t.setCharPositionInLine(_tokenStartCharIndex);
t.setLine(line);
return t;
}
public void consume() {
int curChar = _input.LA(1);
if ( curChar=='\n' ) {
line++;
charPositionInLine=0;
}
else {
charPositionInLine++;
}
_input.consume();
}
@Override
public int getCharPositionInLine() {
return charPositionInLine;
}
public String matchID() {
int start = _input.index();
consume(); // drop start<SUF>
while ( isNameChar(_input.LA(1)) ) {
consume();
}
return _input.getText(Interval.of(start,_input.index()-1));
}
public String matchString() {
int start = _input.index();
consume(); // drop first quote
while ( _input.LA(1)!='\'' ) {
consume();
}
consume(); // drop last quote
return _input.getText(Interval.of(start,_input.index()-1));
}
public boolean isNameChar(int c) { return Character.isUnicodeIdentifierPart(c); }
public boolean isNameStartChar(int c) { return Character.isUnicodeIdentifierStart(c); }
}
|
197681_0 | /*
* see license.txt
*/
package seventh.game.weapons;
import java.util.Random;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoObject;
import seventh.game.Game;
import seventh.game.entities.Entity;
import seventh.game.entities.Entity.Type;
import seventh.game.entities.PlayerEntity;
import seventh.game.net.NetWeapon;
import seventh.math.Vector2f;
import seventh.shared.Config;
import seventh.shared.Cons;
import seventh.shared.SoundType;
import seventh.shared.TimeStep;
/**
* Represents a Weapon.
*
* @author Tony
*
*/
public abstract class Weapon {
public enum WeaponState {
READY,
FIRING,
WAITING,
RELOADING,
FIRE_EMPTY,
MELEE_ATTACK,
SWITCHING,
UNKNOWN
;
public byte netValue() {
return (byte)ordinal();
}
private static WeaponState[] values = values();
public static WeaponState fromNet(byte value) {
if(value < 0 || value >= values.length) {
return UNKNOWN;
}
return values[value];
}
public static int numOfBits() {
return 4;
}
}
protected long weaponTime;
protected int damage;
protected long reloadTime;
protected int weaponWeight;
protected int clipSize;
protected int bulletsInClip;
protected int totalAmmo;
protected int spread;
protected int lineOfSight;
protected int bulletRange;
private WeaponState weaponState;
protected Entity owner;
protected Game game;
protected NetWeapon netWeapon;
private Random random;
private final Type type;
private GunSwing gunSwing;
private float bulletSpawnDistance,
rocketSpawnDistance,
grenadeSpawnDistance;
private int damageMultiplier;
/**
* @param game
* @param owner
* @param type
*/
public Weapon(Game game, Entity owner, Type type) {
this.type = type;
this.game = game;
this.owner = owner;
this.netWeapon = new NetWeapon();
this.netWeapon.type = type;
this.random = new Random();
this.weaponState = WeaponState.READY;
this.gunSwing = new GunSwing(game, owner);
this.bulletSpawnDistance = 15.0f;
this.rocketSpawnDistance = 40.0f;
this.grenadeSpawnDistance = 50.0f;
this.bulletRange = 5000;
}
/**
* Sets the weapons properties.
* @param weaponName
* @return the attributes if available, otherwise null
*/
protected LeoMap applyScriptAttributes(String weaponName) {
Config config = game.getConfig().getConfig();
try {
LeoObject values = config.get("weapons", weaponName);
if(values!=null&&values.isMap()) {
LeoMap attributes = values.as();
this.damage = attributes.getInt("damage");
this.reloadTime = attributes.getInt("reload_time");
this.clipSize = attributes.getInt("clip_size");
this.totalAmmo = attributes.getInt("total_ammo");
this.bulletsInClip = this.clipSize;
this.spread = attributes.getInt("spread");
this.bulletRange = attributes.getInt("bullet_range");
return attributes;
}
}
catch(LeolaRuntimeException e) {
Cons.print("*** Error reading the weapons configuration: " + e);
}
return null;
}
/**
* If this is a primary weapon or not
* @return true if this is a primary weapon
*/
public boolean isPrimary() {
return true;
}
/**
* If this weapon is huge, which prevents the user
* from taking certain actions
*
* @return true if this weapon is yuge
*/
public boolean isHeavyWeapon() {
return false;
}
/**
* @param owner the owner to set
*/
public void setOwner(Entity owner) {
this.owner = owner;
this.gunSwing.setOwner(owner);
if(owner instanceof PlayerEntity) {
this.damageMultiplier = ((PlayerEntity)owner).getDamageMultiplier();
}
}
/**
* @param bulletsInClip the bulletsInClip to set
*/
public void setBulletsInClip(int bulletsInClip) {
this.bulletsInClip = bulletsInClip;
}
/**
* @param totalAmmo the totalAmmo to set
*/
public void setTotalAmmo(int totalAmmo) {
this.totalAmmo = totalAmmo;
}
/**
* @return the type
*/
public Type getType() {
return type;
}
/**
* @return the weaponWeight in pounds
*/
public int getWeaponWeight() {
return weaponWeight;
}
/**
* @return the weaponSightDistance
*/
public int getLineOfSight() {
return lineOfSight;
}
public int getOwnerId() {
return this.owner.getId();
}
/**
* @return the bulletRange
*/
public int getBulletRange() {
return bulletRange;
}
/**
* @return the owners center position
*/
public Vector2f getPos() {
return this.owner.getCenterPos();
}
public void update(TimeStep timeStep) {
if ( weaponTime > 0 ) {
weaponTime -= timeStep.getDeltaTime();
}
else if (!this.isLoaded() && totalAmmo > 0) {
reload();
}
else {
setReadyState();
}
gunSwing.update(timeStep);
}
/**
* Swing the gun for a melee attack
* @return true if we were able to swing
*/
public boolean meleeAttack() {
if(weaponState == WeaponState.READY) {
if(this.gunSwing.beginSwing()) {
setMeleeAttack();
this.gunSwing.endSwing();
return true;
}
}
return false;
}
public void doneMelee() {
//if(this.gunSwing.isSwinging())
{
this.gunSwing.endSwing();
}
}
/**
* @return true if we are currently melee attacking
*/
public boolean isMeleeAttacking() {
return this.gunSwing.isSwinging();
}
/**
* @return true if this weapon is ready to fire/use
*/
public boolean isReady() {
return weaponState == WeaponState.READY;
}
/**
* @return true if this weapon is switching
*/
public boolean isSwitchingWeapon() {
return weaponState == WeaponState.SWITCHING;
}
/**
* @return true if this weapon is currently firing
*/
public boolean isFiring() {
return weaponState == WeaponState.FIRING;
}
/**
* @return true if this weapon is currently reloading
*/
public boolean isReloading() {
return weaponState == WeaponState.RELOADING;
}
/**
* @return the bulletsInClip
*/
public int getBulletsInClip() {
return bulletsInClip;
}
/**
* @return the totalAmmo
*/
public int getTotalAmmo() {
return totalAmmo;
}
/**
* @return the clipSize
*/
public int getClipSize() {
return clipSize;
}
protected void setMeleeAttack() {
weaponState = WeaponState.MELEE_ATTACK;
weaponTime = 200;
}
protected void setReadyState() {
this.weaponState = WeaponState.READY;
}
protected void setReloadingState() {
weaponState = WeaponState.RELOADING;
}
protected void setWaitingState() {
weaponState = WeaponState.WAITING;
}
public void setSwitchingWeaponState() {
weaponState = WeaponState.SWITCHING;
weaponTime = 900;
game.emitSound(getOwnerId(), SoundType.WEAPON_SWITCH, getPos());
}
protected void setFireState() {
weaponState = WeaponState.FIRING;
// this.fired = false;
}
protected void setFireEmptyState() {
if(getState() != Weapon.WeaponState.FIRE_EMPTY) {
game.emitSound(getOwnerId(), SoundType.EMPTY_FIRE, getPos());
}
this.weaponTime = 500;
weaponState = WeaponState.FIRE_EMPTY;
// this.fired = false;
}
/**
* @return the weaponState
*/
public WeaponState getState() {
return weaponState;
}
/**
* Invoked for when the trigger is held down
* @return true if the weapon discharged
*/
public boolean beginFire() {
return false;
}
/**
* Invoked when the trigger is done being pulled.
* @return true if the weapon discharged
*/
public boolean endFire() {
return false;
}
/**
* @return true if this weapon is loaded and ready to fire
*/
public boolean canFire() {
return weaponTime <= 0 && bulletsInClip > 0;
}
/**
* @return true if this weapon is ready for a melee attack at this moment.
*/
public boolean canMelee() {
return this.gunSwing.canSwing();
}
/**
* @return true if any bullets are current in the clip
*/
public boolean isLoaded() {
return bulletsInClip > 0;
}
/**
* Calculates the velocity of the projectile discharged from the weapon.
* @param facing
* @return the velocity
*/
protected abstract Vector2f calculateVelocity(Vector2f facing);
/**
* Attempts to reload the weapon
* @return true if reloading was activated; false otherwise
*/
public boolean reload() {
if (bulletsInClip < clipSize && weaponTime <= 0) {
if(totalAmmo > 0) {
weaponTime = reloadTime;
bulletsInClip = (totalAmmo < clipSize) ? totalAmmo : clipSize;
totalAmmo -= bulletsInClip;
setReloadingState();
return true;
}
}
return false;
}
public void addAmmo(int amount) {
totalAmmo += amount;
}
/**
* @return the damageMultiplier
*/
public int getDamageMultiplier() {
return damageMultiplier;
}
/**
* @param bulletSpawnDistance the bulletSpawnDistance to set
*/
public void setBulletSpawnDistance(float bulletSpawnDistance) {
this.bulletSpawnDistance = bulletSpawnDistance;
}
/**
* @return the distance of the bullet spawn point from the owners origin
*/
public float getBulletSpawnDistance() {
return this.bulletSpawnDistance;
}
/**
* @return the position where the bullet spawns
*/
protected Vector2f newBulletPosition() {
Vector2f ownerDir = owner.getFacing();
Vector2f ownerPos = owner.getCenterPos();
Vector2f pos = new Vector2f(ownerPos.x + ownerDir.x * getBulletSpawnDistance()
, ownerPos.y + ownerDir.y * getBulletSpawnDistance());
return pos;
}
/**
* @return creates a new {@link Bullet} that is not piercing
*/
protected Bullet newBullet() {
return newBullet(false);
}
/**
* Creates a new {@link Bullet}
* @param isPiercing
* @return the {@link Bullet}
*/
protected Bullet newBullet(boolean isPiercing) {
Vector2f pos = newBulletPosition();
Vector2f vel = calculateVelocity(owner.getFacing());
final int speed = 1500 + (random.nextInt(10) * 100);
Bullet bullet = new Bullet(pos, speed, game, owner, vel, damage + getDamageMultiplier(), isPiercing);
bullet.setMaxDistance(getBulletRange());
game.addEntity(bullet);
game.getStatSystem().onBulletFired(owner);
return bullet;
}
/**
* @param rocketSpawnDistance the rocketSpawnDistance to set
*/
public void setRocketSpawnDistance(float rocketSpawnDistance) {
this.rocketSpawnDistance = rocketSpawnDistance;
}
/**
* The distance from the owners location where the rocket is spawned
* @return the distance from the owner to where the rocket is spawned
*/
public float getRocketSpawnDistance() {
return this.rocketSpawnDistance;
}
/**
* @return the position where the new Rocket is spawned
*/
protected Vector2f newRocketPosition() {
Vector2f ownerDir = owner.getFacing();
Vector2f ownerPos = owner.getCenterPos();
Vector2f pos = new Vector2f(ownerPos.x + ownerDir.x * getRocketSpawnDistance(), ownerPos.y + ownerDir.y * getRocketSpawnDistance());
return pos;
}
/**
* Spawns a new {@link Rocket}
* @return the {@link Rocket}
*/
protected Rocket newRocket() {
Vector2f pos = newRocketPosition();
Vector2f vel = calculateVelocity(owner.getFacing());
final int speed = 650;
final int splashDamage = 80;
Rocket bullet = new Rocket(pos, speed, game, owner, vel, damage, splashDamage);
game.addEntity(bullet);
game.getStatSystem().onBulletFired(owner);
return bullet;
}
/**
* @param grenadeSpawnDistance the grenadeSpawnDistance to set
*/
public void setGrenadeSpawnDistance(float grenadeSpawnDistance) {
this.grenadeSpawnDistance = grenadeSpawnDistance;
}
/**
* @return the distance the grenade spawns from the owners origin
*/
public float getGenadeSpawnDistance() {
return this.grenadeSpawnDistance;
}
/**
* Spawns a new grenade
* @param timePinPulled the time the pin was pulled (effects distance)
* @return the {@link Grenade}
*/
protected Entity newGrenade(Type grenadeType, int timePinPulled) {
Vector2f ownerDir = owner.getFacing();
Vector2f ownerPos = owner.getCenterPos();
Vector2f pos = new Vector2f(ownerPos.x + ownerDir.x * getGenadeSpawnDistance()
, ownerPos.y + ownerDir.y * getGenadeSpawnDistance());
Vector2f vel = calculateVelocity(owner.getFacing());
final int maxSpeed = 250;
int speed = Math.min(120 + (timePinPulled*7), maxSpeed);
Entity grenade = null;
switch(grenadeType) {
case NAPALM_GRENADE:
grenade = new NapalmGrenade(pos, speed, game, owner, vel, damage);
break;
case SMOKE_GRENADE:
grenade = new SmokeGrenade(pos, speed, game, owner, vel);
break;
default: {
grenade = new Grenade(pos, speed, game, owner, vel, damage);
}
}
game.addEntity(grenade);
return grenade;
}
/**
* Adds a new {@link Explosion}
* @param pos
* @param owner
* @param splashDamage
* @return the {@link Explosion}
*/
protected Explosion newExplosion(Vector2f pos, int splashDamage) {
return game.newExplosion(pos, owner, splashDamage);
}
/**
* Creates a new {@link Fire}
*
* @return the {@link Fire}
*/
protected Fire newFire() {
Vector2f pos = newBulletPosition();
Vector2f vel = calculateVelocity(owner.getFacing());
final int speed = 230 + (random.nextInt(10) * 1);
Fire fire = new Fire(pos, speed, game, owner, vel, damage);
game.addEntity(fire);
return fire;
}
/**
* Calculates the accuracy of the shot based on the owner {@link Entity}'s weaponState.
*
* <p>
* The more still you are, the more accurate you are.
*
* @param facing
* @param standardAccuracy
* @return the altered 'standardAccuracy' value
*/
protected int calculateAccuracy(Vector2f facing, int standardAccuracy) {
int newAccuracy = standardAccuracy;
switch(owner.getCurrentState()) {
case CROUCHING:
newAccuracy = standardAccuracy / 5;
break;
case IDLE:
newAccuracy = standardAccuracy / 2;
break;
case RUNNING:
newAccuracy = standardAccuracy + (standardAccuracy/4);
break;
case SPRINTING:
newAccuracy = standardAccuracy * 3;
break;
case WALKING:
newAccuracy = standardAccuracy - (standardAccuracy/4);
break;
default: newAccuracy = standardAccuracy * 10;
}
if(newAccuracy<0) {
newAccuracy = 0;
}
return newAccuracy;
}
/**
* Calculates a random velocity given a facing and a maxSpread value.
* @param facing
* @param maxSpread
* @return a rotated vector of the supplied facing randomized between -maxSpread and maxSpread
*/
protected Vector2f spread(Vector2f facing, int maxSpread) {
maxSpread = calculateAccuracy(facing, maxSpread);
double rd = Math.toRadians(random.nextInt(maxSpread));
int sd = random.nextInt(2);
return sd>0 ? facing.rotate(rd) : facing.rotate(-rd);
}
public NetWeapon getNetWeapon() {
netWeapon.ammoInClip = (byte)bulletsInClip;
netWeapon.totalAmmo = (short)totalAmmo;
netWeapon.weaponState = weaponState;
return this.netWeapon;
}
}
| tonysparks/seventh | src/seventh/game/weapons/Weapon.java | 5,415 | /*
* see license.txt
*/ | block_comment | nl | /*
* see license.txt <SUF>*/
package seventh.game.weapons;
import java.util.Random;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoObject;
import seventh.game.Game;
import seventh.game.entities.Entity;
import seventh.game.entities.Entity.Type;
import seventh.game.entities.PlayerEntity;
import seventh.game.net.NetWeapon;
import seventh.math.Vector2f;
import seventh.shared.Config;
import seventh.shared.Cons;
import seventh.shared.SoundType;
import seventh.shared.TimeStep;
/**
* Represents a Weapon.
*
* @author Tony
*
*/
public abstract class Weapon {
public enum WeaponState {
READY,
FIRING,
WAITING,
RELOADING,
FIRE_EMPTY,
MELEE_ATTACK,
SWITCHING,
UNKNOWN
;
public byte netValue() {
return (byte)ordinal();
}
private static WeaponState[] values = values();
public static WeaponState fromNet(byte value) {
if(value < 0 || value >= values.length) {
return UNKNOWN;
}
return values[value];
}
public static int numOfBits() {
return 4;
}
}
protected long weaponTime;
protected int damage;
protected long reloadTime;
protected int weaponWeight;
protected int clipSize;
protected int bulletsInClip;
protected int totalAmmo;
protected int spread;
protected int lineOfSight;
protected int bulletRange;
private WeaponState weaponState;
protected Entity owner;
protected Game game;
protected NetWeapon netWeapon;
private Random random;
private final Type type;
private GunSwing gunSwing;
private float bulletSpawnDistance,
rocketSpawnDistance,
grenadeSpawnDistance;
private int damageMultiplier;
/**
* @param game
* @param owner
* @param type
*/
public Weapon(Game game, Entity owner, Type type) {
this.type = type;
this.game = game;
this.owner = owner;
this.netWeapon = new NetWeapon();
this.netWeapon.type = type;
this.random = new Random();
this.weaponState = WeaponState.READY;
this.gunSwing = new GunSwing(game, owner);
this.bulletSpawnDistance = 15.0f;
this.rocketSpawnDistance = 40.0f;
this.grenadeSpawnDistance = 50.0f;
this.bulletRange = 5000;
}
/**
* Sets the weapons properties.
* @param weaponName
* @return the attributes if available, otherwise null
*/
protected LeoMap applyScriptAttributes(String weaponName) {
Config config = game.getConfig().getConfig();
try {
LeoObject values = config.get("weapons", weaponName);
if(values!=null&&values.isMap()) {
LeoMap attributes = values.as();
this.damage = attributes.getInt("damage");
this.reloadTime = attributes.getInt("reload_time");
this.clipSize = attributes.getInt("clip_size");
this.totalAmmo = attributes.getInt("total_ammo");
this.bulletsInClip = this.clipSize;
this.spread = attributes.getInt("spread");
this.bulletRange = attributes.getInt("bullet_range");
return attributes;
}
}
catch(LeolaRuntimeException e) {
Cons.print("*** Error reading the weapons configuration: " + e);
}
return null;
}
/**
* If this is a primary weapon or not
* @return true if this is a primary weapon
*/
public boolean isPrimary() {
return true;
}
/**
* If this weapon is huge, which prevents the user
* from taking certain actions
*
* @return true if this weapon is yuge
*/
public boolean isHeavyWeapon() {
return false;
}
/**
* @param owner the owner to set
*/
public void setOwner(Entity owner) {
this.owner = owner;
this.gunSwing.setOwner(owner);
if(owner instanceof PlayerEntity) {
this.damageMultiplier = ((PlayerEntity)owner).getDamageMultiplier();
}
}
/**
* @param bulletsInClip the bulletsInClip to set
*/
public void setBulletsInClip(int bulletsInClip) {
this.bulletsInClip = bulletsInClip;
}
/**
* @param totalAmmo the totalAmmo to set
*/
public void setTotalAmmo(int totalAmmo) {
this.totalAmmo = totalAmmo;
}
/**
* @return the type
*/
public Type getType() {
return type;
}
/**
* @return the weaponWeight in pounds
*/
public int getWeaponWeight() {
return weaponWeight;
}
/**
* @return the weaponSightDistance
*/
public int getLineOfSight() {
return lineOfSight;
}
public int getOwnerId() {
return this.owner.getId();
}
/**
* @return the bulletRange
*/
public int getBulletRange() {
return bulletRange;
}
/**
* @return the owners center position
*/
public Vector2f getPos() {
return this.owner.getCenterPos();
}
public void update(TimeStep timeStep) {
if ( weaponTime > 0 ) {
weaponTime -= timeStep.getDeltaTime();
}
else if (!this.isLoaded() && totalAmmo > 0) {
reload();
}
else {
setReadyState();
}
gunSwing.update(timeStep);
}
/**
* Swing the gun for a melee attack
* @return true if we were able to swing
*/
public boolean meleeAttack() {
if(weaponState == WeaponState.READY) {
if(this.gunSwing.beginSwing()) {
setMeleeAttack();
this.gunSwing.endSwing();
return true;
}
}
return false;
}
public void doneMelee() {
//if(this.gunSwing.isSwinging())
{
this.gunSwing.endSwing();
}
}
/**
* @return true if we are currently melee attacking
*/
public boolean isMeleeAttacking() {
return this.gunSwing.isSwinging();
}
/**
* @return true if this weapon is ready to fire/use
*/
public boolean isReady() {
return weaponState == WeaponState.READY;
}
/**
* @return true if this weapon is switching
*/
public boolean isSwitchingWeapon() {
return weaponState == WeaponState.SWITCHING;
}
/**
* @return true if this weapon is currently firing
*/
public boolean isFiring() {
return weaponState == WeaponState.FIRING;
}
/**
* @return true if this weapon is currently reloading
*/
public boolean isReloading() {
return weaponState == WeaponState.RELOADING;
}
/**
* @return the bulletsInClip
*/
public int getBulletsInClip() {
return bulletsInClip;
}
/**
* @return the totalAmmo
*/
public int getTotalAmmo() {
return totalAmmo;
}
/**
* @return the clipSize
*/
public int getClipSize() {
return clipSize;
}
protected void setMeleeAttack() {
weaponState = WeaponState.MELEE_ATTACK;
weaponTime = 200;
}
protected void setReadyState() {
this.weaponState = WeaponState.READY;
}
protected void setReloadingState() {
weaponState = WeaponState.RELOADING;
}
protected void setWaitingState() {
weaponState = WeaponState.WAITING;
}
public void setSwitchingWeaponState() {
weaponState = WeaponState.SWITCHING;
weaponTime = 900;
game.emitSound(getOwnerId(), SoundType.WEAPON_SWITCH, getPos());
}
protected void setFireState() {
weaponState = WeaponState.FIRING;
// this.fired = false;
}
protected void setFireEmptyState() {
if(getState() != Weapon.WeaponState.FIRE_EMPTY) {
game.emitSound(getOwnerId(), SoundType.EMPTY_FIRE, getPos());
}
this.weaponTime = 500;
weaponState = WeaponState.FIRE_EMPTY;
// this.fired = false;
}
/**
* @return the weaponState
*/
public WeaponState getState() {
return weaponState;
}
/**
* Invoked for when the trigger is held down
* @return true if the weapon discharged
*/
public boolean beginFire() {
return false;
}
/**
* Invoked when the trigger is done being pulled.
* @return true if the weapon discharged
*/
public boolean endFire() {
return false;
}
/**
* @return true if this weapon is loaded and ready to fire
*/
public boolean canFire() {
return weaponTime <= 0 && bulletsInClip > 0;
}
/**
* @return true if this weapon is ready for a melee attack at this moment.
*/
public boolean canMelee() {
return this.gunSwing.canSwing();
}
/**
* @return true if any bullets are current in the clip
*/
public boolean isLoaded() {
return bulletsInClip > 0;
}
/**
* Calculates the velocity of the projectile discharged from the weapon.
* @param facing
* @return the velocity
*/
protected abstract Vector2f calculateVelocity(Vector2f facing);
/**
* Attempts to reload the weapon
* @return true if reloading was activated; false otherwise
*/
public boolean reload() {
if (bulletsInClip < clipSize && weaponTime <= 0) {
if(totalAmmo > 0) {
weaponTime = reloadTime;
bulletsInClip = (totalAmmo < clipSize) ? totalAmmo : clipSize;
totalAmmo -= bulletsInClip;
setReloadingState();
return true;
}
}
return false;
}
public void addAmmo(int amount) {
totalAmmo += amount;
}
/**
* @return the damageMultiplier
*/
public int getDamageMultiplier() {
return damageMultiplier;
}
/**
* @param bulletSpawnDistance the bulletSpawnDistance to set
*/
public void setBulletSpawnDistance(float bulletSpawnDistance) {
this.bulletSpawnDistance = bulletSpawnDistance;
}
/**
* @return the distance of the bullet spawn point from the owners origin
*/
public float getBulletSpawnDistance() {
return this.bulletSpawnDistance;
}
/**
* @return the position where the bullet spawns
*/
protected Vector2f newBulletPosition() {
Vector2f ownerDir = owner.getFacing();
Vector2f ownerPos = owner.getCenterPos();
Vector2f pos = new Vector2f(ownerPos.x + ownerDir.x * getBulletSpawnDistance()
, ownerPos.y + ownerDir.y * getBulletSpawnDistance());
return pos;
}
/**
* @return creates a new {@link Bullet} that is not piercing
*/
protected Bullet newBullet() {
return newBullet(false);
}
/**
* Creates a new {@link Bullet}
* @param isPiercing
* @return the {@link Bullet}
*/
protected Bullet newBullet(boolean isPiercing) {
Vector2f pos = newBulletPosition();
Vector2f vel = calculateVelocity(owner.getFacing());
final int speed = 1500 + (random.nextInt(10) * 100);
Bullet bullet = new Bullet(pos, speed, game, owner, vel, damage + getDamageMultiplier(), isPiercing);
bullet.setMaxDistance(getBulletRange());
game.addEntity(bullet);
game.getStatSystem().onBulletFired(owner);
return bullet;
}
/**
* @param rocketSpawnDistance the rocketSpawnDistance to set
*/
public void setRocketSpawnDistance(float rocketSpawnDistance) {
this.rocketSpawnDistance = rocketSpawnDistance;
}
/**
* The distance from the owners location where the rocket is spawned
* @return the distance from the owner to where the rocket is spawned
*/
public float getRocketSpawnDistance() {
return this.rocketSpawnDistance;
}
/**
* @return the position where the new Rocket is spawned
*/
protected Vector2f newRocketPosition() {
Vector2f ownerDir = owner.getFacing();
Vector2f ownerPos = owner.getCenterPos();
Vector2f pos = new Vector2f(ownerPos.x + ownerDir.x * getRocketSpawnDistance(), ownerPos.y + ownerDir.y * getRocketSpawnDistance());
return pos;
}
/**
* Spawns a new {@link Rocket}
* @return the {@link Rocket}
*/
protected Rocket newRocket() {
Vector2f pos = newRocketPosition();
Vector2f vel = calculateVelocity(owner.getFacing());
final int speed = 650;
final int splashDamage = 80;
Rocket bullet = new Rocket(pos, speed, game, owner, vel, damage, splashDamage);
game.addEntity(bullet);
game.getStatSystem().onBulletFired(owner);
return bullet;
}
/**
* @param grenadeSpawnDistance the grenadeSpawnDistance to set
*/
public void setGrenadeSpawnDistance(float grenadeSpawnDistance) {
this.grenadeSpawnDistance = grenadeSpawnDistance;
}
/**
* @return the distance the grenade spawns from the owners origin
*/
public float getGenadeSpawnDistance() {
return this.grenadeSpawnDistance;
}
/**
* Spawns a new grenade
* @param timePinPulled the time the pin was pulled (effects distance)
* @return the {@link Grenade}
*/
protected Entity newGrenade(Type grenadeType, int timePinPulled) {
Vector2f ownerDir = owner.getFacing();
Vector2f ownerPos = owner.getCenterPos();
Vector2f pos = new Vector2f(ownerPos.x + ownerDir.x * getGenadeSpawnDistance()
, ownerPos.y + ownerDir.y * getGenadeSpawnDistance());
Vector2f vel = calculateVelocity(owner.getFacing());
final int maxSpeed = 250;
int speed = Math.min(120 + (timePinPulled*7), maxSpeed);
Entity grenade = null;
switch(grenadeType) {
case NAPALM_GRENADE:
grenade = new NapalmGrenade(pos, speed, game, owner, vel, damage);
break;
case SMOKE_GRENADE:
grenade = new SmokeGrenade(pos, speed, game, owner, vel);
break;
default: {
grenade = new Grenade(pos, speed, game, owner, vel, damage);
}
}
game.addEntity(grenade);
return grenade;
}
/**
* Adds a new {@link Explosion}
* @param pos
* @param owner
* @param splashDamage
* @return the {@link Explosion}
*/
protected Explosion newExplosion(Vector2f pos, int splashDamage) {
return game.newExplosion(pos, owner, splashDamage);
}
/**
* Creates a new {@link Fire}
*
* @return the {@link Fire}
*/
protected Fire newFire() {
Vector2f pos = newBulletPosition();
Vector2f vel = calculateVelocity(owner.getFacing());
final int speed = 230 + (random.nextInt(10) * 1);
Fire fire = new Fire(pos, speed, game, owner, vel, damage);
game.addEntity(fire);
return fire;
}
/**
* Calculates the accuracy of the shot based on the owner {@link Entity}'s weaponState.
*
* <p>
* The more still you are, the more accurate you are.
*
* @param facing
* @param standardAccuracy
* @return the altered 'standardAccuracy' value
*/
protected int calculateAccuracy(Vector2f facing, int standardAccuracy) {
int newAccuracy = standardAccuracy;
switch(owner.getCurrentState()) {
case CROUCHING:
newAccuracy = standardAccuracy / 5;
break;
case IDLE:
newAccuracy = standardAccuracy / 2;
break;
case RUNNING:
newAccuracy = standardAccuracy + (standardAccuracy/4);
break;
case SPRINTING:
newAccuracy = standardAccuracy * 3;
break;
case WALKING:
newAccuracy = standardAccuracy - (standardAccuracy/4);
break;
default: newAccuracy = standardAccuracy * 10;
}
if(newAccuracy<0) {
newAccuracy = 0;
}
return newAccuracy;
}
/**
* Calculates a random velocity given a facing and a maxSpread value.
* @param facing
* @param maxSpread
* @return a rotated vector of the supplied facing randomized between -maxSpread and maxSpread
*/
protected Vector2f spread(Vector2f facing, int maxSpread) {
maxSpread = calculateAccuracy(facing, maxSpread);
double rd = Math.toRadians(random.nextInt(maxSpread));
int sd = random.nextInt(2);
return sd>0 ? facing.rotate(rd) : facing.rotate(-rd);
}
public NetWeapon getNetWeapon() {
netWeapon.ammoInClip = (byte)bulletsInClip;
netWeapon.totalAmmo = (short)totalAmmo;
netWeapon.weaponState = weaponState;
return this.netWeapon;
}
}
|
21770_0 | package sesh.mood.chessGame.domain;
public class Piece {
//eerste zet bepalen
private Boolean initialMove = false;
private int initialMovePos;
//resterende zet
private int MovePos;
//bewegingsrichtingen
private Boolean allowedFileUp = false;
private Boolean allowedFileDown = false;
private Boolean allowedDiagonalUp = false;
private Boolean allowedDiagonalDown = false;
private Boolean allowedRankLeft = false;
private Boolean allowedRankRight = false;
//aantal max toegelaten posities
private int fileUp;
private int fileDown;
private int diagonalUp;
private int diagonalDown;
private int rankLeft;
private int rankRight;
//identifier
private String name;
private int id;
private String unicode;
public Piece(Boolean initialMove, int initialMovePos, int MovePos, Boolean allowedFileUp, Boolean allowedFileDown, Boolean allowedDiagonalUp, Boolean allowedDiagonalDown, Boolean allowedRankLeft, Boolean allowedRankRight, int fileUp, int fileDown, int diagonalUp, int diagonalDown, int rankLeft, int rankRight, String name, int id, String unicode) {
this.initialMove = initialMove;
this.initialMovePos = initialMovePos;
this.MovePos = MovePos;
this.allowedFileUp = allowedFileUp;
this.allowedFileDown = allowedFileDown;
this.allowedDiagonalUp = allowedDiagonalUp;
this.allowedDiagonalDown = allowedDiagonalDown;
this.allowedRankLeft = allowedRankLeft;
this.allowedRankRight = allowedRankRight;
this.fileUp = fileUp;
this.fileDown = fileDown;
this.diagonalUp = diagonalUp;
this.diagonalDown = diagonalDown;
this.rankLeft = rankLeft;
this.rankRight = rankRight;
this.name = name;
this.id = id;
this.unicode = unicode;
}
} | toonvank/terminalChessJava | src/main/java/sesh/mood/chessGame/domain/Piece.java | 505 | //eerste zet bepalen | line_comment | nl | package sesh.mood.chessGame.domain;
public class Piece {
//eerste zet<SUF>
private Boolean initialMove = false;
private int initialMovePos;
//resterende zet
private int MovePos;
//bewegingsrichtingen
private Boolean allowedFileUp = false;
private Boolean allowedFileDown = false;
private Boolean allowedDiagonalUp = false;
private Boolean allowedDiagonalDown = false;
private Boolean allowedRankLeft = false;
private Boolean allowedRankRight = false;
//aantal max toegelaten posities
private int fileUp;
private int fileDown;
private int diagonalUp;
private int diagonalDown;
private int rankLeft;
private int rankRight;
//identifier
private String name;
private int id;
private String unicode;
public Piece(Boolean initialMove, int initialMovePos, int MovePos, Boolean allowedFileUp, Boolean allowedFileDown, Boolean allowedDiagonalUp, Boolean allowedDiagonalDown, Boolean allowedRankLeft, Boolean allowedRankRight, int fileUp, int fileDown, int diagonalUp, int diagonalDown, int rankLeft, int rankRight, String name, int id, String unicode) {
this.initialMove = initialMove;
this.initialMovePos = initialMovePos;
this.MovePos = MovePos;
this.allowedFileUp = allowedFileUp;
this.allowedFileDown = allowedFileDown;
this.allowedDiagonalUp = allowedDiagonalUp;
this.allowedDiagonalDown = allowedDiagonalDown;
this.allowedRankLeft = allowedRankLeft;
this.allowedRankRight = allowedRankRight;
this.fileUp = fileUp;
this.fileDown = fileDown;
this.diagonalUp = diagonalUp;
this.diagonalDown = diagonalDown;
this.rankLeft = rankLeft;
this.rankRight = rankRight;
this.name = name;
this.id = id;
this.unicode = unicode;
}
} |
155089_1 | package nl.topicus.topical;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import com.google.gson.*;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.availability.AvailabilityData;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.LegacyFreeBusyStatus;
import microsoft.exchange.webservices.data.core.response.AttendeeAvailability;
import microsoft.exchange.webservices.data.core.response.ServiceResponseCollection;
import microsoft.exchange.webservices.data.core.service.item.Appointment;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.misc.availability.AttendeeInfo;
import microsoft.exchange.webservices.data.misc.availability.GetUserAvailabilityResults;
import microsoft.exchange.webservices.data.misc.availability.TimeWindow;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import spark.Spark;
public class TopicalBackend {
private String domain;
private String username;
private String password;
private String url;
public List<String> rooms;
private ExchangeService service;
public static void main(String[] args) {
if (args.length < 5) {
System.out
.println("Usage: [domain] [username] [password] [url] [room1] [room2]");
} else {
List<String> argsList = Arrays.asList(args);
new TopicalBackend(argsList.get(0), argsList.get(1), argsList.get(2),
argsList.get(3), argsList.subList(4, argsList.size()));
}
}
public TopicalBackend(String domain, String username, String password,
String url, List<String> rooms) {
this.domain = domain;
this.username = username;
this.password = password;
this.url = url;
this.rooms = rooms;
Gson gson = new GsonBuilder().registerTypeAdapter(Instant.class,
new JsonSerializer<Instant>() {
@Override
public JsonElement serialize(Instant instant, Type type,
JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(instant.toString());
}
}).create();
Spark.get("/rooms", (req, res) -> {
res.type("application/json");
return rooms;
}, gson::toJson);
Spark.get("/events/:room", (req, res) -> {
res.type("application/json");
return listEventsToday(req.params(":room"));
}, gson::toJson);
Spark.get("claim/:room", (req, res) -> {
try {
createAppointment(req.params(":room"));
return "claim succesvol";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
});
Spark.after((request, response) -> {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "GET, OPTIONS");
});
}
// Exchange-server vind het niet fijn om meerdere requests tegelijk te ontvangen. Levert een
// "The remote server returned an error: (401)Unauthorized" op - daarom deze methode synchronized gemaakt.
private synchronized List<SimpleEvent> listEventsToday(String adres) {
AttendeeInfo attendee = AttendeeInfo.getAttendeeInfoFromString(adres);
List<AttendeeInfo> attendees = Arrays.asList(attendee);
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR, 0);
today.set(Calendar.MINUTE, 0);
Calendar tomorrow = (Calendar) today.clone();
tomorrow.add(Calendar.DATE, 1);
TimeWindow timeWindow = new TimeWindow(today.getTime(),
tomorrow.getTime());
try {
ExchangeService service = getService();
GetUserAvailabilityResults userAvailability = service
.getUserAvailability(attendees, timeWindow,
AvailabilityData.FreeBusy);
ServiceResponseCollection<AttendeeAvailability> attendeesAvailability = userAvailability
.getAttendeesAvailability();
AttendeeAvailability availability = attendeesAvailability
.iterator().next();
return availability
.getCalendarEvents()
.stream()
.filter(e -> e.getFreeBusyStatus().equals(
LegacyFreeBusyStatus.Busy))
.map(e -> new SimpleEvent(e.getStartTime(), e.getEndTime(),
e.getDetails().getSubject()))
.collect(Collectors.toList());
} catch (Exception e) {
e.printStackTrace();
}
return new ArrayList<>();
}
/**
* Creates an appointment starting now and ending within an hour or when the
* next appointment starts, whichever comes first.
*
* @throws Exception
* if the room is currently occupied or the exchange server
* throws an exception
*/
private void createAppointment(String adres) throws Exception {
List<SimpleEvent> events = listEventsToday(adres);
SimpleEvent currentEvent = getCurrentEvent(events);
if (currentEvent != null) {
throw new Exception(
"Room is currently not available. Subject of current event: "
+ currentEvent.getSubject());
}
Appointment appointment = new Appointment(getService());
appointment.setSubject("Vergaderruimte geclaimed via Topical");
appointment
.setBody(MessageBody
.getMessageBodyFromText("Deze afspraak is ingeschoten vanuit Topical"));
Instant nu = Instant.now();
appointment.setStart(Date.from(nu.atZone(ZoneId.systemDefault())
.toInstant()));
Instant inOneHour = nu.plus(Duration.ofHours(1));
SimpleEvent nextEvent = getNextEvent(events);
if (nextEvent.getStartTime().isBefore(inOneHour)) {
appointment.setEnd(Date.from(nextEvent.getStartTime()
.atZone(ZoneId.systemDefault()).toInstant()));
} else {
appointment.setEnd(Date.from(inOneHour.atZone(
ZoneId.systemDefault()).toInstant()));
}
appointment.getRequiredAttendees().add(adres);
appointment.save();
}
private SimpleEvent getCurrentEvent(List<SimpleEvent> events) {
Instant nu = Instant.now();
List<SimpleEvent> currentEvents = events
.stream()
.filter(e -> e.getStartTime().isBefore(nu)
&& e.getEndTime().isAfter(nu))
.collect(Collectors.toList());
return currentEvents.size() > 0 ? currentEvents.get(0) : null;
}
private SimpleEvent getNextEvent(List<SimpleEvent> events) {
Instant nu = Instant.now();
List<SimpleEvent> upcomingEvents = events.stream()
.filter(e -> e.getStartTime().isAfter(nu))
.collect(Collectors.toList());
return upcomingEvents.size() > 0 ? upcomingEvents.get(0) : null;
}
private ExchangeService getService() {
if(service == null)
{
try {
service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.setCredentials(new WebCredentials(username, password, domain));
service.setUrl(new URI(url));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return service;
}
} | topicusonderwijs/topical | backend/src/main/java/nl/topicus/topical/TopicalBackend.java | 2,208 | // "The remote server returned an error: (401)Unauthorized" op - daarom deze methode synchronized gemaakt. | line_comment | nl | package nl.topicus.topical;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import com.google.gson.*;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.availability.AvailabilityData;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.LegacyFreeBusyStatus;
import microsoft.exchange.webservices.data.core.response.AttendeeAvailability;
import microsoft.exchange.webservices.data.core.response.ServiceResponseCollection;
import microsoft.exchange.webservices.data.core.service.item.Appointment;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.misc.availability.AttendeeInfo;
import microsoft.exchange.webservices.data.misc.availability.GetUserAvailabilityResults;
import microsoft.exchange.webservices.data.misc.availability.TimeWindow;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import spark.Spark;
public class TopicalBackend {
private String domain;
private String username;
private String password;
private String url;
public List<String> rooms;
private ExchangeService service;
public static void main(String[] args) {
if (args.length < 5) {
System.out
.println("Usage: [domain] [username] [password] [url] [room1] [room2]");
} else {
List<String> argsList = Arrays.asList(args);
new TopicalBackend(argsList.get(0), argsList.get(1), argsList.get(2),
argsList.get(3), argsList.subList(4, argsList.size()));
}
}
public TopicalBackend(String domain, String username, String password,
String url, List<String> rooms) {
this.domain = domain;
this.username = username;
this.password = password;
this.url = url;
this.rooms = rooms;
Gson gson = new GsonBuilder().registerTypeAdapter(Instant.class,
new JsonSerializer<Instant>() {
@Override
public JsonElement serialize(Instant instant, Type type,
JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(instant.toString());
}
}).create();
Spark.get("/rooms", (req, res) -> {
res.type("application/json");
return rooms;
}, gson::toJson);
Spark.get("/events/:room", (req, res) -> {
res.type("application/json");
return listEventsToday(req.params(":room"));
}, gson::toJson);
Spark.get("claim/:room", (req, res) -> {
try {
createAppointment(req.params(":room"));
return "claim succesvol";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
});
Spark.after((request, response) -> {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Methods", "GET, OPTIONS");
});
}
// Exchange-server vind het niet fijn om meerdere requests tegelijk te ontvangen. Levert een
// "The remote<SUF>
private synchronized List<SimpleEvent> listEventsToday(String adres) {
AttendeeInfo attendee = AttendeeInfo.getAttendeeInfoFromString(adres);
List<AttendeeInfo> attendees = Arrays.asList(attendee);
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR, 0);
today.set(Calendar.MINUTE, 0);
Calendar tomorrow = (Calendar) today.clone();
tomorrow.add(Calendar.DATE, 1);
TimeWindow timeWindow = new TimeWindow(today.getTime(),
tomorrow.getTime());
try {
ExchangeService service = getService();
GetUserAvailabilityResults userAvailability = service
.getUserAvailability(attendees, timeWindow,
AvailabilityData.FreeBusy);
ServiceResponseCollection<AttendeeAvailability> attendeesAvailability = userAvailability
.getAttendeesAvailability();
AttendeeAvailability availability = attendeesAvailability
.iterator().next();
return availability
.getCalendarEvents()
.stream()
.filter(e -> e.getFreeBusyStatus().equals(
LegacyFreeBusyStatus.Busy))
.map(e -> new SimpleEvent(e.getStartTime(), e.getEndTime(),
e.getDetails().getSubject()))
.collect(Collectors.toList());
} catch (Exception e) {
e.printStackTrace();
}
return new ArrayList<>();
}
/**
* Creates an appointment starting now and ending within an hour or when the
* next appointment starts, whichever comes first.
*
* @throws Exception
* if the room is currently occupied or the exchange server
* throws an exception
*/
private void createAppointment(String adres) throws Exception {
List<SimpleEvent> events = listEventsToday(adres);
SimpleEvent currentEvent = getCurrentEvent(events);
if (currentEvent != null) {
throw new Exception(
"Room is currently not available. Subject of current event: "
+ currentEvent.getSubject());
}
Appointment appointment = new Appointment(getService());
appointment.setSubject("Vergaderruimte geclaimed via Topical");
appointment
.setBody(MessageBody
.getMessageBodyFromText("Deze afspraak is ingeschoten vanuit Topical"));
Instant nu = Instant.now();
appointment.setStart(Date.from(nu.atZone(ZoneId.systemDefault())
.toInstant()));
Instant inOneHour = nu.plus(Duration.ofHours(1));
SimpleEvent nextEvent = getNextEvent(events);
if (nextEvent.getStartTime().isBefore(inOneHour)) {
appointment.setEnd(Date.from(nextEvent.getStartTime()
.atZone(ZoneId.systemDefault()).toInstant()));
} else {
appointment.setEnd(Date.from(inOneHour.atZone(
ZoneId.systemDefault()).toInstant()));
}
appointment.getRequiredAttendees().add(adres);
appointment.save();
}
private SimpleEvent getCurrentEvent(List<SimpleEvent> events) {
Instant nu = Instant.now();
List<SimpleEvent> currentEvents = events
.stream()
.filter(e -> e.getStartTime().isBefore(nu)
&& e.getEndTime().isAfter(nu))
.collect(Collectors.toList());
return currentEvents.size() > 0 ? currentEvents.get(0) : null;
}
private SimpleEvent getNextEvent(List<SimpleEvent> events) {
Instant nu = Instant.now();
List<SimpleEvent> upcomingEvents = events.stream()
.filter(e -> e.getStartTime().isAfter(nu))
.collect(Collectors.toList());
return upcomingEvents.size() > 0 ? upcomingEvents.get(0) : null;
}
private ExchangeService getService() {
if(service == null)
{
try {
service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.setCredentials(new WebCredentials(username, password, domain));
service.setUrl(new URI(url));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return service;
}
} |
30217_2 | package nl.topicus.eduarte.entities.resultaatstructuur;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import nl.topicus.cobra.modelsv2.DefaultModelManager;
import nl.topicus.cobra.modelsv2.ModelManager;
import nl.topicus.cobra.templates.annotations.Exportable;
import nl.topicus.cobra.util.StringUtil;
import nl.topicus.cobra.web.components.form.AutoForm;
import nl.topicus.eduarte.entities.codenaamactief.CodeNaamActiefInstellingEntiteit;
import nl.topicus.eduarte.entities.landelijk.Cohort;
import nl.topicus.eduarte.entities.onderwijsproduct.Onderwijsproduct;
import nl.topicus.eduarte.entities.personen.Medewerker;
import nl.topicus.eduarte.entities.resultaatstructuur.Toets.SoortToets;
import nl.topicus.eduarte.entities.resultaatstructuur.Toets.ToetsCodePathMode;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Index;
/**
* Een onderwijsproduct dat een summatief resultaat levert heeft een resultaatstructuur
* per cohort.
*
* @author loite
*/
@Exportable()
@Entity()
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Inrichting")
@javax.persistence.Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"code",
"organisatie", "cohort", "onderwijsproduct"})})
public class Resultaatstructuur extends CodeNaamActiefInstellingEntiteit
{
private static final long serialVersionUID = 1L;
public static final String RES_SUMMATIEF = "RES_SUMMATIEF";
public static final String RES_FORMATIEF = "RES_FORMATIEF";
public static final String VERWIJDEREN = "_VERWIJDEREN";
public static final String KOPIEREN = "_KOPIEREN";
public static final String IMPORTEREN = "_IMPORTEREN";
public static final String ANDERMANS_STRUCTUREN = "ANDERMANS_STRUCTUREN";
public static enum Status
{
IN_HERBEREKENING,
BESCHIKBAAR,
IN_ONDERHOUD,
FOUTIEF;
@Override
public String toString()
{
return StringUtil.firstCharUppercase(StringUtil.convertCamelCase(name().toLowerCase()));
}
}
public static enum Type
{
SUMMATIEF(RES_SUMMATIEF),
FORMATIEF(RES_FORMATIEF);
Type(String securityId)
{
this.securityId = securityId;
}
public String securityId;
public String getSecurityId()
{
return securityId;
}
@Override
public String toString()
{
return StringUtil.firstCharUppercase(name());
}
}
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private Type type;
@Column(nullable = false)
private boolean specifiek;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = true, name = "categorie")
@Index(name = "idx_Resstructuur_categorie")
@AutoForm(required = true, htmlClasses = "unit_max")
private ResultaatstructuurCategorie categorie;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, name = "cohort")
@Index(name = "idx_Resstructuur_cohort")
private Cohort cohort;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, name = "onderwijsproduct")
@Index(name = "idx_Resstructuur_ondprod")
@AutoForm(htmlClasses = "unit_max")
private Onderwijsproduct onderwijsproduct;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = true, name = "auteur")
@Index(name = "idx_Resstructuur_auteur")
@AutoForm(readOnly = true)
private Medewerker auteur;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private Status status;
/**
* Nullable omdat het een 1-op-1 relatie is die eigenlijk aan allebei kanten not-null
* zouden moeten zijn. Dit is echter niet mogelijk omdat de twee records dan
* tegelijkertijd inserted zouden moeten worden.
*/
@Basic(optional = false)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = true, name = "eindresultaat")
@Index(name = "idx_Resstructuur_eindres")
private Toets eindresultaat;
/**
* Alle toetsen waar de resultaatstructuur uit bestaat
*/
@OneToMany(fetch = FetchType.LAZY, mappedBy = "resultaatstructuur")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Instelling")
@BatchSize(size = 100)
private List<Toets> toetsen = new ArrayList<Toets>();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "resultaatstructuur")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Instelling")
private List<DeelnemerResultaatVersie> versies = new ArrayList<DeelnemerResultaatVersie>();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "resultaatstructuur")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Instelling")
private List<ResultaatstructuurMedewerker> medewerkers =
new ArrayList<ResultaatstructuurMedewerker>();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "resultaatstructuur")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Instelling")
private List<ResultaatstructuurDeelnemer> deelnemers =
new ArrayList<ResultaatstructuurDeelnemer>();
public Resultaatstructuur()
{
}
public Resultaatstructuur(Onderwijsproduct onderwijsproduct, Cohort cohort)
{
setOnderwijsproduct(onderwijsproduct);
setCohort(cohort);
}
public Type getType()
{
return type;
}
public void setType(Type type)
{
this.type = type;
}
public boolean isSpecifiek()
{
return specifiek;
}
public void setSpecifiek(boolean specifiek)
{
this.specifiek = specifiek;
}
public ResultaatstructuurCategorie getCategorie()
{
return categorie;
}
public void setCategorie(ResultaatstructuurCategorie categorie)
{
this.categorie = categorie;
}
public Cohort getCohort()
{
return cohort;
}
public void setCohort(Cohort cohort)
{
this.cohort = cohort;
}
@Exportable()
public Onderwijsproduct getOnderwijsproduct()
{
return onderwijsproduct;
}
public void setOnderwijsproduct(Onderwijsproduct onderwijsproduct)
{
this.onderwijsproduct = onderwijsproduct;
}
public Medewerker getAuteur()
{
return auteur;
}
public void setAuteur(Medewerker auteur)
{
this.auteur = auteur;
}
public Toets getEindresultaat()
{
return eindresultaat;
}
public void setEindresultaat(Toets eindresultaat)
{
this.eindresultaat = eindresultaat;
}
public void setToetsen(List<Toets> toetsen)
{
this.toetsen = toetsen;
}
public List<Toets> getToetsen()
{
return toetsen;
}
public int getDepth()
{
int ret = 0;
for (Toets curToets : getToetsen())
{
int curDepth = curToets.getDepth();
if (curDepth > ret)
ret = curDepth;
}
return ret + 1;
}
public void setStatus(Status status)
{
this.status = status;
}
public Status getStatus()
{
return status;
}
public List<DeelnemerResultaatVersie> getVersies()
{
return versies;
}
public void setVersies(List<DeelnemerResultaatVersie> versies)
{
this.versies = versies;
}
public List<ResultaatstructuurMedewerker> getMedewerkers()
{
return medewerkers;
}
public void setMedewerkers(List<ResultaatstructuurMedewerker> medewerkers)
{
this.medewerkers = medewerkers;
}
public List<ResultaatstructuurDeelnemer> getDeelnemers()
{
return deelnemers;
}
public void setDeelnemers(List<ResultaatstructuurDeelnemer> deelnemers)
{
this.deelnemers = deelnemers;
}
public boolean isBewerkbaar()
{
return status.equals(Status.IN_ONDERHOUD);
}
public boolean isBeschikbaar()
{
return status.equals(Status.BESCHIKBAAR);
}
public boolean isInBerekening()
{
return status.equals(Status.IN_HERBEREKENING);
}
/**
* @return de toets met het gegeven toetscodepad. Voorbeeld van een toetscodepad:
* EIND/SE/309
*/
@Exportable
public Toets findToets(String toetsCodePath)
{
for (Toets curToets : getToetsen())
if (curToets.getToetscodePath().equals(toetsCodePath))
return curToets;
return null;
}
public Toets findToets(String toetsCodePath, ToetsCodePathMode mode)
{
for (Toets curToets : getToetsen())
if (curToets.getToetscodePath(mode).equals(toetsCodePath))
return curToets;
return null;
}
/**
* @return De unieke toets binnen deze resultaatstructuur van de gegeven soort. Soort
* moet aangegeven zijn als uniek binnen de resultaatstructuur.
*/
public Toets getToets(SoortToets soort)
{
if (!soort.isUniekBinnenResultaatstructuur())
throw new IllegalArgumentException("Soort moet uniek binnen de resultaatstructuur zijn");
if (getEindresultaat() == null)
return null;
return getEindresultaat().getChild(soort);
}
@Override
public String toString()
{
return "(" + getCohort() + ") " + onderwijsproduct;
}
public boolean isEindResultaatCompleet()
{
return getEindresultaat().getCode() != null && getEindresultaat().getNaam() != null
&& getEindresultaat().getSchaal() != null
&& getEindresultaat().getScoreschaal() != null;
}
public static ModelManager createModelManager()
{
return new DefaultModelManager(ResultaatstructuurDeelnemer.class,
ResultaatstructuurMedewerker.class, Scoreschaalwaarde.class, ToetsVerwijzing.class,
PersoonlijkeToetscode.class, Toets.class, Resultaatstructuur.class);
}
public boolean isGekoppeld(Medewerker medewerker)
{
if (!isSpecifiek())
return true;
for (ResultaatstructuurMedewerker curMedewerker : getMedewerkers())
if (curMedewerker.getMedewerker().equals(medewerker))
return true;
return false;
}
}
| topicusonderwijs/tribe-krd-opensource | eduarte/core/src/main/java/nl/topicus/eduarte/entities/resultaatstructuur/Resultaatstructuur.java | 3,505 | /**
* Alle toetsen waar de resultaatstructuur uit bestaat
*/ | block_comment | nl | package nl.topicus.eduarte.entities.resultaatstructuur;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import nl.topicus.cobra.modelsv2.DefaultModelManager;
import nl.topicus.cobra.modelsv2.ModelManager;
import nl.topicus.cobra.templates.annotations.Exportable;
import nl.topicus.cobra.util.StringUtil;
import nl.topicus.cobra.web.components.form.AutoForm;
import nl.topicus.eduarte.entities.codenaamactief.CodeNaamActiefInstellingEntiteit;
import nl.topicus.eduarte.entities.landelijk.Cohort;
import nl.topicus.eduarte.entities.onderwijsproduct.Onderwijsproduct;
import nl.topicus.eduarte.entities.personen.Medewerker;
import nl.topicus.eduarte.entities.resultaatstructuur.Toets.SoortToets;
import nl.topicus.eduarte.entities.resultaatstructuur.Toets.ToetsCodePathMode;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Index;
/**
* Een onderwijsproduct dat een summatief resultaat levert heeft een resultaatstructuur
* per cohort.
*
* @author loite
*/
@Exportable()
@Entity()
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Inrichting")
@javax.persistence.Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"code",
"organisatie", "cohort", "onderwijsproduct"})})
public class Resultaatstructuur extends CodeNaamActiefInstellingEntiteit
{
private static final long serialVersionUID = 1L;
public static final String RES_SUMMATIEF = "RES_SUMMATIEF";
public static final String RES_FORMATIEF = "RES_FORMATIEF";
public static final String VERWIJDEREN = "_VERWIJDEREN";
public static final String KOPIEREN = "_KOPIEREN";
public static final String IMPORTEREN = "_IMPORTEREN";
public static final String ANDERMANS_STRUCTUREN = "ANDERMANS_STRUCTUREN";
public static enum Status
{
IN_HERBEREKENING,
BESCHIKBAAR,
IN_ONDERHOUD,
FOUTIEF;
@Override
public String toString()
{
return StringUtil.firstCharUppercase(StringUtil.convertCamelCase(name().toLowerCase()));
}
}
public static enum Type
{
SUMMATIEF(RES_SUMMATIEF),
FORMATIEF(RES_FORMATIEF);
Type(String securityId)
{
this.securityId = securityId;
}
public String securityId;
public String getSecurityId()
{
return securityId;
}
@Override
public String toString()
{
return StringUtil.firstCharUppercase(name());
}
}
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private Type type;
@Column(nullable = false)
private boolean specifiek;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = true, name = "categorie")
@Index(name = "idx_Resstructuur_categorie")
@AutoForm(required = true, htmlClasses = "unit_max")
private ResultaatstructuurCategorie categorie;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, name = "cohort")
@Index(name = "idx_Resstructuur_cohort")
private Cohort cohort;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, name = "onderwijsproduct")
@Index(name = "idx_Resstructuur_ondprod")
@AutoForm(htmlClasses = "unit_max")
private Onderwijsproduct onderwijsproduct;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = true, name = "auteur")
@Index(name = "idx_Resstructuur_auteur")
@AutoForm(readOnly = true)
private Medewerker auteur;
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private Status status;
/**
* Nullable omdat het een 1-op-1 relatie is die eigenlijk aan allebei kanten not-null
* zouden moeten zijn. Dit is echter niet mogelijk omdat de twee records dan
* tegelijkertijd inserted zouden moeten worden.
*/
@Basic(optional = false)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = true, name = "eindresultaat")
@Index(name = "idx_Resstructuur_eindres")
private Toets eindresultaat;
/**
* Alle toetsen waar<SUF>*/
@OneToMany(fetch = FetchType.LAZY, mappedBy = "resultaatstructuur")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Instelling")
@BatchSize(size = 100)
private List<Toets> toetsen = new ArrayList<Toets>();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "resultaatstructuur")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Instelling")
private List<DeelnemerResultaatVersie> versies = new ArrayList<DeelnemerResultaatVersie>();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "resultaatstructuur")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Instelling")
private List<ResultaatstructuurMedewerker> medewerkers =
new ArrayList<ResultaatstructuurMedewerker>();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "resultaatstructuur")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Instelling")
private List<ResultaatstructuurDeelnemer> deelnemers =
new ArrayList<ResultaatstructuurDeelnemer>();
public Resultaatstructuur()
{
}
public Resultaatstructuur(Onderwijsproduct onderwijsproduct, Cohort cohort)
{
setOnderwijsproduct(onderwijsproduct);
setCohort(cohort);
}
public Type getType()
{
return type;
}
public void setType(Type type)
{
this.type = type;
}
public boolean isSpecifiek()
{
return specifiek;
}
public void setSpecifiek(boolean specifiek)
{
this.specifiek = specifiek;
}
public ResultaatstructuurCategorie getCategorie()
{
return categorie;
}
public void setCategorie(ResultaatstructuurCategorie categorie)
{
this.categorie = categorie;
}
public Cohort getCohort()
{
return cohort;
}
public void setCohort(Cohort cohort)
{
this.cohort = cohort;
}
@Exportable()
public Onderwijsproduct getOnderwijsproduct()
{
return onderwijsproduct;
}
public void setOnderwijsproduct(Onderwijsproduct onderwijsproduct)
{
this.onderwijsproduct = onderwijsproduct;
}
public Medewerker getAuteur()
{
return auteur;
}
public void setAuteur(Medewerker auteur)
{
this.auteur = auteur;
}
public Toets getEindresultaat()
{
return eindresultaat;
}
public void setEindresultaat(Toets eindresultaat)
{
this.eindresultaat = eindresultaat;
}
public void setToetsen(List<Toets> toetsen)
{
this.toetsen = toetsen;
}
public List<Toets> getToetsen()
{
return toetsen;
}
public int getDepth()
{
int ret = 0;
for (Toets curToets : getToetsen())
{
int curDepth = curToets.getDepth();
if (curDepth > ret)
ret = curDepth;
}
return ret + 1;
}
public void setStatus(Status status)
{
this.status = status;
}
public Status getStatus()
{
return status;
}
public List<DeelnemerResultaatVersie> getVersies()
{
return versies;
}
public void setVersies(List<DeelnemerResultaatVersie> versies)
{
this.versies = versies;
}
public List<ResultaatstructuurMedewerker> getMedewerkers()
{
return medewerkers;
}
public void setMedewerkers(List<ResultaatstructuurMedewerker> medewerkers)
{
this.medewerkers = medewerkers;
}
public List<ResultaatstructuurDeelnemer> getDeelnemers()
{
return deelnemers;
}
public void setDeelnemers(List<ResultaatstructuurDeelnemer> deelnemers)
{
this.deelnemers = deelnemers;
}
public boolean isBewerkbaar()
{
return status.equals(Status.IN_ONDERHOUD);
}
public boolean isBeschikbaar()
{
return status.equals(Status.BESCHIKBAAR);
}
public boolean isInBerekening()
{
return status.equals(Status.IN_HERBEREKENING);
}
/**
* @return de toets met het gegeven toetscodepad. Voorbeeld van een toetscodepad:
* EIND/SE/309
*/
@Exportable
public Toets findToets(String toetsCodePath)
{
for (Toets curToets : getToetsen())
if (curToets.getToetscodePath().equals(toetsCodePath))
return curToets;
return null;
}
public Toets findToets(String toetsCodePath, ToetsCodePathMode mode)
{
for (Toets curToets : getToetsen())
if (curToets.getToetscodePath(mode).equals(toetsCodePath))
return curToets;
return null;
}
/**
* @return De unieke toets binnen deze resultaatstructuur van de gegeven soort. Soort
* moet aangegeven zijn als uniek binnen de resultaatstructuur.
*/
public Toets getToets(SoortToets soort)
{
if (!soort.isUniekBinnenResultaatstructuur())
throw new IllegalArgumentException("Soort moet uniek binnen de resultaatstructuur zijn");
if (getEindresultaat() == null)
return null;
return getEindresultaat().getChild(soort);
}
@Override
public String toString()
{
return "(" + getCohort() + ") " + onderwijsproduct;
}
public boolean isEindResultaatCompleet()
{
return getEindresultaat().getCode() != null && getEindresultaat().getNaam() != null
&& getEindresultaat().getSchaal() != null
&& getEindresultaat().getScoreschaal() != null;
}
public static ModelManager createModelManager()
{
return new DefaultModelManager(ResultaatstructuurDeelnemer.class,
ResultaatstructuurMedewerker.class, Scoreschaalwaarde.class, ToetsVerwijzing.class,
PersoonlijkeToetscode.class, Toets.class, Resultaatstructuur.class);
}
public boolean isGekoppeld(Medewerker medewerker)
{
if (!isSpecifiek())
return true;
for (ResultaatstructuurMedewerker curMedewerker : getMedewerkers())
if (curMedewerker.getMedewerker().equals(medewerker))
return true;
return false;
}
}
|
158781_6 | /*
* Copyright 2022 Topicus Onderwijs Eduarte B.V..
*
* 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
*
* https://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 nl.topicus.eduarte.model.entities.participatie.enums;
/**
* Status van een uitnodiging bij een afspraak.
*
*/
public enum UitnodigingStatus
{
/**
* Participant is direct geplaatst.
*/
DIRECTE_PLAATSING("Direct geplaatst", true),
/**
* Participant is uitgenodigd
*/
UITGENODIGD("Uitgenodigd", false),
/**
* Participant heeft de uitnodiging geaccepteerd
*/
GEACCEPTEERD("Uitnodiging geaccepteerd", true),
/**
* Participant heeft de uitnodiging geweigerd.
*/
GEWEIGERD("Uitnodiging geweigerd", false),
/**
* Participant heeft zich ingeschreven voor een inloopcollege.
*/
INGETEKEND("Ingetekend voor het college", true);
private String naam;
/**
* Geeft aan of aanwezigheidsregistratie mogelijk is bij deze status.
*/
private boolean aanwezigheidsregistratieMogelijk;
/**
* Constructor
*
* @param naam
*/
UitnodigingStatus(String naam, boolean aanwezigheidsregistratieMogelijk)
{
this.naam = naam;
this.aanwezigheidsregistratieMogelijk = aanwezigheidsregistratieMogelijk;
}
@Override
public String toString()
{
return naam;
}
/**
* @return Returns the aanwezigheidsregistratieMogelijk.
*/
public boolean isAanwezigheidsregistratieMogelijk()
{
return aanwezigheidsregistratieMogelijk;
}
}
| topicusonderwijs/tribe-krd-quarkus | src/main/java/nl/topicus/eduarte/model/entities/participatie/enums/UitnodigingStatus.java | 631 | /**
* Participant heeft zich ingeschreven voor een inloopcollege.
*/ | block_comment | nl | /*
* Copyright 2022 Topicus Onderwijs Eduarte B.V..
*
* 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
*
* https://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 nl.topicus.eduarte.model.entities.participatie.enums;
/**
* Status van een uitnodiging bij een afspraak.
*
*/
public enum UitnodigingStatus
{
/**
* Participant is direct geplaatst.
*/
DIRECTE_PLAATSING("Direct geplaatst", true),
/**
* Participant is uitgenodigd
*/
UITGENODIGD("Uitgenodigd", false),
/**
* Participant heeft de uitnodiging geaccepteerd
*/
GEACCEPTEERD("Uitnodiging geaccepteerd", true),
/**
* Participant heeft de uitnodiging geweigerd.
*/
GEWEIGERD("Uitnodiging geweigerd", false),
/**
* Participant heeft zich<SUF>*/
INGETEKEND("Ingetekend voor het college", true);
private String naam;
/**
* Geeft aan of aanwezigheidsregistratie mogelijk is bij deze status.
*/
private boolean aanwezigheidsregistratieMogelijk;
/**
* Constructor
*
* @param naam
*/
UitnodigingStatus(String naam, boolean aanwezigheidsregistratieMogelijk)
{
this.naam = naam;
this.aanwezigheidsregistratieMogelijk = aanwezigheidsregistratieMogelijk;
}
@Override
public String toString()
{
return naam;
}
/**
* @return Returns the aanwezigheidsregistratieMogelijk.
*/
public boolean isAanwezigheidsregistratieMogelijk()
{
return aanwezigheidsregistratieMogelijk;
}
}
|
75869_2 | package nl.topicus.onderwijs.vakkentabel;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.sonatype.plexus.build.incremental.BuildContext;
/**
* Maven Goal voor het genereren van utility classes op basis van de vakkentabel van DUO
*
* <a href=
* "http://www.duo.nl/zakelijk/klantenservice/softwareleveranciers/Programmas_van_eisen.asp"
* >http://www.duo.nl/zakelijk/klantenservice/softwareleveranciers/Programmas_van_eisen. asp</a>.
*
* Voor uitleg rondom deze Maven plugin:
*
* <a href= "https://github.com/topicusonderwijs/vakkentabel-maven-plugin/wiki/Vakkentabel-DUO"
* >Vakkentabel DUO</a>
*
* @author Jeroen Steenbeeke
* @author Sven Haster
*/
@Mojo(defaultPhase = LifecyclePhase.GENERATE_SOURCES, name = "generate", threadSafe = true,
requiresDependencyResolution = ResolutionScope.TEST)
public class VakkentabelMojo extends AbstractMojo
{
/**
* De locatie van de vakkentabel (relatief tov pom-dir, of absoluut tov systeem - dat laatste
* wil je niet)
*/
@Parameter(required = true)
public File vakkentabel;
/**
* De package waarbinnen de gegenereerde classes moeten worden geplaatst (onder
* target/generated-sources/vakkentabel )
*/
@Parameter(required = true)
public String packagePrefix;
/**
* Type dat gebruikt wordt voor methoden die matchers terug geven
*
* @see nl.topicus.iridium.util.bron.rules.BronVakRule
*/
@SuppressWarnings("javadoc")
@Parameter(required = false)
public String matcherClass;
/**
* Type dat gebruikt wordt voor het aanmaken van bovenstaande matchers
*
* @see nl.topicus.iridium.util.bron.rules.BronVakRules
*/
@SuppressWarnings("javadoc")
@Parameter(required = false)
public String matcherFactory;
@Parameter(required = true,
defaultValue = "${project.build.directory}/generated-sources/vakkentabel")
public File outputDirectory;
@Component
public BuildContext buildContext;
@Parameter(required = true, property = "project")
protected MavenProject project;
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
performIntegrityChecks();
File packageDir = createOutputDirectories();
try
{
long maxSourceDate = vakkentabel.lastModified();
// use atomic long for effectively final wrapper around long variable
AtomicLong maxOutputDate = new AtomicLong(Long.MIN_VALUE);
Files.walkFileTree(outputDirectory.toPath(), new SimpleFileVisitor<>()
{
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
if (Files.isRegularFile(file))
{
maxOutputDate.updateAndGet(t -> Math.max(t, file.toFile().lastModified()));
}
return FileVisitResult.CONTINUE;
}
});
if (getLog().isDebugEnabled())
{
getLog().debug("max source file date: " + maxSourceDate + ", max output date: " + maxOutputDate
.get());
}
if (maxSourceDate <= maxOutputDate.get())
{
getLog().info("no source file(s) change(s) detected! Processor task will be skipped");
return;
}
}
catch(IOException e)
{
getLog().warn("Exception tijdens het bepalen van de lastModified: " + e);
// behandel deze situatie als dat er geen update controle heeft plaatsgevonden
}
if (buildContext == null || !buildContext.isIncremental()
|| buildContext.hasDelta(vakkentabel))
{
try
{
getLog().info(String.format("Analyseren van %s", vakkentabel.getName()));
Scanner scanner = new Scanner().scan(vakkentabel);
getLog().info(String.format("%d vakregels gevonden", scanner.getAantalRegels()));
getLog()
.info(String.format("Genereer %s", packagePrefix.concat(".CentraalExamen")));
scanner.generateCentraalExamen(packageDir, packagePrefix);
getLog()
.info(String.format("Genereer %s", packagePrefix.concat(".BeroepsgerichtVak")));
scanner.generateBeroepsgerichtVak(packageDir, packagePrefix, matcherClass,
matcherFactory);
getLog().info(String.format("Genereer %s", packagePrefix.concat(".SchoolExamen")));
scanner.generateSchoolExamen(packageDir, packagePrefix);
getLog().info(String.format("Genereer %s", packagePrefix.concat(".OVG")));
scanner.generateOVGVakken(packageDir, packagePrefix);
getLog().info("Vakkentabel voltooid");
}
catch (IOException e)
{
throw new MojoFailureException("IO exception bij het scannen van de vakkentabel",
e);
}
finally
{
if (buildContext != null)
{
buildContext.refresh(packageDir);
}
}
}
}
private File createOutputDirectories() throws MojoFailureException
{
if (!outputDirectory.exists() && !outputDirectory.mkdirs())
{
throw new MojoFailureException(
"Kon doelmap target/generated-sources/vakkentabel niet aanmaken");
}
project.addCompileSourceRoot("target/generated-sources/vakkentabel");
String[] pkg = packagePrefix.split("\\.");
File packageDir = outputDirectory;
if (pkg[0].length() > 0)
{
packageDir = new File(outputDirectory, pkg[0]);
}
if (pkg.length > 1)
{
for (int i = 1; i < pkg.length; i++)
{
packageDir = new File(packageDir, pkg[i]);
}
}
if (!packageDir.exists() && !packageDir.mkdirs())
{
throw new MojoFailureException(String.format("Kon package %s in %s niet aanmaken",
packagePrefix, outputDirectory.getPath()));
}
return packageDir;
}
private void performIntegrityChecks() throws MojoExecutionException, MojoFailureException
{
getLog().debug("Checking project");
if (project == null)
{
throw new MojoExecutionException("INTERNE FOUT: Ontbrekende maven project reference");
}
getLog().debug(String.format("OK: %s", project.getName()));
if (buildContext == null)
{
throw new MojoExecutionException("INTERNE FOUT: Ontbrekende build context");
}
Set<String> missing = new HashSet<>();
getLog().debug("Checking config");
if (vakkentabel == null)
{
missing.add("vakkentabel");
}
if (packagePrefix == null)
{
missing.add("packagePrefix");
}
if (outputDirectory == null)
{
missing.add("outputDirectory");
}
if (!missing.isEmpty())
{
throw new MojoFailureException(String.format("Ontbrekende configuratie-opties: %s",
missing.stream().collect(Collectors.joining(", "))));
}
getLog().debug(String.format("- vakkentabel: %s", vakkentabel.getName()));
getLog().debug(String.format("- packagePrefix: %s", packagePrefix));
if (!vakkentabel.exists())
{
throw new MojoFailureException(
String.format("Vakkentabel %s bestaat niet", vakkentabel.getName()));
}
getLog().debug("Vakkentabel exists");
}
}
| topicusonderwijs/vakkentabel-maven-plugin | src/main/java/nl/topicus/onderwijs/vakkentabel/VakkentabelMojo.java | 2,438 | /**
* De package waarbinnen de gegenereerde classes moeten worden geplaatst (onder
* target/generated-sources/vakkentabel )
*/ | block_comment | nl | package nl.topicus.onderwijs.vakkentabel;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.sonatype.plexus.build.incremental.BuildContext;
/**
* Maven Goal voor het genereren van utility classes op basis van de vakkentabel van DUO
*
* <a href=
* "http://www.duo.nl/zakelijk/klantenservice/softwareleveranciers/Programmas_van_eisen.asp"
* >http://www.duo.nl/zakelijk/klantenservice/softwareleveranciers/Programmas_van_eisen. asp</a>.
*
* Voor uitleg rondom deze Maven plugin:
*
* <a href= "https://github.com/topicusonderwijs/vakkentabel-maven-plugin/wiki/Vakkentabel-DUO"
* >Vakkentabel DUO</a>
*
* @author Jeroen Steenbeeke
* @author Sven Haster
*/
@Mojo(defaultPhase = LifecyclePhase.GENERATE_SOURCES, name = "generate", threadSafe = true,
requiresDependencyResolution = ResolutionScope.TEST)
public class VakkentabelMojo extends AbstractMojo
{
/**
* De locatie van de vakkentabel (relatief tov pom-dir, of absoluut tov systeem - dat laatste
* wil je niet)
*/
@Parameter(required = true)
public File vakkentabel;
/**
* De package waarbinnen<SUF>*/
@Parameter(required = true)
public String packagePrefix;
/**
* Type dat gebruikt wordt voor methoden die matchers terug geven
*
* @see nl.topicus.iridium.util.bron.rules.BronVakRule
*/
@SuppressWarnings("javadoc")
@Parameter(required = false)
public String matcherClass;
/**
* Type dat gebruikt wordt voor het aanmaken van bovenstaande matchers
*
* @see nl.topicus.iridium.util.bron.rules.BronVakRules
*/
@SuppressWarnings("javadoc")
@Parameter(required = false)
public String matcherFactory;
@Parameter(required = true,
defaultValue = "${project.build.directory}/generated-sources/vakkentabel")
public File outputDirectory;
@Component
public BuildContext buildContext;
@Parameter(required = true, property = "project")
protected MavenProject project;
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
performIntegrityChecks();
File packageDir = createOutputDirectories();
try
{
long maxSourceDate = vakkentabel.lastModified();
// use atomic long for effectively final wrapper around long variable
AtomicLong maxOutputDate = new AtomicLong(Long.MIN_VALUE);
Files.walkFileTree(outputDirectory.toPath(), new SimpleFileVisitor<>()
{
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
if (Files.isRegularFile(file))
{
maxOutputDate.updateAndGet(t -> Math.max(t, file.toFile().lastModified()));
}
return FileVisitResult.CONTINUE;
}
});
if (getLog().isDebugEnabled())
{
getLog().debug("max source file date: " + maxSourceDate + ", max output date: " + maxOutputDate
.get());
}
if (maxSourceDate <= maxOutputDate.get())
{
getLog().info("no source file(s) change(s) detected! Processor task will be skipped");
return;
}
}
catch(IOException e)
{
getLog().warn("Exception tijdens het bepalen van de lastModified: " + e);
// behandel deze situatie als dat er geen update controle heeft plaatsgevonden
}
if (buildContext == null || !buildContext.isIncremental()
|| buildContext.hasDelta(vakkentabel))
{
try
{
getLog().info(String.format("Analyseren van %s", vakkentabel.getName()));
Scanner scanner = new Scanner().scan(vakkentabel);
getLog().info(String.format("%d vakregels gevonden", scanner.getAantalRegels()));
getLog()
.info(String.format("Genereer %s", packagePrefix.concat(".CentraalExamen")));
scanner.generateCentraalExamen(packageDir, packagePrefix);
getLog()
.info(String.format("Genereer %s", packagePrefix.concat(".BeroepsgerichtVak")));
scanner.generateBeroepsgerichtVak(packageDir, packagePrefix, matcherClass,
matcherFactory);
getLog().info(String.format("Genereer %s", packagePrefix.concat(".SchoolExamen")));
scanner.generateSchoolExamen(packageDir, packagePrefix);
getLog().info(String.format("Genereer %s", packagePrefix.concat(".OVG")));
scanner.generateOVGVakken(packageDir, packagePrefix);
getLog().info("Vakkentabel voltooid");
}
catch (IOException e)
{
throw new MojoFailureException("IO exception bij het scannen van de vakkentabel",
e);
}
finally
{
if (buildContext != null)
{
buildContext.refresh(packageDir);
}
}
}
}
private File createOutputDirectories() throws MojoFailureException
{
if (!outputDirectory.exists() && !outputDirectory.mkdirs())
{
throw new MojoFailureException(
"Kon doelmap target/generated-sources/vakkentabel niet aanmaken");
}
project.addCompileSourceRoot("target/generated-sources/vakkentabel");
String[] pkg = packagePrefix.split("\\.");
File packageDir = outputDirectory;
if (pkg[0].length() > 0)
{
packageDir = new File(outputDirectory, pkg[0]);
}
if (pkg.length > 1)
{
for (int i = 1; i < pkg.length; i++)
{
packageDir = new File(packageDir, pkg[i]);
}
}
if (!packageDir.exists() && !packageDir.mkdirs())
{
throw new MojoFailureException(String.format("Kon package %s in %s niet aanmaken",
packagePrefix, outputDirectory.getPath()));
}
return packageDir;
}
private void performIntegrityChecks() throws MojoExecutionException, MojoFailureException
{
getLog().debug("Checking project");
if (project == null)
{
throw new MojoExecutionException("INTERNE FOUT: Ontbrekende maven project reference");
}
getLog().debug(String.format("OK: %s", project.getName()));
if (buildContext == null)
{
throw new MojoExecutionException("INTERNE FOUT: Ontbrekende build context");
}
Set<String> missing = new HashSet<>();
getLog().debug("Checking config");
if (vakkentabel == null)
{
missing.add("vakkentabel");
}
if (packagePrefix == null)
{
missing.add("packagePrefix");
}
if (outputDirectory == null)
{
missing.add("outputDirectory");
}
if (!missing.isEmpty())
{
throw new MojoFailureException(String.format("Ontbrekende configuratie-opties: %s",
missing.stream().collect(Collectors.joining(", "))));
}
getLog().debug(String.format("- vakkentabel: %s", vakkentabel.getName()));
getLog().debug(String.format("- packagePrefix: %s", packagePrefix));
if (!vakkentabel.exists())
{
throw new MojoFailureException(
String.format("Vakkentabel %s bestaat niet", vakkentabel.getName()));
}
getLog().debug("Vakkentabel exists");
}
}
|
118182_7 | package nl.topicus.cambo.stubsis.client;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import nl.topicus.cambo.stubsis.model.AccessTokenResponse;
@ApplicationScoped
public class StubSISCamboClient
{
private static final GenericType<Map<String, Object>> ANY_TYPE = new GenericType<>()
{
};
private Client client;
private ObjectMapper mapper;
private String accessToken;
private Instant accessTokenExpiresAt = Instant.now();
private static final MediaType CAMBO_JSON_TYPE =
MediaType.valueOf("application/vnd.topicus.cambo+json");
public StubSISCamboClient()
{
}
/**
* Maakt een Jackson ObjectMapper die overweg kan met datums als strings en de types in
* java.time. VCA geeft datums terug in het formaat 'yyyy-MM-dd' en niet als een timestamp.
*/
private static ObjectMapper createMapper()
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.setTimeZone(TimeZone.getDefault());
mapper.registerModule(new JavaTimeModule());
return mapper;
}
@PostConstruct
private void init()
{
mapper = createMapper();
// Bouw een JAX-RS client met JSON support en registreer de keystore met het PKI Overheid
// certificaat en private key. De client zal dit certificaat automatisch gebruiken voor
// client authenticatie.
client = ClientBuilder.newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.keyStore(readStubSISKeyStore(), "password")
.register(JacksonJaxbJsonProvider.class)
.register(new JacksonObjectMapperProvider(mapper))
.build();
}
private KeyStore readStubSISKeyStore()
{
try (FileInputStream fis = new FileInputStream(System.getProperty("stubsis/tlscertbundle")))
{
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(fis, System.getProperty("stubsis/tlscertpassword").toCharArray());
return ks;
}
catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException e)
{
throw new RuntimeException(e);
}
}
private String getCamboUrl()
{
return "https://" + System.getProperty("cambo/hostname");
}
/**
* Haalt een nieuw access token op als dit nodig is.
*/
public String ensureToken()
{
// Als het token nog minimaal 5 minuten geldig is, gebruik dan de oude
if (accessTokenExpiresAt.isAfter(Instant.now().plus(5, ChronoUnit.MINUTES)))
return accessToken;
// StubSIS gebruikt een dummy-OIN met 20x9. Het gebruikte nummer moet overeenkomen het het
// OIN in het certificaat (serial number in het subjectDN)
URI uri = UriBuilder.fromUri(getCamboUrl()).path("/login/oauth2/token").build();
MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
form.putSingle("client_id", "99999999999999999999");
form.putSingle("grant_type", "client_credentials");
Response response = null;
try
{
response = client.target(uri)
.request()
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
if (response.getStatus() != Status.OK.getStatusCode())
{
throw new RuntimeException(toJsonString(response.readEntity(ANY_TYPE)));
}
AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class);
accessToken = tokenResponse.getAccessToken().toString();
accessTokenExpiresAt =
Instant.now().plus(tokenResponse.getExpiresIn(), ChronoUnit.SECONDS);
return accessToken;
}
finally
{
close(response);
}
}
protected void close(Response response)
{
if (response != null)
response.close();
}
public URI me()
{
return UriBuilder.fromUri(getCamboUrl()).path("/cambo/rest/v1/party/me").build();
}
public URI endpoints()
{
return UriBuilder.fromUri(getCamboUrl()).path("/cambo/rest/v1/koppelpunt").build();
}
public URI nieuweAanmeldingen(String endpoint)
{
return UriBuilder.fromUri(getCamboUrl())
.path("/cambo/rest/v1/koppelpunt")
.path(endpoint)
.path("aanmelding/nieuw")
.build();
}
public URI aanmeldingen(String endpoint)
{
return UriBuilder.fromUri(getCamboUrl())
.path("/cambo/rest/v1/koppelpunt")
.path(endpoint)
.path("aanmelding")
.build();
}
public Object read(URI uri, Class< ? > responseType)
{
Response response = null;
try
{
response = client.target(uri)
.request(CAMBO_JSON_TYPE)
.header("Authorization", "Bearer " + ensureToken())
.get();
if (responseType == null)
return response.readEntity(ANY_TYPE);
else
return response.readEntity(responseType);
}
finally
{
close(response);
}
}
public String toJsonString(Object obj)
{
try
{
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
catch (JsonProcessingException e)
{
throw new RuntimeException(e);
}
}
}
| topicusonderwijs/vca-stubsis | src/main/java/nl/topicus/cambo/stubsis/client/StubSISCamboClient.java | 1,960 | // OIN in het certificaat (serial number in het subjectDN) | line_comment | nl | package nl.topicus.cambo.stubsis.client;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import nl.topicus.cambo.stubsis.model.AccessTokenResponse;
@ApplicationScoped
public class StubSISCamboClient
{
private static final GenericType<Map<String, Object>> ANY_TYPE = new GenericType<>()
{
};
private Client client;
private ObjectMapper mapper;
private String accessToken;
private Instant accessTokenExpiresAt = Instant.now();
private static final MediaType CAMBO_JSON_TYPE =
MediaType.valueOf("application/vnd.topicus.cambo+json");
public StubSISCamboClient()
{
}
/**
* Maakt een Jackson ObjectMapper die overweg kan met datums als strings en de types in
* java.time. VCA geeft datums terug in het formaat 'yyyy-MM-dd' en niet als een timestamp.
*/
private static ObjectMapper createMapper()
{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.setTimeZone(TimeZone.getDefault());
mapper.registerModule(new JavaTimeModule());
return mapper;
}
@PostConstruct
private void init()
{
mapper = createMapper();
// Bouw een JAX-RS client met JSON support en registreer de keystore met het PKI Overheid
// certificaat en private key. De client zal dit certificaat automatisch gebruiken voor
// client authenticatie.
client = ClientBuilder.newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.keyStore(readStubSISKeyStore(), "password")
.register(JacksonJaxbJsonProvider.class)
.register(new JacksonObjectMapperProvider(mapper))
.build();
}
private KeyStore readStubSISKeyStore()
{
try (FileInputStream fis = new FileInputStream(System.getProperty("stubsis/tlscertbundle")))
{
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(fis, System.getProperty("stubsis/tlscertpassword").toCharArray());
return ks;
}
catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException e)
{
throw new RuntimeException(e);
}
}
private String getCamboUrl()
{
return "https://" + System.getProperty("cambo/hostname");
}
/**
* Haalt een nieuw access token op als dit nodig is.
*/
public String ensureToken()
{
// Als het token nog minimaal 5 minuten geldig is, gebruik dan de oude
if (accessTokenExpiresAt.isAfter(Instant.now().plus(5, ChronoUnit.MINUTES)))
return accessToken;
// StubSIS gebruikt een dummy-OIN met 20x9. Het gebruikte nummer moet overeenkomen het het
// OIN in<SUF>
URI uri = UriBuilder.fromUri(getCamboUrl()).path("/login/oauth2/token").build();
MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
form.putSingle("client_id", "99999999999999999999");
form.putSingle("grant_type", "client_credentials");
Response response = null;
try
{
response = client.target(uri)
.request()
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
if (response.getStatus() != Status.OK.getStatusCode())
{
throw new RuntimeException(toJsonString(response.readEntity(ANY_TYPE)));
}
AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class);
accessToken = tokenResponse.getAccessToken().toString();
accessTokenExpiresAt =
Instant.now().plus(tokenResponse.getExpiresIn(), ChronoUnit.SECONDS);
return accessToken;
}
finally
{
close(response);
}
}
protected void close(Response response)
{
if (response != null)
response.close();
}
public URI me()
{
return UriBuilder.fromUri(getCamboUrl()).path("/cambo/rest/v1/party/me").build();
}
public URI endpoints()
{
return UriBuilder.fromUri(getCamboUrl()).path("/cambo/rest/v1/koppelpunt").build();
}
public URI nieuweAanmeldingen(String endpoint)
{
return UriBuilder.fromUri(getCamboUrl())
.path("/cambo/rest/v1/koppelpunt")
.path(endpoint)
.path("aanmelding/nieuw")
.build();
}
public URI aanmeldingen(String endpoint)
{
return UriBuilder.fromUri(getCamboUrl())
.path("/cambo/rest/v1/koppelpunt")
.path(endpoint)
.path("aanmelding")
.build();
}
public Object read(URI uri, Class< ? > responseType)
{
Response response = null;
try
{
response = client.target(uri)
.request(CAMBO_JSON_TYPE)
.header("Authorization", "Bearer " + ensureToken())
.get();
if (responseType == null)
return response.readEntity(ANY_TYPE);
else
return response.readEntity(responseType);
}
finally
{
close(response);
}
}
public String toJsonString(Object obj)
{
try
{
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
catch (JsonProcessingException e)
{
throw new RuntimeException(e);
}
}
}
|
187188_22 | /*
* TwoElectronIntegrals.java
*
* Created on July 28, 2004, 7:03 AM
*/
package org.meta.math.qm;
import java.util.*;
import org.meta.math.geom.Point3D;
import org.meta.math.Vector3D;
import org.meta.math.qm.basis.ContractedGaussian;
import org.meta.math.qm.basis.Power;
import org.meta.math.qm.basis.PrimitiveGaussian;
import org.meta.math.qm.integral.Integrals;
import org.meta.math.qm.integral.IntegralsUtil;
import org.meta.molecule.Molecule;
import org.meta.parallel.AbstractSimpleParallelTask;
import org.meta.parallel.SimpleParallelTask;
import org.meta.parallel.SimpleParallelTaskExecuter;
/**
* The 2E integral driver.
*
* @author V.Ganesh
* @version 2.0 (Part of MeTA v2.0)
*/
public class TwoElectronIntegrals {
private BasisFunctions basisFunctions;
private Molecule molecule;
/**
* Holds value of property twoEIntegrals.
*/
private double[] twoEIntegrals;
/**
* Creates a new instance of TwoElectronIntegrals
*
* @param basisFunctions the basis functions to be used
*/
public TwoElectronIntegrals(BasisFunctions basisFunctions) {
this(basisFunctions, false);
}
/**
* Creates a new instance of TwoElectronIntegrals
*
* @param basisFunctions the basis functions to be used
* @param onTheFly if true, the 2E integrals are not calculated and stored,
* they must be calculated individually by calling compute2E(i,j,k,l)
*/
public TwoElectronIntegrals(BasisFunctions basisFunctions,
boolean onTheFly) {
this.basisFunctions = basisFunctions;
this.onTheFly = onTheFly;
// compute the 2E integrals
if (!onTheFly) {
try {
compute2E(); // try to do compute 2E incore
} catch(OutOfMemoryError e) {
// if no memory, resort to direct SCF
System.err.println("No memory for in-core integral evaluation" +
". Switching to direct integral evaluation.");
System.gc();
this.onTheFly = true;
} // end of try catch block
} // end if
}
/**
* Creates a new instance of TwoElectronIntegrals, and computes
* two electron intergrals using shell-pair method rather than the
* conventional loop over all basis functions approach. Note that, this
* requires the Molecule object to be passed as an argument for it to
* function correctly. Note that the Atom objects which are a part of
* Molecule object must be specially configured to have a user defined
* property called "basisFunctions" that is essentially a list of
* ContractedGaussians that are centered on the atom. If this breaks, then
* the code will silentely default to using the conventional way of
* computing the two electron intergrals.
*
* @param molecule
* @param onTheFly if true, the 2E integrals are not calculated and stored,
* they must be calculated individually by calling
* compute2EShellPair(i,j,k,l)
*/
public TwoElectronIntegrals(BasisFunctions basisFunctions,
Molecule molecule, boolean onTheFly) {
this.basisFunctions = basisFunctions;
this.molecule = molecule;
this.onTheFly = onTheFly;
// compute the 2E integrals
if (!onTheFly) {
try {
// first try in - core method
try {
compute2EShellPair(); // try to use shell pair algorithm
} catch(Exception ignored) {
System.err.println("WARNING: Using a slower algorithm" +
" to compute two electron integrals. Error is: "
+ ignored.toString());
ignored.printStackTrace();
compute2E(); // if it doesn't succeed then fall back to normal
} // end if
} catch(OutOfMemoryError e) {
// if no memory, resort to direct SCF
System.err.println("No memory for in-core integral evaluation" +
". Switching to direct integral evaluation.");
System.gc();
this.onTheFly = true;
} // end if
} // end if
}
/**
* compute the 2E integrals, and store it in a single 1D array,
* in the form [ijkl].
*
* This method has been modified to take advantage of multi core systems
* where available.
*/
protected void compute2E() {
ArrayList<ContractedGaussian> bfs = basisFunctions.getBasisFunctions();
// allocate required memory
int noOfBasisFunctions = bfs.size();
int noOfIntegrals = noOfBasisFunctions * (noOfBasisFunctions + 1)
* (noOfBasisFunctions * noOfBasisFunctions
+ noOfBasisFunctions + 2) / 8;
twoEIntegrals = new double[noOfIntegrals];
SimpleParallelTaskExecuter pTaskExecuter
= new SimpleParallelTaskExecuter();
TwoElectronIntegralEvaluaterThread tThread
= new TwoElectronIntegralEvaluaterThread();
tThread.setTaskName("TwoElectronIntegralEvaluater Thread");
tThread.setTotalItems(noOfBasisFunctions);
pTaskExecuter.execute(tThread);
}
/**
* Actually compute the 2E integrals
*/
private void compute2E(int startBasisFunction, int endBasisFunction,
ArrayList<ContractedGaussian> bfs) {
int i, j, k, l, ij, kl, ijkl;
int noOfBasisFunctions = bfs.size();
ContractedGaussian bfi, bfj, bfk, bfl;
// we only need i <= j, k <= l, and ij >= kl
for(i=startBasisFunction; i<endBasisFunction; i++) {
bfi = bfs.get(i);
for(j=0; j<(i+1); j++) {
bfj = bfs.get(j);
ij = i * (i+1) / 2+j;
for(k=0; k<noOfBasisFunctions; k++) {
bfk = bfs.get(k);
for(l=0; l<(k+1); l++) {
bfl = bfs.get(l);
kl = k * (k+1) / 2+l;
if (ij >= kl) {
ijkl = IntegralsUtil.ijkl2intindex(i, j, k, l);
// record the 2E integrals
twoEIntegrals[ijkl] = Integrals.coulomb(bfi, bfj,
bfk, bfl);
} // end if
} // end l loop
} // end k loop
} // end of j loop
} // end of i loop
}
/**
* Actually compute the 2E integrals derivatives
*/
private void compute2EDerivative(int startBasisFunction, int endBasisFunction,
ArrayList<ContractedGaussian> bfs) {
int i, j, k, l, ij, kl, ijkl;
int noOfBasisFunctions = bfs.size();
ContractedGaussian bfi, bfj, bfk, bfl;
double [] dxTwoE = twoEDer.get(0);
double [] dyTwoE = twoEDer.get(1);
double [] dzTwoE = twoEDer.get(2);
// we only need i <= j, k <= l, and ij >= kl
for(i=startBasisFunction; i<endBasisFunction; i++) {
bfi = bfs.get(i);
for(j=0; j<(i+1); j++) {
bfj = bfs.get(j);
ij = i * (i+1) / 2+j;
for(k=0; k<noOfBasisFunctions; k++) {
bfk = bfs.get(k);
for(l=0; l<(k+1); l++) {
bfl = bfs.get(l);
kl = k * (k+1) / 2+l;
if (ij >= kl) {
ijkl = IntegralsUtil.ijkl2intindex(i, j, k, l);
// record derivative of the 2E integrals
Vector3D twoEDerEle
= compute2EDerivativeElement(bfi, bfj, bfk, bfl);
dxTwoE[ijkl] = twoEDerEle.getI();
dyTwoE[ijkl] = twoEDerEle.getJ();
dzTwoE[ijkl] = twoEDerEle.getK();
} // end if
} // end l loop
} // end k loop
} // end of j loop
} // end of i loop
}
/** Compute a single 2E derivative element */
private Vector3D compute2EDerivativeElement(ContractedGaussian bfi,
ContractedGaussian bfj, ContractedGaussian bfk, ContractedGaussian bfl) {
Vector3D twoEDerEle = new Vector3D();
int [] paramIdx;
Power currentPower;
Point3D currentOrigin;
double currentAlpha;
if (bfi.getCenteredAtom().getIndex() == atomIndex) {
paramIdx = new int[]{4, 1, 2, 3};
for(PrimitiveGaussian iPG : bfi.getPrimitives()) {
currentOrigin = iPG.getOrigin();
currentPower = iPG.getPowers();
currentAlpha = iPG.getExponent();
for(PrimitiveGaussian jPG : bfj.getPrimitives()) {
for(PrimitiveGaussian kPG : bfk.getPrimitives()) {
for(PrimitiveGaussian lPG : bfl.getPrimitives()) {
compute2EDerivativeElementHelper(iPG, jPG,
kPG, lPG, currentOrigin, currentPower,
currentAlpha, paramIdx, twoEDerEle);
} // end for
} // end for
} // end for
} // end for
} // end if
if (bfj.getCenteredAtom().getIndex() == atomIndex) {
paramIdx = new int[]{0, 4, 2, 3};
for(PrimitiveGaussian iPG : bfi.getPrimitives()) {
for(PrimitiveGaussian jPG : bfj.getPrimitives()) {
currentOrigin = jPG.getOrigin();
currentPower = jPG.getPowers();
currentAlpha = jPG.getExponent();
for(PrimitiveGaussian kPG : bfk.getPrimitives()) {
for(PrimitiveGaussian lPG : bfl.getPrimitives()) {
compute2EDerivativeElementHelper(iPG, jPG,
kPG, lPG, currentOrigin, currentPower,
currentAlpha, paramIdx, twoEDerEle);
} // end for
} // end for
} // end for
} // end for
} // end if
if (bfk.getCenteredAtom().getIndex() == atomIndex) {
paramIdx = new int[]{0, 1, 4, 3};
for(PrimitiveGaussian iPG : bfi.getPrimitives()) {
for(PrimitiveGaussian jPG : bfj.getPrimitives()) {
for(PrimitiveGaussian kPG : bfk.getPrimitives()) {
currentOrigin = kPG.getOrigin();
currentPower = kPG.getPowers();
currentAlpha = kPG.getExponent();
for(PrimitiveGaussian lPG : bfl.getPrimitives()) {
compute2EDerivativeElementHelper(iPG, jPG,
kPG, lPG, currentOrigin, currentPower,
currentAlpha, paramIdx, twoEDerEle);
} // end for
} // end for
} // end for
} // end for
} // end if
if (bfl.getCenteredAtom().getIndex() == atomIndex) {
paramIdx = new int[]{0, 1, 2, 4};
for(PrimitiveGaussian iPG : bfi.getPrimitives()) {
for(PrimitiveGaussian jPG : bfj.getPrimitives()) {
for(PrimitiveGaussian kPG : bfk.getPrimitives()) {
for(PrimitiveGaussian lPG : bfl.getPrimitives()) {
currentOrigin = lPG.getOrigin();
currentPower = lPG.getPowers();
currentAlpha = lPG.getExponent();
compute2EDerivativeElementHelper(iPG, jPG,
kPG, lPG, currentOrigin, currentPower,
currentAlpha, paramIdx, twoEDerEle);
} // end for
} // end for
} // end for
} // end for
} // end if
return twoEDerEle;
}
/** helper for computing 2E derivative */
private void compute2EDerivativeElementHelper(PrimitiveGaussian iPG,
PrimitiveGaussian jPG, PrimitiveGaussian kPG, PrimitiveGaussian lPG,
Point3D currentOrigin, Power currentPower, double currentAlpha,
int [] paramIdx, Vector3D derEle) {
int l = currentPower.getL(),
m = currentPower.getM(),
n = currentPower.getN();
double coeff = iPG.getCoefficient()*jPG.getCoefficient()
*kPG.getCoefficient()*lPG.getCoefficient();
PrimitiveGaussian xPG = new PrimitiveGaussian(currentOrigin,
new Power(l+1,m,n), currentAlpha, coeff);
xPG.normalize();
PrimitiveGaussian [] pgs
= new PrimitiveGaussian[]{iPG, jPG, kPG, lPG, xPG};
double terma = Math.sqrt(currentAlpha*(2.0*l+1.0))*coeff*
Integrals.coulomb(pgs[paramIdx[0]], pgs[paramIdx[1]],
pgs[paramIdx[2]], pgs[paramIdx[3]]),
termb = 0.0;
if (l>0) {
xPG.setPowers(new Power(l-1,m,n));
xPG.normalize();
termb = -2.0*l*Math.sqrt(currentAlpha/(2.*l-1))*coeff*
Integrals.coulomb(pgs[paramIdx[0]], pgs[paramIdx[1]],
pgs[paramIdx[2]], pgs[paramIdx[3]]);
} // end if
derEle.setI(derEle.getI() + terma + termb); // x component
if (m>0) {
xPG.setPowers(new Power(l,m-1,n));
xPG.normalize();
termb = -2.0*m*Math.sqrt(currentAlpha/(2.*m-1))*coeff*
Integrals.coulomb(pgs[paramIdx[0]], pgs[paramIdx[1]],
pgs[paramIdx[2]], pgs[paramIdx[3]]);
} // end if
derEle.setJ(derEle.getJ() + terma + termb); // y component
if (n>0) {
xPG.setPowers(new Power(l,m,n-1));
xPG.normalize();
termb = -2.0*n*Math.sqrt(currentAlpha/(2.*n-1))*coeff*
Integrals.coulomb(pgs[paramIdx[0]], pgs[paramIdx[1]],
pgs[paramIdx[2]], pgs[paramIdx[3]]);
} // end if
derEle.setK(derEle.getK() + terma + termb); // z component
}
/**
* compute the 2E integrals using shell pair based method, and store it in
* a single 1D array, in the form [ijkl].
*
* This method has been modified to take advantage of multi core systems
* where available.
*/
protected void compute2EShellPair() {
// TODO : parallel
ArrayList<ContractedGaussian> bfs = basisFunctions.getBasisFunctions();
// allocate required memory
int noOfBasisFunctions = bfs.size();
int noOfIntegrals = noOfBasisFunctions * (noOfBasisFunctions + 1)
* (noOfBasisFunctions * noOfBasisFunctions
+ noOfBasisFunctions + 2) / 8;
twoEIntegrals = new double[noOfIntegrals];
int noOfAtoms = molecule.getNumberOfAtoms();
int a, b, c, d;
int i, j, k, l;
int naFunc, nbFunc, ncFunc, ndFunc, twoEIndx;
ArrayList<ContractedGaussian> aFunc, bFunc, cFunc, dFunc;
ContractedGaussian iaFunc, jbFunc, kcFunc, ldFunc;
// center a
for(a=0; a<noOfAtoms; a++) {
aFunc = (ArrayList<ContractedGaussian>) molecule.getAtom(a)
.getUserDefinedAtomProperty("basisFunctions").getValue();
naFunc = aFunc.size();
// basis functions on a
for(i=0; i<naFunc; i++) {
iaFunc = aFunc.get(i);
// center b
for(b=0; b<=a; b++) {
bFunc = (ArrayList<ContractedGaussian>) molecule.getAtom(b)
.getUserDefinedAtomProperty("basisFunctions").getValue();
nbFunc = (b<a) ? bFunc.size() : i+1;
// basis functions on b
for(j=0; j<nbFunc; j++) {
jbFunc = bFunc.get(j);
// center c
for(c=0; c<noOfAtoms; c++) {
cFunc = (ArrayList<ContractedGaussian>)
molecule.getAtom(c).getUserDefinedAtomProperty(
"basisFunctions").getValue();
ncFunc = cFunc.size();
// basis functions on c
for(k=0; k<ncFunc; k++) {
kcFunc = cFunc.get(k);
// center d
for(d=0; d<=c; d++) {
dFunc = (ArrayList<ContractedGaussian>)
molecule.getAtom(d)
.getUserDefinedAtomProperty(
"basisFunctions").getValue();
ndFunc = (d<c) ? dFunc.size() : k+1;
// basis functions on d
for(l=0; l<ndFunc; l++) {
ldFunc = dFunc.get(l);
twoEIndx = IntegralsUtil.ijkl2intindex(
iaFunc.getIndex(),
jbFunc.getIndex(),
kcFunc.getIndex(),
ldFunc.getIndex());
twoEIntegrals[twoEIndx] =
compute2E(iaFunc, jbFunc,
kcFunc, ldFunc);
} // end for (l)
} // end for (d)
} // end for (k)
} // end for (c)
} // end for (j)
} // end for (b)
} // end for (i)
} // end for (a)
}
/**
*
* Compute an integral centered at <ij|kl>
*
* @return the value of two integral electron
*/
public double compute2E(int i, int j, int k, int l) {
// if we really need to compute, go ahead!
ArrayList<ContractedGaussian> bfs = basisFunctions.getBasisFunctions();
return Integrals.coulomb(bfs.get(i), bfs.get(j),
bfs.get(k), bfs.get(l));
}
/**
*
* Compute an integral centered at <ij|kl>
*
* @return the value of two integral electron
*/
public double compute2E(ContractedGaussian cgi, ContractedGaussian cgj,
ContractedGaussian cgk, ContractedGaussian cgl) {
return Integrals.coulomb(cgi, cgj, cgk, cgl);
}
/**
* Getter for property twoEIntegrals.
* @return Value of property twoEIntegrals.
*/
public double[] getTwoEIntegrals() {
return this.twoEIntegrals;
}
/**
* Setter for property twoEIntegrals.
* @param twoEIntegrals New value of property twoEIntegrals.
*/
public void setTwoEIntegrals(double[] twoEIntegrals) {
this.twoEIntegrals = twoEIntegrals;
}
private int atomIndex;
private SCFMethod scfMethod;
/**
* Return the derivatives of the two electron integrals.
*
* @param atomIndex the reference atom index
* @param scfMethod the reference SCF method
*/
public void compute2EDerivatives(int atomIndex, SCFMethod scfMethod) {
this.atomIndex = atomIndex;
this.scfMethod = scfMethod;
twoEDer = new ArrayList<double []>();
double [] dxTwoE = new double[twoEIntegrals.length];
double [] dyTwoE = new double[twoEIntegrals.length];
double [] dzTwoE = new double[twoEIntegrals.length];
twoEDer.add(dxTwoE);
twoEDer.add(dyTwoE);
twoEDer.add(dzTwoE);
SimpleParallelTaskExecuter pTaskExecuter
= new SimpleParallelTaskExecuter();
TwoElectronIntegralDerivativeEvaluaterThread tThread
= new TwoElectronIntegralDerivativeEvaluaterThread();
tThread.setTaskName("TwoElectronIntegralDerivativeEvaluater Thread");
tThread.setTotalItems(basisFunctions.getBasisFunctions().size());
pTaskExecuter.execute(tThread);
}
protected ArrayList<double []> twoEDer;
/**
* The currently computed list of two electron derivatives
*
* @return partial derivatives of 2E integrals, computed in previous call
* to compute2EDerivatives()
*/
public ArrayList<double []> getTwoEDer() {
return twoEDer;
}
/**
* Class encapsulating the way to compute 2E electrons in a way
* useful for utilizing multi core (processor) systems.
*/
protected class TwoElectronIntegralEvaluaterThread
extends AbstractSimpleParallelTask {
private int startBasisFunction, endBasisFunction;
private ArrayList<ContractedGaussian> bfs;
public TwoElectronIntegralEvaluaterThread() { }
public TwoElectronIntegralEvaluaterThread(int startBasisFunction,
int endBasisFunction,
ArrayList<ContractedGaussian> bfs) {
this.startBasisFunction = startBasisFunction;
this.endBasisFunction = endBasisFunction;
this.bfs = bfs;
setTaskName("TwoElectronIntegralEvaluater Thread");
}
/**
* Overridden run()
*/
@Override
public void run() {
compute2E(startBasisFunction, endBasisFunction, bfs);
}
/** Overridden init() */
@Override
public SimpleParallelTask init(int startItem, int endItem) {
return new TwoElectronIntegralEvaluaterThread(
startItem, endItem,
basisFunctions.getBasisFunctions());
}
} // end of class TwoElectronIntegralEvaluaterThread
/**
* Class encapsulating the way to compute 2E electrons in a way
* useful for utilizing multi core (processor) systems.
*/
protected class TwoElectronIntegralDerivativeEvaluaterThread
extends AbstractSimpleParallelTask {
private int startBasisFunction, endBasisFunction;
private ArrayList<ContractedGaussian> bfs;
public TwoElectronIntegralDerivativeEvaluaterThread() { }
public TwoElectronIntegralDerivativeEvaluaterThread(
int startBasisFunction,
int endBasisFunction,
ArrayList<ContractedGaussian> bfs) {
this.startBasisFunction = startBasisFunction;
this.endBasisFunction = endBasisFunction;
this.bfs = bfs;
setTaskName("TwoElectronIntegralDerivativeEvaluater Thread");
}
/**
* Overridden run()
*/
@Override
public void run() {
compute2EDerivative(startBasisFunction, endBasisFunction, bfs);
}
/** Overridden init() */
@Override
public SimpleParallelTask init(int startItem, int endItem) {
return new TwoElectronIntegralDerivativeEvaluaterThread(
startItem, endItem,
basisFunctions.getBasisFunctions());
}
} // end of class TwoElectronIntegralEvaluaterThread
/** Calculate integrals on the fly instead of storing them in an array */
protected boolean onTheFly;
/**
* Get the value of onTheFly
*
* @return the value of onTheFly
*/
public boolean isOnTheFly() {
return onTheFly;
}
/**
* Set the value of onTheFly
*
* @param onTheFly new value of onTheFly
*/
public void setOnTheFly(boolean onTheFly) {
this.onTheFly = onTheFly;
}
} // end of class TwoElectronIntegrals
| tovganesh/metastudio | metastudio/src/org/meta/math/qm/TwoElectronIntegrals.java | 7,143 | // end of j loop | line_comment | nl | /*
* TwoElectronIntegrals.java
*
* Created on July 28, 2004, 7:03 AM
*/
package org.meta.math.qm;
import java.util.*;
import org.meta.math.geom.Point3D;
import org.meta.math.Vector3D;
import org.meta.math.qm.basis.ContractedGaussian;
import org.meta.math.qm.basis.Power;
import org.meta.math.qm.basis.PrimitiveGaussian;
import org.meta.math.qm.integral.Integrals;
import org.meta.math.qm.integral.IntegralsUtil;
import org.meta.molecule.Molecule;
import org.meta.parallel.AbstractSimpleParallelTask;
import org.meta.parallel.SimpleParallelTask;
import org.meta.parallel.SimpleParallelTaskExecuter;
/**
* The 2E integral driver.
*
* @author V.Ganesh
* @version 2.0 (Part of MeTA v2.0)
*/
public class TwoElectronIntegrals {
private BasisFunctions basisFunctions;
private Molecule molecule;
/**
* Holds value of property twoEIntegrals.
*/
private double[] twoEIntegrals;
/**
* Creates a new instance of TwoElectronIntegrals
*
* @param basisFunctions the basis functions to be used
*/
public TwoElectronIntegrals(BasisFunctions basisFunctions) {
this(basisFunctions, false);
}
/**
* Creates a new instance of TwoElectronIntegrals
*
* @param basisFunctions the basis functions to be used
* @param onTheFly if true, the 2E integrals are not calculated and stored,
* they must be calculated individually by calling compute2E(i,j,k,l)
*/
public TwoElectronIntegrals(BasisFunctions basisFunctions,
boolean onTheFly) {
this.basisFunctions = basisFunctions;
this.onTheFly = onTheFly;
// compute the 2E integrals
if (!onTheFly) {
try {
compute2E(); // try to do compute 2E incore
} catch(OutOfMemoryError e) {
// if no memory, resort to direct SCF
System.err.println("No memory for in-core integral evaluation" +
". Switching to direct integral evaluation.");
System.gc();
this.onTheFly = true;
} // end of try catch block
} // end if
}
/**
* Creates a new instance of TwoElectronIntegrals, and computes
* two electron intergrals using shell-pair method rather than the
* conventional loop over all basis functions approach. Note that, this
* requires the Molecule object to be passed as an argument for it to
* function correctly. Note that the Atom objects which are a part of
* Molecule object must be specially configured to have a user defined
* property called "basisFunctions" that is essentially a list of
* ContractedGaussians that are centered on the atom. If this breaks, then
* the code will silentely default to using the conventional way of
* computing the two electron intergrals.
*
* @param molecule
* @param onTheFly if true, the 2E integrals are not calculated and stored,
* they must be calculated individually by calling
* compute2EShellPair(i,j,k,l)
*/
public TwoElectronIntegrals(BasisFunctions basisFunctions,
Molecule molecule, boolean onTheFly) {
this.basisFunctions = basisFunctions;
this.molecule = molecule;
this.onTheFly = onTheFly;
// compute the 2E integrals
if (!onTheFly) {
try {
// first try in - core method
try {
compute2EShellPair(); // try to use shell pair algorithm
} catch(Exception ignored) {
System.err.println("WARNING: Using a slower algorithm" +
" to compute two electron integrals. Error is: "
+ ignored.toString());
ignored.printStackTrace();
compute2E(); // if it doesn't succeed then fall back to normal
} // end if
} catch(OutOfMemoryError e) {
// if no memory, resort to direct SCF
System.err.println("No memory for in-core integral evaluation" +
". Switching to direct integral evaluation.");
System.gc();
this.onTheFly = true;
} // end if
} // end if
}
/**
* compute the 2E integrals, and store it in a single 1D array,
* in the form [ijkl].
*
* This method has been modified to take advantage of multi core systems
* where available.
*/
protected void compute2E() {
ArrayList<ContractedGaussian> bfs = basisFunctions.getBasisFunctions();
// allocate required memory
int noOfBasisFunctions = bfs.size();
int noOfIntegrals = noOfBasisFunctions * (noOfBasisFunctions + 1)
* (noOfBasisFunctions * noOfBasisFunctions
+ noOfBasisFunctions + 2) / 8;
twoEIntegrals = new double[noOfIntegrals];
SimpleParallelTaskExecuter pTaskExecuter
= new SimpleParallelTaskExecuter();
TwoElectronIntegralEvaluaterThread tThread
= new TwoElectronIntegralEvaluaterThread();
tThread.setTaskName("TwoElectronIntegralEvaluater Thread");
tThread.setTotalItems(noOfBasisFunctions);
pTaskExecuter.execute(tThread);
}
/**
* Actually compute the 2E integrals
*/
private void compute2E(int startBasisFunction, int endBasisFunction,
ArrayList<ContractedGaussian> bfs) {
int i, j, k, l, ij, kl, ijkl;
int noOfBasisFunctions = bfs.size();
ContractedGaussian bfi, bfj, bfk, bfl;
// we only need i <= j, k <= l, and ij >= kl
for(i=startBasisFunction; i<endBasisFunction; i++) {
bfi = bfs.get(i);
for(j=0; j<(i+1); j++) {
bfj = bfs.get(j);
ij = i * (i+1) / 2+j;
for(k=0; k<noOfBasisFunctions; k++) {
bfk = bfs.get(k);
for(l=0; l<(k+1); l++) {
bfl = bfs.get(l);
kl = k * (k+1) / 2+l;
if (ij >= kl) {
ijkl = IntegralsUtil.ijkl2intindex(i, j, k, l);
// record the 2E integrals
twoEIntegrals[ijkl] = Integrals.coulomb(bfi, bfj,
bfk, bfl);
} // end if
} // end l loop
} // end k loop
} // end of<SUF>
} // end of i loop
}
/**
* Actually compute the 2E integrals derivatives
*/
private void compute2EDerivative(int startBasisFunction, int endBasisFunction,
ArrayList<ContractedGaussian> bfs) {
int i, j, k, l, ij, kl, ijkl;
int noOfBasisFunctions = bfs.size();
ContractedGaussian bfi, bfj, bfk, bfl;
double [] dxTwoE = twoEDer.get(0);
double [] dyTwoE = twoEDer.get(1);
double [] dzTwoE = twoEDer.get(2);
// we only need i <= j, k <= l, and ij >= kl
for(i=startBasisFunction; i<endBasisFunction; i++) {
bfi = bfs.get(i);
for(j=0; j<(i+1); j++) {
bfj = bfs.get(j);
ij = i * (i+1) / 2+j;
for(k=0; k<noOfBasisFunctions; k++) {
bfk = bfs.get(k);
for(l=0; l<(k+1); l++) {
bfl = bfs.get(l);
kl = k * (k+1) / 2+l;
if (ij >= kl) {
ijkl = IntegralsUtil.ijkl2intindex(i, j, k, l);
// record derivative of the 2E integrals
Vector3D twoEDerEle
= compute2EDerivativeElement(bfi, bfj, bfk, bfl);
dxTwoE[ijkl] = twoEDerEle.getI();
dyTwoE[ijkl] = twoEDerEle.getJ();
dzTwoE[ijkl] = twoEDerEle.getK();
} // end if
} // end l loop
} // end k loop
} // end of j loop
} // end of i loop
}
/** Compute a single 2E derivative element */
private Vector3D compute2EDerivativeElement(ContractedGaussian bfi,
ContractedGaussian bfj, ContractedGaussian bfk, ContractedGaussian bfl) {
Vector3D twoEDerEle = new Vector3D();
int [] paramIdx;
Power currentPower;
Point3D currentOrigin;
double currentAlpha;
if (bfi.getCenteredAtom().getIndex() == atomIndex) {
paramIdx = new int[]{4, 1, 2, 3};
for(PrimitiveGaussian iPG : bfi.getPrimitives()) {
currentOrigin = iPG.getOrigin();
currentPower = iPG.getPowers();
currentAlpha = iPG.getExponent();
for(PrimitiveGaussian jPG : bfj.getPrimitives()) {
for(PrimitiveGaussian kPG : bfk.getPrimitives()) {
for(PrimitiveGaussian lPG : bfl.getPrimitives()) {
compute2EDerivativeElementHelper(iPG, jPG,
kPG, lPG, currentOrigin, currentPower,
currentAlpha, paramIdx, twoEDerEle);
} // end for
} // end for
} // end for
} // end for
} // end if
if (bfj.getCenteredAtom().getIndex() == atomIndex) {
paramIdx = new int[]{0, 4, 2, 3};
for(PrimitiveGaussian iPG : bfi.getPrimitives()) {
for(PrimitiveGaussian jPG : bfj.getPrimitives()) {
currentOrigin = jPG.getOrigin();
currentPower = jPG.getPowers();
currentAlpha = jPG.getExponent();
for(PrimitiveGaussian kPG : bfk.getPrimitives()) {
for(PrimitiveGaussian lPG : bfl.getPrimitives()) {
compute2EDerivativeElementHelper(iPG, jPG,
kPG, lPG, currentOrigin, currentPower,
currentAlpha, paramIdx, twoEDerEle);
} // end for
} // end for
} // end for
} // end for
} // end if
if (bfk.getCenteredAtom().getIndex() == atomIndex) {
paramIdx = new int[]{0, 1, 4, 3};
for(PrimitiveGaussian iPG : bfi.getPrimitives()) {
for(PrimitiveGaussian jPG : bfj.getPrimitives()) {
for(PrimitiveGaussian kPG : bfk.getPrimitives()) {
currentOrigin = kPG.getOrigin();
currentPower = kPG.getPowers();
currentAlpha = kPG.getExponent();
for(PrimitiveGaussian lPG : bfl.getPrimitives()) {
compute2EDerivativeElementHelper(iPG, jPG,
kPG, lPG, currentOrigin, currentPower,
currentAlpha, paramIdx, twoEDerEle);
} // end for
} // end for
} // end for
} // end for
} // end if
if (bfl.getCenteredAtom().getIndex() == atomIndex) {
paramIdx = new int[]{0, 1, 2, 4};
for(PrimitiveGaussian iPG : bfi.getPrimitives()) {
for(PrimitiveGaussian jPG : bfj.getPrimitives()) {
for(PrimitiveGaussian kPG : bfk.getPrimitives()) {
for(PrimitiveGaussian lPG : bfl.getPrimitives()) {
currentOrigin = lPG.getOrigin();
currentPower = lPG.getPowers();
currentAlpha = lPG.getExponent();
compute2EDerivativeElementHelper(iPG, jPG,
kPG, lPG, currentOrigin, currentPower,
currentAlpha, paramIdx, twoEDerEle);
} // end for
} // end for
} // end for
} // end for
} // end if
return twoEDerEle;
}
/** helper for computing 2E derivative */
private void compute2EDerivativeElementHelper(PrimitiveGaussian iPG,
PrimitiveGaussian jPG, PrimitiveGaussian kPG, PrimitiveGaussian lPG,
Point3D currentOrigin, Power currentPower, double currentAlpha,
int [] paramIdx, Vector3D derEle) {
int l = currentPower.getL(),
m = currentPower.getM(),
n = currentPower.getN();
double coeff = iPG.getCoefficient()*jPG.getCoefficient()
*kPG.getCoefficient()*lPG.getCoefficient();
PrimitiveGaussian xPG = new PrimitiveGaussian(currentOrigin,
new Power(l+1,m,n), currentAlpha, coeff);
xPG.normalize();
PrimitiveGaussian [] pgs
= new PrimitiveGaussian[]{iPG, jPG, kPG, lPG, xPG};
double terma = Math.sqrt(currentAlpha*(2.0*l+1.0))*coeff*
Integrals.coulomb(pgs[paramIdx[0]], pgs[paramIdx[1]],
pgs[paramIdx[2]], pgs[paramIdx[3]]),
termb = 0.0;
if (l>0) {
xPG.setPowers(new Power(l-1,m,n));
xPG.normalize();
termb = -2.0*l*Math.sqrt(currentAlpha/(2.*l-1))*coeff*
Integrals.coulomb(pgs[paramIdx[0]], pgs[paramIdx[1]],
pgs[paramIdx[2]], pgs[paramIdx[3]]);
} // end if
derEle.setI(derEle.getI() + terma + termb); // x component
if (m>0) {
xPG.setPowers(new Power(l,m-1,n));
xPG.normalize();
termb = -2.0*m*Math.sqrt(currentAlpha/(2.*m-1))*coeff*
Integrals.coulomb(pgs[paramIdx[0]], pgs[paramIdx[1]],
pgs[paramIdx[2]], pgs[paramIdx[3]]);
} // end if
derEle.setJ(derEle.getJ() + terma + termb); // y component
if (n>0) {
xPG.setPowers(new Power(l,m,n-1));
xPG.normalize();
termb = -2.0*n*Math.sqrt(currentAlpha/(2.*n-1))*coeff*
Integrals.coulomb(pgs[paramIdx[0]], pgs[paramIdx[1]],
pgs[paramIdx[2]], pgs[paramIdx[3]]);
} // end if
derEle.setK(derEle.getK() + terma + termb); // z component
}
/**
* compute the 2E integrals using shell pair based method, and store it in
* a single 1D array, in the form [ijkl].
*
* This method has been modified to take advantage of multi core systems
* where available.
*/
protected void compute2EShellPair() {
// TODO : parallel
ArrayList<ContractedGaussian> bfs = basisFunctions.getBasisFunctions();
// allocate required memory
int noOfBasisFunctions = bfs.size();
int noOfIntegrals = noOfBasisFunctions * (noOfBasisFunctions + 1)
* (noOfBasisFunctions * noOfBasisFunctions
+ noOfBasisFunctions + 2) / 8;
twoEIntegrals = new double[noOfIntegrals];
int noOfAtoms = molecule.getNumberOfAtoms();
int a, b, c, d;
int i, j, k, l;
int naFunc, nbFunc, ncFunc, ndFunc, twoEIndx;
ArrayList<ContractedGaussian> aFunc, bFunc, cFunc, dFunc;
ContractedGaussian iaFunc, jbFunc, kcFunc, ldFunc;
// center a
for(a=0; a<noOfAtoms; a++) {
aFunc = (ArrayList<ContractedGaussian>) molecule.getAtom(a)
.getUserDefinedAtomProperty("basisFunctions").getValue();
naFunc = aFunc.size();
// basis functions on a
for(i=0; i<naFunc; i++) {
iaFunc = aFunc.get(i);
// center b
for(b=0; b<=a; b++) {
bFunc = (ArrayList<ContractedGaussian>) molecule.getAtom(b)
.getUserDefinedAtomProperty("basisFunctions").getValue();
nbFunc = (b<a) ? bFunc.size() : i+1;
// basis functions on b
for(j=0; j<nbFunc; j++) {
jbFunc = bFunc.get(j);
// center c
for(c=0; c<noOfAtoms; c++) {
cFunc = (ArrayList<ContractedGaussian>)
molecule.getAtom(c).getUserDefinedAtomProperty(
"basisFunctions").getValue();
ncFunc = cFunc.size();
// basis functions on c
for(k=0; k<ncFunc; k++) {
kcFunc = cFunc.get(k);
// center d
for(d=0; d<=c; d++) {
dFunc = (ArrayList<ContractedGaussian>)
molecule.getAtom(d)
.getUserDefinedAtomProperty(
"basisFunctions").getValue();
ndFunc = (d<c) ? dFunc.size() : k+1;
// basis functions on d
for(l=0; l<ndFunc; l++) {
ldFunc = dFunc.get(l);
twoEIndx = IntegralsUtil.ijkl2intindex(
iaFunc.getIndex(),
jbFunc.getIndex(),
kcFunc.getIndex(),
ldFunc.getIndex());
twoEIntegrals[twoEIndx] =
compute2E(iaFunc, jbFunc,
kcFunc, ldFunc);
} // end for (l)
} // end for (d)
} // end for (k)
} // end for (c)
} // end for (j)
} // end for (b)
} // end for (i)
} // end for (a)
}
/**
*
* Compute an integral centered at <ij|kl>
*
* @return the value of two integral electron
*/
public double compute2E(int i, int j, int k, int l) {
// if we really need to compute, go ahead!
ArrayList<ContractedGaussian> bfs = basisFunctions.getBasisFunctions();
return Integrals.coulomb(bfs.get(i), bfs.get(j),
bfs.get(k), bfs.get(l));
}
/**
*
* Compute an integral centered at <ij|kl>
*
* @return the value of two integral electron
*/
public double compute2E(ContractedGaussian cgi, ContractedGaussian cgj,
ContractedGaussian cgk, ContractedGaussian cgl) {
return Integrals.coulomb(cgi, cgj, cgk, cgl);
}
/**
* Getter for property twoEIntegrals.
* @return Value of property twoEIntegrals.
*/
public double[] getTwoEIntegrals() {
return this.twoEIntegrals;
}
/**
* Setter for property twoEIntegrals.
* @param twoEIntegrals New value of property twoEIntegrals.
*/
public void setTwoEIntegrals(double[] twoEIntegrals) {
this.twoEIntegrals = twoEIntegrals;
}
private int atomIndex;
private SCFMethod scfMethod;
/**
* Return the derivatives of the two electron integrals.
*
* @param atomIndex the reference atom index
* @param scfMethod the reference SCF method
*/
public void compute2EDerivatives(int atomIndex, SCFMethod scfMethod) {
this.atomIndex = atomIndex;
this.scfMethod = scfMethod;
twoEDer = new ArrayList<double []>();
double [] dxTwoE = new double[twoEIntegrals.length];
double [] dyTwoE = new double[twoEIntegrals.length];
double [] dzTwoE = new double[twoEIntegrals.length];
twoEDer.add(dxTwoE);
twoEDer.add(dyTwoE);
twoEDer.add(dzTwoE);
SimpleParallelTaskExecuter pTaskExecuter
= new SimpleParallelTaskExecuter();
TwoElectronIntegralDerivativeEvaluaterThread tThread
= new TwoElectronIntegralDerivativeEvaluaterThread();
tThread.setTaskName("TwoElectronIntegralDerivativeEvaluater Thread");
tThread.setTotalItems(basisFunctions.getBasisFunctions().size());
pTaskExecuter.execute(tThread);
}
protected ArrayList<double []> twoEDer;
/**
* The currently computed list of two electron derivatives
*
* @return partial derivatives of 2E integrals, computed in previous call
* to compute2EDerivatives()
*/
public ArrayList<double []> getTwoEDer() {
return twoEDer;
}
/**
* Class encapsulating the way to compute 2E electrons in a way
* useful for utilizing multi core (processor) systems.
*/
protected class TwoElectronIntegralEvaluaterThread
extends AbstractSimpleParallelTask {
private int startBasisFunction, endBasisFunction;
private ArrayList<ContractedGaussian> bfs;
public TwoElectronIntegralEvaluaterThread() { }
public TwoElectronIntegralEvaluaterThread(int startBasisFunction,
int endBasisFunction,
ArrayList<ContractedGaussian> bfs) {
this.startBasisFunction = startBasisFunction;
this.endBasisFunction = endBasisFunction;
this.bfs = bfs;
setTaskName("TwoElectronIntegralEvaluater Thread");
}
/**
* Overridden run()
*/
@Override
public void run() {
compute2E(startBasisFunction, endBasisFunction, bfs);
}
/** Overridden init() */
@Override
public SimpleParallelTask init(int startItem, int endItem) {
return new TwoElectronIntegralEvaluaterThread(
startItem, endItem,
basisFunctions.getBasisFunctions());
}
} // end of class TwoElectronIntegralEvaluaterThread
/**
* Class encapsulating the way to compute 2E electrons in a way
* useful for utilizing multi core (processor) systems.
*/
protected class TwoElectronIntegralDerivativeEvaluaterThread
extends AbstractSimpleParallelTask {
private int startBasisFunction, endBasisFunction;
private ArrayList<ContractedGaussian> bfs;
public TwoElectronIntegralDerivativeEvaluaterThread() { }
public TwoElectronIntegralDerivativeEvaluaterThread(
int startBasisFunction,
int endBasisFunction,
ArrayList<ContractedGaussian> bfs) {
this.startBasisFunction = startBasisFunction;
this.endBasisFunction = endBasisFunction;
this.bfs = bfs;
setTaskName("TwoElectronIntegralDerivativeEvaluater Thread");
}
/**
* Overridden run()
*/
@Override
public void run() {
compute2EDerivative(startBasisFunction, endBasisFunction, bfs);
}
/** Overridden init() */
@Override
public SimpleParallelTask init(int startItem, int endItem) {
return new TwoElectronIntegralDerivativeEvaluaterThread(
startItem, endItem,
basisFunctions.getBasisFunctions());
}
} // end of class TwoElectronIntegralEvaluaterThread
/** Calculate integrals on the fly instead of storing them in an array */
protected boolean onTheFly;
/**
* Get the value of onTheFly
*
* @return the value of onTheFly
*/
public boolean isOnTheFly() {
return onTheFly;
}
/**
* Set the value of onTheFly
*
* @param onTheFly new value of onTheFly
*/
public void setOnTheFly(boolean onTheFly) {
this.onTheFly = onTheFly;
}
} // end of class TwoElectronIntegrals
|
37363_34 | package jmri.jmrix.sprog.simulator;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import jmri.jmrix.sprog.SprogConstants.SprogMode;
import jmri.jmrix.sprog.SprogMessage;
import jmri.jmrix.sprog.SprogPortController; // no special xSimulatorController
import jmri.jmrix.sprog.SprogReply;
import jmri.jmrix.sprog.SprogSystemConnectionMemo;
import jmri.jmrix.sprog.SprogTrafficController;
import jmri.util.ImmediatePipedOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provide access to a simulated SPROG system.
* <p>
* Can be loaded as either a Programmer or Command Station.
* The SPROG SimulatorAdapter reacts to commands sent from the user interface
* with an appropriate reply message.
* <p>
* Based on jmri.jmrix.lenz.xnetsimulator.XNetSimulatorAdapter / DCCppSimulatorAdapter 2017
*
* @author Paul Bender, Copyright (C) 2009-2010
* @author Mark Underwood, Copyright (C) 2015
* @author Egbert Broerse, Copyright (C) 2018
*/
public class SimulatorAdapter extends SprogPortController implements Runnable {
// private control members
private boolean opened = false;
private Thread sourceThread;
private SprogTrafficController control;
private boolean outputBufferEmpty = true;
private boolean checkBuffer = true;
private SprogMode operatingMode = SprogMode.SERVICE;
// Simulator responses
String SPR_OK = "OK";
String SPR_NO = "No Ack";
String SPR_PR = "\nP> "; // prompt
public SimulatorAdapter() {
super(new SprogSystemConnectionMemo(SprogMode.SERVICE)); // use default user name
// starts as SERVICE mode (Programmer); may be set to OPS (Command Station) from connection option
setManufacturer(jmri.jmrix.sprog.SprogConnectionTypeList.SPROG);
this.getSystemConnectionMemo().setUserName(Bundle.getMessage("SprogSimulatorTitle"));
// create the traffic controller
control = new SprogTrafficController(this.getSystemConnectionMemo());
this.getSystemConnectionMemo().setSprogTrafficController(control);
options.put("OperatingMode", // NOI18N
new Option(Bundle.getMessage("MakeLabel", Bundle.getMessage("SprogSimOption")), // NOI18N
new String[]{Bundle.getMessage("SprogProgrammerTitle"),
Bundle.getMessage("SprogCSTitle")}, true));
}
/**
* {@inheritDoc}
* Simulated input/output pipes.
*/
@Override
public String openPort(String portName, String appName) {
try {
PipedOutputStream tempPipeI = new ImmediatePipedOutputStream();
log.debug("tempPipeI created");
pout = new DataOutputStream(tempPipeI);
inpipe = new DataInputStream(new PipedInputStream(tempPipeI));
log.debug("inpipe created {}", inpipe != null);
PipedOutputStream tempPipeO = new ImmediatePipedOutputStream();
outpipe = new DataOutputStream(tempPipeO);
pin = new DataInputStream(new PipedInputStream(tempPipeO));
} catch (java.io.IOException e) {
log.error("init (pipe): Exception: {}", e.toString());
}
opened = true;
return null; // indicates OK return
}
/**
* Set if the output buffer is empty or full. This should only be set to
* false by external processes.
*
* @param s true if output buffer is empty; false otherwise
*/
synchronized public void setOutputBufferEmpty(boolean s) {
outputBufferEmpty = s;
}
/**
* Can the port accept additional characters? The state of CTS determines
* this, as there seems to be no way to check the number of queued bytes and
* buffer length. This might go false for short intervals, but it might also
* stick off if something goes wrong.
*
* @return true if port can accept additional characters; false otherwise
*/
public boolean okToSend() {
if (checkBuffer) {
log.debug("Buffer Empty: {}", outputBufferEmpty);
return (outputBufferEmpty);
} else {
log.debug("No Flow Control or Buffer Check");
return (true);
}
}
/**
* Set up all of the other objects to operate with a Sprog Simulator.
*/
@Override
public void configure() {
// connect to the traffic controller
this.getSystemConnectionMemo().getSprogTrafficController().connectPort(this);
if (getOptionState("OperatingMode") != null && getOptionState("OperatingMode").equals(Bundle.getMessage("SprogProgrammerTitle"))) {
operatingMode = SprogMode.SERVICE;
} else { // default, also used after Locale change
operatingMode = SprogMode.OPS;
}
this.getSystemConnectionMemo().setSprogMode(operatingMode); // first update mode in memo
this.getSystemConnectionMemo().configureCommandStation(); // CS only if in OPS mode, memo will take care of that
this.getSystemConnectionMemo().configureManagers(); // wait for mode to be correct
if (getOptionState("TrackPowerState") != null && getOptionState("TrackPowerState").equals(Bundle.getMessage("PowerStateOn"))) {
try {
this.getSystemConnectionMemo().getPowerManager().setPower(jmri.PowerManager.ON);
} catch (jmri.JmriException e) {
log.error(e.toString());
}
}
log.debug("SimulatorAdapter configure() with prefix = {}", this.getSystemConnectionMemo().getSystemPrefix());
// start the simulator
sourceThread = new Thread(this);
sourceThread.setName("SPROG Simulator");
sourceThread.setPriority(Thread.MIN_PRIORITY);
sourceThread.start();
}
/**
* {@inheritDoc}
*/
@Override
public void connect() throws java.io.IOException {
log.debug("connect called");
super.connect();
}
// Base class methods for the SprogPortController simulated interface
/**
* {@inheritDoc}
*/
@Override
public DataInputStream getInputStream() {
if (!opened || pin == null) {
log.error("getInputStream called before load(), stream not available");
}
log.debug("DataInputStream pin returned");
return pin;
}
/**
* {@inheritDoc}
*/
@Override
public DataOutputStream getOutputStream() {
if (!opened || pout == null) {
log.error("getOutputStream called before load(), stream not available");
}
log.debug("DataOutputStream pout returned");
return pout;
}
/**
* {@inheritDoc}
*/
@Override
public boolean status() {
return (pout != null && pin != null);
}
/**
* {@inheritDoc}
*
* @return null
*/
@Override
public String[] validBaudRates() {
log.debug("validBaudRates should not have been invoked");
return new String[]{};
}
/**
* {@inheritDoc}
*/
@Override
public int[] validBaudNumbers() {
return new int[]{};
}
@Override
public String getCurrentBaudRate() {
return "";
}
@Override
public String getCurrentPortName(){
return "";
}
@Override
public void run() { // start a new thread
// This thread has one task. It repeatedly reads from the input pipe
// and writes an appropriate response to the output pipe. This is the heart
// of the SPROG command station simulation.
log.info("SPROG Simulator Started");
while (true) {
try {
synchronized (this) {
wait(50);
}
} catch (InterruptedException e) {
log.debug("interrupted, ending");
return;
}
SprogMessage m = readMessage();
SprogReply r;
if (log.isDebugEnabled()) {
StringBuffer buf = new StringBuffer();
buf.append("SPROG Simulator Thread received message: ");
if (m != null) {
buf.append(m);
} else {
buf.append("null message buffer");
}
//log.debug(buf.toString()); // generates a lot of output
}
if (m != null) {
r = generateReply(m);
writeReply(r);
if (log.isDebugEnabled() && r != null) {
log.debug("Simulator Thread sent Reply: \"{}\"", r);
}
}
}
}
/**
* Read one incoming message from the buffer
* and set outputBufferEmpty to true.
*/
private SprogMessage readMessage() {
SprogMessage msg = null;
// log.debug("Simulator reading message");
try {
if (inpipe != null && inpipe.available() > 0) {
msg = loadChars();
}
} catch (java.io.IOException e) {
// should do something meaningful here.
}
setOutputBufferEmpty(true);
return (msg);
}
/**
* This is the heart of the simulation. It translates an
* incoming SprogMessage into an outgoing SprogReply.
*
* Based on SPROG information from A. Crosland.
* @see jmri.jmrix.sprog.SprogReply#value()
*/
private SprogReply generateReply(SprogMessage msg) {
log.debug("Generate Reply to message type {} (string = {})", msg.toString().charAt(0), msg.toString());
SprogReply reply = new SprogReply();
int i = 0;
char command = msg.toString().charAt(0);
log.debug("Message type = {}", command);
switch (command) {
case 'I':
log.debug("CurrentQuery detected");
reply = new SprogReply("= h3E7\n"); // reply fictionary current (decimal 999mA)
break;
case 'C':
case 'V':
log.debug("Read/Write CV detected");
reply = new SprogReply("= " + msg.toString().substring(2) + "\n"); // echo CV value (hex)
break;
case 'O':
log.debug("Send packet command detected");
reply = new SprogReply("= " + msg.toString().substring(2) + "\n"); // echo command (hex)
break;
case 'A':
log.debug("Address (open Throttle) command detected");
reply = new SprogReply(msg.toString().substring(2) + "\n"); // echo address (decimal)
break;
case '>':
log.debug("Set speed (Throttle) command detected");
reply = new SprogReply(msg.toString().substring(1) + "\n"); // echo speed (decimal)
break;
case '+':
log.debug("TRACK_POWER_ON detected");
//reply = new SprogReply(SPR_PR);
break;
case '-':
log.debug("TRACK_POWER_OFF detected");
//reply = new SprogReply(SPR_PR);
break;
case '?':
log.debug("Read_Sprog_Version detected");
String replyString = "\nSPROG II Ver 4.3\n";
reply = new SprogReply(replyString);
break;
case 'M':
log.debug("Mode Word detected");
reply = new SprogReply("P>M=h800\n"); // default mode reply
break;
case 'S':
log.debug("getStatus detected");
reply = new SprogReply("OK\n");
break;
default:
log.debug("non-reply message detected: {}", msg.toString());
reply = new SprogReply("!E\n"); // SPROG error reply
}
i = reply.toString().length();
reply.setElement(i++, 'P'); // add prompt to all replies
reply.setElement(i++, '>');
reply.setElement(i++, ' ');
log.debug("Reply generated = \"{}\"", reply.toString());
return reply;
}
/**
* Write reply to output.
* <p>
* Copied from jmri.jmrix.nce.simulator.SimulatorAdapter,
* adapted for {@link jmri.jmrix.sprog.SprogTrafficController#handleOneIncomingReply()}.
*
* @param r reply on message
*/
private void writeReply(SprogReply r) {
if (r == null) {
return; // there is no reply to be sent
}
int len = r.getNumDataElements();
for (int i = 0; i < len; i++) {
try {
outpipe.writeByte((byte) r.getElement(i));
log.debug("{} of {} bytes written to outpipe", i + 1, len);
if (pin.available() > 0) {
control.handleOneIncomingReply();
}
} catch (java.io.IOException ex) {
}
}
try {
outpipe.flush();
} catch (java.io.IOException ex) {
}
}
/**
* Get characters from the input source.
* <p>
* Only used in the Receive thread.
*
* @return filled message, only when the message is complete.
* @throws IOException when presented by the input source.
*/
private SprogMessage loadChars() throws java.io.IOException {
// code copied from EasyDcc/NCE Simulator
int nchars;
byte[] rcvBuffer = new byte[32];
nchars = inpipe.read(rcvBuffer, 0, 32);
//log.debug("new message received");
SprogMessage msg = new SprogMessage(nchars);
for (int i = 0; i < nchars; i++) {
msg.setElement(i, rcvBuffer[i] & 0xFF);
}
return msg;
}
// streams to share with user class
private DataOutputStream pout = null; // this is provided to classes who want to write to us
private DataInputStream pin = null; // this is provided to classes who want data from us
// internal ends of the pipes
private DataOutputStream outpipe = null; // feed pin
private DataInputStream inpipe = null; // feed pout
private final static Logger log = LoggerFactory.getLogger(SimulatorAdapter.class);
}
| trainman419/JMRI | java/src/jmri/jmrix/sprog/simulator/SimulatorAdapter.java | 4,043 | // echo CV value (hex) | line_comment | nl | package jmri.jmrix.sprog.simulator;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import jmri.jmrix.sprog.SprogConstants.SprogMode;
import jmri.jmrix.sprog.SprogMessage;
import jmri.jmrix.sprog.SprogPortController; // no special xSimulatorController
import jmri.jmrix.sprog.SprogReply;
import jmri.jmrix.sprog.SprogSystemConnectionMemo;
import jmri.jmrix.sprog.SprogTrafficController;
import jmri.util.ImmediatePipedOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provide access to a simulated SPROG system.
* <p>
* Can be loaded as either a Programmer or Command Station.
* The SPROG SimulatorAdapter reacts to commands sent from the user interface
* with an appropriate reply message.
* <p>
* Based on jmri.jmrix.lenz.xnetsimulator.XNetSimulatorAdapter / DCCppSimulatorAdapter 2017
*
* @author Paul Bender, Copyright (C) 2009-2010
* @author Mark Underwood, Copyright (C) 2015
* @author Egbert Broerse, Copyright (C) 2018
*/
public class SimulatorAdapter extends SprogPortController implements Runnable {
// private control members
private boolean opened = false;
private Thread sourceThread;
private SprogTrafficController control;
private boolean outputBufferEmpty = true;
private boolean checkBuffer = true;
private SprogMode operatingMode = SprogMode.SERVICE;
// Simulator responses
String SPR_OK = "OK";
String SPR_NO = "No Ack";
String SPR_PR = "\nP> "; // prompt
public SimulatorAdapter() {
super(new SprogSystemConnectionMemo(SprogMode.SERVICE)); // use default user name
// starts as SERVICE mode (Programmer); may be set to OPS (Command Station) from connection option
setManufacturer(jmri.jmrix.sprog.SprogConnectionTypeList.SPROG);
this.getSystemConnectionMemo().setUserName(Bundle.getMessage("SprogSimulatorTitle"));
// create the traffic controller
control = new SprogTrafficController(this.getSystemConnectionMemo());
this.getSystemConnectionMemo().setSprogTrafficController(control);
options.put("OperatingMode", // NOI18N
new Option(Bundle.getMessage("MakeLabel", Bundle.getMessage("SprogSimOption")), // NOI18N
new String[]{Bundle.getMessage("SprogProgrammerTitle"),
Bundle.getMessage("SprogCSTitle")}, true));
}
/**
* {@inheritDoc}
* Simulated input/output pipes.
*/
@Override
public String openPort(String portName, String appName) {
try {
PipedOutputStream tempPipeI = new ImmediatePipedOutputStream();
log.debug("tempPipeI created");
pout = new DataOutputStream(tempPipeI);
inpipe = new DataInputStream(new PipedInputStream(tempPipeI));
log.debug("inpipe created {}", inpipe != null);
PipedOutputStream tempPipeO = new ImmediatePipedOutputStream();
outpipe = new DataOutputStream(tempPipeO);
pin = new DataInputStream(new PipedInputStream(tempPipeO));
} catch (java.io.IOException e) {
log.error("init (pipe): Exception: {}", e.toString());
}
opened = true;
return null; // indicates OK return
}
/**
* Set if the output buffer is empty or full. This should only be set to
* false by external processes.
*
* @param s true if output buffer is empty; false otherwise
*/
synchronized public void setOutputBufferEmpty(boolean s) {
outputBufferEmpty = s;
}
/**
* Can the port accept additional characters? The state of CTS determines
* this, as there seems to be no way to check the number of queued bytes and
* buffer length. This might go false for short intervals, but it might also
* stick off if something goes wrong.
*
* @return true if port can accept additional characters; false otherwise
*/
public boolean okToSend() {
if (checkBuffer) {
log.debug("Buffer Empty: {}", outputBufferEmpty);
return (outputBufferEmpty);
} else {
log.debug("No Flow Control or Buffer Check");
return (true);
}
}
/**
* Set up all of the other objects to operate with a Sprog Simulator.
*/
@Override
public void configure() {
// connect to the traffic controller
this.getSystemConnectionMemo().getSprogTrafficController().connectPort(this);
if (getOptionState("OperatingMode") != null && getOptionState("OperatingMode").equals(Bundle.getMessage("SprogProgrammerTitle"))) {
operatingMode = SprogMode.SERVICE;
} else { // default, also used after Locale change
operatingMode = SprogMode.OPS;
}
this.getSystemConnectionMemo().setSprogMode(operatingMode); // first update mode in memo
this.getSystemConnectionMemo().configureCommandStation(); // CS only if in OPS mode, memo will take care of that
this.getSystemConnectionMemo().configureManagers(); // wait for mode to be correct
if (getOptionState("TrackPowerState") != null && getOptionState("TrackPowerState").equals(Bundle.getMessage("PowerStateOn"))) {
try {
this.getSystemConnectionMemo().getPowerManager().setPower(jmri.PowerManager.ON);
} catch (jmri.JmriException e) {
log.error(e.toString());
}
}
log.debug("SimulatorAdapter configure() with prefix = {}", this.getSystemConnectionMemo().getSystemPrefix());
// start the simulator
sourceThread = new Thread(this);
sourceThread.setName("SPROG Simulator");
sourceThread.setPriority(Thread.MIN_PRIORITY);
sourceThread.start();
}
/**
* {@inheritDoc}
*/
@Override
public void connect() throws java.io.IOException {
log.debug("connect called");
super.connect();
}
// Base class methods for the SprogPortController simulated interface
/**
* {@inheritDoc}
*/
@Override
public DataInputStream getInputStream() {
if (!opened || pin == null) {
log.error("getInputStream called before load(), stream not available");
}
log.debug("DataInputStream pin returned");
return pin;
}
/**
* {@inheritDoc}
*/
@Override
public DataOutputStream getOutputStream() {
if (!opened || pout == null) {
log.error("getOutputStream called before load(), stream not available");
}
log.debug("DataOutputStream pout returned");
return pout;
}
/**
* {@inheritDoc}
*/
@Override
public boolean status() {
return (pout != null && pin != null);
}
/**
* {@inheritDoc}
*
* @return null
*/
@Override
public String[] validBaudRates() {
log.debug("validBaudRates should not have been invoked");
return new String[]{};
}
/**
* {@inheritDoc}
*/
@Override
public int[] validBaudNumbers() {
return new int[]{};
}
@Override
public String getCurrentBaudRate() {
return "";
}
@Override
public String getCurrentPortName(){
return "";
}
@Override
public void run() { // start a new thread
// This thread has one task. It repeatedly reads from the input pipe
// and writes an appropriate response to the output pipe. This is the heart
// of the SPROG command station simulation.
log.info("SPROG Simulator Started");
while (true) {
try {
synchronized (this) {
wait(50);
}
} catch (InterruptedException e) {
log.debug("interrupted, ending");
return;
}
SprogMessage m = readMessage();
SprogReply r;
if (log.isDebugEnabled()) {
StringBuffer buf = new StringBuffer();
buf.append("SPROG Simulator Thread received message: ");
if (m != null) {
buf.append(m);
} else {
buf.append("null message buffer");
}
//log.debug(buf.toString()); // generates a lot of output
}
if (m != null) {
r = generateReply(m);
writeReply(r);
if (log.isDebugEnabled() && r != null) {
log.debug("Simulator Thread sent Reply: \"{}\"", r);
}
}
}
}
/**
* Read one incoming message from the buffer
* and set outputBufferEmpty to true.
*/
private SprogMessage readMessage() {
SprogMessage msg = null;
// log.debug("Simulator reading message");
try {
if (inpipe != null && inpipe.available() > 0) {
msg = loadChars();
}
} catch (java.io.IOException e) {
// should do something meaningful here.
}
setOutputBufferEmpty(true);
return (msg);
}
/**
* This is the heart of the simulation. It translates an
* incoming SprogMessage into an outgoing SprogReply.
*
* Based on SPROG information from A. Crosland.
* @see jmri.jmrix.sprog.SprogReply#value()
*/
private SprogReply generateReply(SprogMessage msg) {
log.debug("Generate Reply to message type {} (string = {})", msg.toString().charAt(0), msg.toString());
SprogReply reply = new SprogReply();
int i = 0;
char command = msg.toString().charAt(0);
log.debug("Message type = {}", command);
switch (command) {
case 'I':
log.debug("CurrentQuery detected");
reply = new SprogReply("= h3E7\n"); // reply fictionary current (decimal 999mA)
break;
case 'C':
case 'V':
log.debug("Read/Write CV detected");
reply = new SprogReply("= " + msg.toString().substring(2) + "\n"); // echo CV<SUF>
break;
case 'O':
log.debug("Send packet command detected");
reply = new SprogReply("= " + msg.toString().substring(2) + "\n"); // echo command (hex)
break;
case 'A':
log.debug("Address (open Throttle) command detected");
reply = new SprogReply(msg.toString().substring(2) + "\n"); // echo address (decimal)
break;
case '>':
log.debug("Set speed (Throttle) command detected");
reply = new SprogReply(msg.toString().substring(1) + "\n"); // echo speed (decimal)
break;
case '+':
log.debug("TRACK_POWER_ON detected");
//reply = new SprogReply(SPR_PR);
break;
case '-':
log.debug("TRACK_POWER_OFF detected");
//reply = new SprogReply(SPR_PR);
break;
case '?':
log.debug("Read_Sprog_Version detected");
String replyString = "\nSPROG II Ver 4.3\n";
reply = new SprogReply(replyString);
break;
case 'M':
log.debug("Mode Word detected");
reply = new SprogReply("P>M=h800\n"); // default mode reply
break;
case 'S':
log.debug("getStatus detected");
reply = new SprogReply("OK\n");
break;
default:
log.debug("non-reply message detected: {}", msg.toString());
reply = new SprogReply("!E\n"); // SPROG error reply
}
i = reply.toString().length();
reply.setElement(i++, 'P'); // add prompt to all replies
reply.setElement(i++, '>');
reply.setElement(i++, ' ');
log.debug("Reply generated = \"{}\"", reply.toString());
return reply;
}
/**
* Write reply to output.
* <p>
* Copied from jmri.jmrix.nce.simulator.SimulatorAdapter,
* adapted for {@link jmri.jmrix.sprog.SprogTrafficController#handleOneIncomingReply()}.
*
* @param r reply on message
*/
private void writeReply(SprogReply r) {
if (r == null) {
return; // there is no reply to be sent
}
int len = r.getNumDataElements();
for (int i = 0; i < len; i++) {
try {
outpipe.writeByte((byte) r.getElement(i));
log.debug("{} of {} bytes written to outpipe", i + 1, len);
if (pin.available() > 0) {
control.handleOneIncomingReply();
}
} catch (java.io.IOException ex) {
}
}
try {
outpipe.flush();
} catch (java.io.IOException ex) {
}
}
/**
* Get characters from the input source.
* <p>
* Only used in the Receive thread.
*
* @return filled message, only when the message is complete.
* @throws IOException when presented by the input source.
*/
private SprogMessage loadChars() throws java.io.IOException {
// code copied from EasyDcc/NCE Simulator
int nchars;
byte[] rcvBuffer = new byte[32];
nchars = inpipe.read(rcvBuffer, 0, 32);
//log.debug("new message received");
SprogMessage msg = new SprogMessage(nchars);
for (int i = 0; i < nchars; i++) {
msg.setElement(i, rcvBuffer[i] & 0xFF);
}
return msg;
}
// streams to share with user class
private DataOutputStream pout = null; // this is provided to classes who want to write to us
private DataInputStream pin = null; // this is provided to classes who want data from us
// internal ends of the pipes
private DataOutputStream outpipe = null; // feed pin
private DataInputStream inpipe = null; // feed pout
private final static Logger log = LoggerFactory.getLogger(SimulatorAdapter.class);
}
|
204382_8 | package org.treblereel.gwt.three4g.geometries.parameters;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import org.treblereel.gwt.three4g.extras.core.Font;
/**
* @author Dmitrii Tikhomirov
* Created by treblereel on 5/3/18.
*/
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
public class TextGeometryParameters {
public Font font; // — an instance of THREE.Font.
public float size; // — Size of the text. Default is 100.
public float height;// - Thickness to extrude text. Default is 50.
public int curveSegments;// - Number of points on the curves. Default is 12.
public boolean bevelEnabled; // — Turn on bevel. Default is False.
public float bevelThickness; // - How deep into text bevel goes. Default is 10.
public float bevelSize; // - How far from text outline is bevel. Default is 8.
public int bevelSegments; // - Number of bevel segments. Default is 3.
}
| treblereel/three4g | core/src/main/java/org/treblereel/gwt/three4g/geometries/parameters/TextGeometryParameters.java | 306 | // - Number of bevel segments. Default is 3. | line_comment | nl | package org.treblereel.gwt.three4g.geometries.parameters;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import org.treblereel.gwt.three4g.extras.core.Font;
/**
* @author Dmitrii Tikhomirov
* Created by treblereel on 5/3/18.
*/
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
public class TextGeometryParameters {
public Font font; // — an instance of THREE.Font.
public float size; // — Size of the text. Default is 100.
public float height;// - Thickness to extrude text. Default is 50.
public int curveSegments;// - Number of points on the curves. Default is 12.
public boolean bevelEnabled; // — Turn on bevel. Default is False.
public float bevelThickness; // - How deep into text bevel goes. Default is 10.
public float bevelSize; // - How far from text outline is bevel. Default is 8.
public int bevelSegments; // - <SUF>
}
|
96349_1 | package bGLOOP;
import java.util.logging.Logger;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.glu.GLUquadric;
/**
* Basisklasse aller bGLOOP-Objekte.
*
* @author R. Spillner
*/
public abstract class GLObjekt extends DisplayItem implements IGLColorable {
Logger log = Logger.getLogger("bGLOOP");
float[] aDiffuse = { 1, 1, 1, 1 };
final private float[] aAmbient = { 0.15f, 0.15f, 0.15f, 1 };
private float[] aSpecular = { 0, 0, 0, 1 };
float[] aEmission = { 0, 0, 0, 0 };
private float aGlanz = 70; // between 0 and 128
private static int maxSelectionID = 0;
int selectionID = 0;
/**
* Der Darstellungsmodus beschreibt, wie ein Objekt gezeichnet wird. Dabei
* gibt es drei Möglichkeiten: als Punktgrafik, als Gitternetzgrafik oder
* als durchgehend gefüllte Struktur.
*
* @author R. Spillner
*/
public static enum Darstellungsmodus {
/**
* <code>Darstellungsmodus.PUNKT</code>: Das Objekt wird durch ein
* Punktnetz dargestellt.
*/
PUNKT(GL2.GL_POINT),
/**
* <code>Darstellungsmodus.LINIE</code>: Das Objekt wird durch ein
* Gitternetz dargestellt.
*/
LINIE(GL2.GL_LINE),
/**
* <code>Darstellungsmodus.FUELLEN</code>: Die Seitenflächen des Objekts
* sind durchgehend mit der Farbe gefüllt.
*/
FUELLEN(GL2.GL_FILL),
/**
* <code>Darstellungsmodus.NA</code>: Darstellungsmodus nicht verfügbar.
* In diesem Fall wird der Standarddarstellungsmodus des Fensters gewählt.
*/
NV(-1);
private int dm;
private Darstellungsmodus(int i) {
dm = i;
}
int getMode() {
return dm;
}
};
static enum Rendermodus {
RENDER_GLU, RENDER_GL, RENDER_VBOGL
};
/**
* Klasse eines Konfigurations-Objektes, dass jedem {@link GLObjekt}
* zugeordnet ist.
*
* @author R. Spillner
*/
static class GLConfig {
int xDivision;
int yDivision;
Rendermodus objectRenderMode;
Darstellungsmodus displayMode;
}
final GLConfig conf;
final WindowConfig wconf;
GLUquadric quadric;
// true if needed to be recomputed
boolean needsRedraw = true;
abstract void renderDelegate(GL2 gl, GLU glu);
GLObjekt() {
selectionID = ++maxSelectionID;
conf = new GLConfig();
associatedCam = GLKamera.aktiveKamera();
associatedRenderer = associatedCam.associatedRenderer;
wconf = associatedCam.getWconf();
conf.xDivision = wconf.xDivision;
conf.yDivision = wconf.yDivision;
conf.objectRenderMode = wconf.globalObjectRenderMode;
conf.displayMode = Darstellungsmodus.NV;
scheduleRender();
}
/**
* Legt das Oberflächenmaterial des Objektes fest. Vordefinierte Materialien
* findet man in der Klasse {@link GLMaterial}.
*
* @param pMaterial
* Ein Material aus der Aufzählungsklasse GLMaterial
*/
public synchronized void setzeMaterial(GLMaterial pMaterial) {
System.arraycopy(pMaterial.getAmbient(), 0, aAmbient, 0, 4);
System.arraycopy(pMaterial.getDiffuse(), 0, aDiffuse, 0, 4);
System.arraycopy(pMaterial.getSpecular(), 0, aSpecular, 0, 4);
aGlanz = pMaterial.getShininess();
scheduleRender();
}
/** Farbe des Objekts.
* @return dreielementiges Array mit Rot-, Grün und Blauanteilen
*/
@Override
public double[] gibFarbe() {
return new double[] { aDiffuse[0], aDiffuse[1], aDiffuse[2] };
}
@Override
public synchronized void setzeFarbe(double pR, double pG, double pB) {
aDiffuse[0] = (float) pR;
aDiffuse[1] = (float) pG;
aDiffuse[2] = (float) pB;
scheduleRender();
}
/**
* Setzt die Reflektivität und Farbe der Reflexion. Eine hohe Reflektivität
* ergibt einen z.T. großen Glanzfleck auf gekrümmten Flächen des Objekts.
* Die Farbanteile müssen zwischen 0 und 1 liegen, die Reflektivität muss
* zwischen 0 und 128 liegen.
*
* @param pR
* Rotanteil, zwischen 0 und 1
* @param pG
* Grünanteil, zwischen 0 und 1
* @param pB
* Blauanteil, zwischen 0 und 1
* @param pGlanz
* Reflektivität, zwischen 0 und 128, standardmäßig 70
*/
public synchronized void setzeGlanz(double pR, double pG, double pB, int pGlanz) {
aGlanz = pGlanz;
aSpecular[0] = (float) pR;
aSpecular[1] = (float) pG;
aSpecular[2] = (float) pB;
scheduleRender();
}
@Override
boolean isTransparent() {
return aDiffuse[3] != 1 || aAmbient[3] != 1;
}
/**
* Bestimmt, ob das Objekt gezeichnet wird oder nicht. Wenn die Sichtbarkeit
* auf <code>false</code> gesetzt wird, wird keinerlei OpenGL-Code zum Rendern
* des Objekts ausgeführt.
*
* @param pSichtbar
* Wenn <code>true</code>, so wird das Objekt gezeichnet, bei
* <code>false</code> wird es nicht gezeichnet.
*/
public synchronized void setzeSichtbarkeit(boolean pSichtbar) {
aVisible = pSichtbar;
scheduleRender();
}
/**
* Löscht das Objekt aus der Szene. Es ist danach nicht mehr
* wiederherstellbar.
*/
public synchronized void loesche() {
associatedRenderer.removeObjectFromRenderMap(GLTextur.NULL_TEXTURE, this);
scheduleRender();
}
@Override
void render(GL2 gl, GLU glu) {
if (conf.objectRenderMode == Rendermodus.RENDER_GLU)
if (quadric == null)
quadric = glu.gluNewQuadric();
if (associatedCam.istDrahtgittermodell())
gl.glPolygonMode(GL2.GL_FRONT_AND_BACK, GL2.GL_LINE);
else
gl.glPolygonMode(GL2.GL_FRONT_AND_BACK, conf.displayMode.getMode());
loadMaterial(gl);
gl.glPushMatrix();
renderDelegate(gl, glu);
gl.glPopMatrix();
}
GLConfig getConf() {
return conf;
}
void loadMaterial(GL2 gl) {
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_AMBIENT, aAmbient, 0);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_DIFFUSE, aDiffuse, 0);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_SPECULAR, aSpecular, 0);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_EMISSION, aEmission, 0);
gl.glMaterialf(GL2.GL_FRONT, GL2.GL_SHININESS, aGlanz);
}
void loadMaterial(GL2 gl, float[] pAmb, float[] pDiff, float[] pSpec, float[] pEmiss, float pGlanz) {
float[] t = new float[] { 0, 0, 0, 1};
System.arraycopy(pAmb, 0, t, 0, 3);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_AMBIENT, t, 0);
System.arraycopy(pDiff, 0, t, 0, 3);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_DIFFUSE, t, 0);
System.arraycopy(pSpec, 0, t, 0, 3);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_SPECULAR, t, 0);
System.arraycopy(pEmiss, 0, t, 0, 3);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_EMISSION, t, 0);
gl.glMaterialf(GL2.GL_FRONT, GL2.GL_SHININESS, pGlanz);
}
void scheduleRender() {
associatedRenderer.scheduleRender();
}
}
| trent2/bGLOOP | src/bGLOOP/GLObjekt.java | 2,608 | // between 0 and 128 | line_comment | nl | package bGLOOP;
import java.util.logging.Logger;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.glu.GLU;
import com.jogamp.opengl.glu.GLUquadric;
/**
* Basisklasse aller bGLOOP-Objekte.
*
* @author R. Spillner
*/
public abstract class GLObjekt extends DisplayItem implements IGLColorable {
Logger log = Logger.getLogger("bGLOOP");
float[] aDiffuse = { 1, 1, 1, 1 };
final private float[] aAmbient = { 0.15f, 0.15f, 0.15f, 1 };
private float[] aSpecular = { 0, 0, 0, 1 };
float[] aEmission = { 0, 0, 0, 0 };
private float aGlanz = 70; // between 0<SUF>
private static int maxSelectionID = 0;
int selectionID = 0;
/**
* Der Darstellungsmodus beschreibt, wie ein Objekt gezeichnet wird. Dabei
* gibt es drei Möglichkeiten: als Punktgrafik, als Gitternetzgrafik oder
* als durchgehend gefüllte Struktur.
*
* @author R. Spillner
*/
public static enum Darstellungsmodus {
/**
* <code>Darstellungsmodus.PUNKT</code>: Das Objekt wird durch ein
* Punktnetz dargestellt.
*/
PUNKT(GL2.GL_POINT),
/**
* <code>Darstellungsmodus.LINIE</code>: Das Objekt wird durch ein
* Gitternetz dargestellt.
*/
LINIE(GL2.GL_LINE),
/**
* <code>Darstellungsmodus.FUELLEN</code>: Die Seitenflächen des Objekts
* sind durchgehend mit der Farbe gefüllt.
*/
FUELLEN(GL2.GL_FILL),
/**
* <code>Darstellungsmodus.NA</code>: Darstellungsmodus nicht verfügbar.
* In diesem Fall wird der Standarddarstellungsmodus des Fensters gewählt.
*/
NV(-1);
private int dm;
private Darstellungsmodus(int i) {
dm = i;
}
int getMode() {
return dm;
}
};
static enum Rendermodus {
RENDER_GLU, RENDER_GL, RENDER_VBOGL
};
/**
* Klasse eines Konfigurations-Objektes, dass jedem {@link GLObjekt}
* zugeordnet ist.
*
* @author R. Spillner
*/
static class GLConfig {
int xDivision;
int yDivision;
Rendermodus objectRenderMode;
Darstellungsmodus displayMode;
}
final GLConfig conf;
final WindowConfig wconf;
GLUquadric quadric;
// true if needed to be recomputed
boolean needsRedraw = true;
abstract void renderDelegate(GL2 gl, GLU glu);
GLObjekt() {
selectionID = ++maxSelectionID;
conf = new GLConfig();
associatedCam = GLKamera.aktiveKamera();
associatedRenderer = associatedCam.associatedRenderer;
wconf = associatedCam.getWconf();
conf.xDivision = wconf.xDivision;
conf.yDivision = wconf.yDivision;
conf.objectRenderMode = wconf.globalObjectRenderMode;
conf.displayMode = Darstellungsmodus.NV;
scheduleRender();
}
/**
* Legt das Oberflächenmaterial des Objektes fest. Vordefinierte Materialien
* findet man in der Klasse {@link GLMaterial}.
*
* @param pMaterial
* Ein Material aus der Aufzählungsklasse GLMaterial
*/
public synchronized void setzeMaterial(GLMaterial pMaterial) {
System.arraycopy(pMaterial.getAmbient(), 0, aAmbient, 0, 4);
System.arraycopy(pMaterial.getDiffuse(), 0, aDiffuse, 0, 4);
System.arraycopy(pMaterial.getSpecular(), 0, aSpecular, 0, 4);
aGlanz = pMaterial.getShininess();
scheduleRender();
}
/** Farbe des Objekts.
* @return dreielementiges Array mit Rot-, Grün und Blauanteilen
*/
@Override
public double[] gibFarbe() {
return new double[] { aDiffuse[0], aDiffuse[1], aDiffuse[2] };
}
@Override
public synchronized void setzeFarbe(double pR, double pG, double pB) {
aDiffuse[0] = (float) pR;
aDiffuse[1] = (float) pG;
aDiffuse[2] = (float) pB;
scheduleRender();
}
/**
* Setzt die Reflektivität und Farbe der Reflexion. Eine hohe Reflektivität
* ergibt einen z.T. großen Glanzfleck auf gekrümmten Flächen des Objekts.
* Die Farbanteile müssen zwischen 0 und 1 liegen, die Reflektivität muss
* zwischen 0 und 128 liegen.
*
* @param pR
* Rotanteil, zwischen 0 und 1
* @param pG
* Grünanteil, zwischen 0 und 1
* @param pB
* Blauanteil, zwischen 0 und 1
* @param pGlanz
* Reflektivität, zwischen 0 und 128, standardmäßig 70
*/
public synchronized void setzeGlanz(double pR, double pG, double pB, int pGlanz) {
aGlanz = pGlanz;
aSpecular[0] = (float) pR;
aSpecular[1] = (float) pG;
aSpecular[2] = (float) pB;
scheduleRender();
}
@Override
boolean isTransparent() {
return aDiffuse[3] != 1 || aAmbient[3] != 1;
}
/**
* Bestimmt, ob das Objekt gezeichnet wird oder nicht. Wenn die Sichtbarkeit
* auf <code>false</code> gesetzt wird, wird keinerlei OpenGL-Code zum Rendern
* des Objekts ausgeführt.
*
* @param pSichtbar
* Wenn <code>true</code>, so wird das Objekt gezeichnet, bei
* <code>false</code> wird es nicht gezeichnet.
*/
public synchronized void setzeSichtbarkeit(boolean pSichtbar) {
aVisible = pSichtbar;
scheduleRender();
}
/**
* Löscht das Objekt aus der Szene. Es ist danach nicht mehr
* wiederherstellbar.
*/
public synchronized void loesche() {
associatedRenderer.removeObjectFromRenderMap(GLTextur.NULL_TEXTURE, this);
scheduleRender();
}
@Override
void render(GL2 gl, GLU glu) {
if (conf.objectRenderMode == Rendermodus.RENDER_GLU)
if (quadric == null)
quadric = glu.gluNewQuadric();
if (associatedCam.istDrahtgittermodell())
gl.glPolygonMode(GL2.GL_FRONT_AND_BACK, GL2.GL_LINE);
else
gl.glPolygonMode(GL2.GL_FRONT_AND_BACK, conf.displayMode.getMode());
loadMaterial(gl);
gl.glPushMatrix();
renderDelegate(gl, glu);
gl.glPopMatrix();
}
GLConfig getConf() {
return conf;
}
void loadMaterial(GL2 gl) {
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_AMBIENT, aAmbient, 0);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_DIFFUSE, aDiffuse, 0);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_SPECULAR, aSpecular, 0);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_EMISSION, aEmission, 0);
gl.glMaterialf(GL2.GL_FRONT, GL2.GL_SHININESS, aGlanz);
}
void loadMaterial(GL2 gl, float[] pAmb, float[] pDiff, float[] pSpec, float[] pEmiss, float pGlanz) {
float[] t = new float[] { 0, 0, 0, 1};
System.arraycopy(pAmb, 0, t, 0, 3);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_AMBIENT, t, 0);
System.arraycopy(pDiff, 0, t, 0, 3);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_DIFFUSE, t, 0);
System.arraycopy(pSpec, 0, t, 0, 3);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_SPECULAR, t, 0);
System.arraycopy(pEmiss, 0, t, 0, 3);
gl.glMaterialfv(GL2.GL_FRONT, GL2.GL_EMISSION, t, 0);
gl.glMaterialf(GL2.GL_FRONT, GL2.GL_SHININESS, pGlanz);
}
void scheduleRender() {
associatedRenderer.scheduleRender();
}
}
|
4361_0 | //*elke* kaart heeft een ID, expansion naam, kaart naam,
//een kost en een type
//deze interface zorgt ervoor dat dit word nageleeft bij alle kaarten
public abstract class Card {
private int ID;
private String name;
private int cost;
private String type;
private EXPANSION expansion;
public Card(int id, String name, int cost, String type, EXPANSION expansion){
this.ID = id;
this.name = name;
this.cost = cost;
this.type = type;
this.expansion = expansion;
}
public int getID(){
return ID;
};
public String getName(){
return name;
};
public int getCost(){
return cost;
};
public String getType(){
return type;
};
public EXPANSION getExpansion(){
return expansion;
};
public String toString(){
return "ID = " + ID + ", name = " + name + ", cost = " + cost
+ ", type = " + type + ", expansion = " + expansion;
}
}
| trimonvl/Dominion | Dominion/src/Card.java | 289 | //*elke* kaart heeft een ID, expansion naam, kaart naam, | line_comment | nl | //*elke* kaart<SUF>
//een kost en een type
//deze interface zorgt ervoor dat dit word nageleeft bij alle kaarten
public abstract class Card {
private int ID;
private String name;
private int cost;
private String type;
private EXPANSION expansion;
public Card(int id, String name, int cost, String type, EXPANSION expansion){
this.ID = id;
this.name = name;
this.cost = cost;
this.type = type;
this.expansion = expansion;
}
public int getID(){
return ID;
};
public String getName(){
return name;
};
public int getCost(){
return cost;
};
public String getType(){
return type;
};
public EXPANSION getExpansion(){
return expansion;
};
public String toString(){
return "ID = " + ID + ", name = " + name + ", cost = " + cost
+ ", type = " + type + ", expansion = " + expansion;
}
}
|
24063_16 | /*
* 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 io.trino.orc.stream;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.trino.orc.OrcCorruptionException;
import io.trino.orc.checkpoint.DecimalStreamCheckpoint;
import java.io.IOException;
import static com.google.common.base.Verify.verify;
import static io.trino.orc.checkpoint.InputStreamCheckpoint.decodeCompressedBlockOffset;
import static io.trino.orc.checkpoint.InputStreamCheckpoint.decodeDecompressedOffset;
public class DecimalInputStream
implements ValueInputStream<DecimalStreamCheckpoint>
{
private static final long LONG_MASK = 0x80_80_80_80_80_80_80_80L;
private static final int INT_MASK = 0x80_80_80_80;
private final OrcChunkLoader chunkLoader;
private Slice block = Slices.EMPTY_SLICE; // reference to current (decoded) data block. Can be either a reference to the buffer or to current chunk
private int blockOffset; // position within current data block
private long lastCheckpoint;
public DecimalInputStream(OrcChunkLoader chunkLoader)
{
this.chunkLoader = chunkLoader;
}
@Override
public void seekToCheckpoint(DecimalStreamCheckpoint checkpoint)
throws IOException
{
long newCheckpoint = checkpoint.getInputStreamCheckpoint();
// if checkpoint starts at the same compressed position...
// (we're checking for an empty block because empty blocks signify that we possibly read all the data in the existing
// buffer, so last checkpoint is no longer valid)
if (block.length() > 0 && decodeCompressedBlockOffset(newCheckpoint) == decodeCompressedBlockOffset(lastCheckpoint)) {
// and decompressed position is within our block, reposition in the block directly
int blockOffset = decodeDecompressedOffset(newCheckpoint) - decodeDecompressedOffset(lastCheckpoint);
if (blockOffset >= 0 && blockOffset < block.length()) {
this.blockOffset = blockOffset;
// do not change last checkpoint because we have not moved positions
return;
}
}
chunkLoader.seekToCheckpoint(newCheckpoint);
lastCheckpoint = newCheckpoint;
block = Slices.EMPTY_SLICE;
blockOffset = 0;
}
// result must have at least batchSize * 2 capacity
@SuppressWarnings("PointlessBitwiseExpression")
public void nextLongDecimal(long[] result, int batchSize)
throws IOException
{
verify(result.length >= batchSize * 2);
int count = 0;
while (count < batchSize) {
if (blockOffset == block.length()) {
advance();
}
while (blockOffset <= block.length() - 20) { // we'll read 2 longs + 1 int
long low;
long middle = 0;
int high = 0;
// low bits
long current = block.getLong(blockOffset);
int zeros = Long.numberOfTrailingZeros(~current & LONG_MASK);
int end = (zeros + 1) / 8;
blockOffset += end;
boolean negative = (current & 1) == 1;
low = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7;
low |= (current & 0x7F_00_00_00_00_00_00L) >>> 6;
low |= (current & 0x7F_00_00_00_00_00L) >>> 5;
low |= (current & 0x7F_00_00_00_00L) >>> 4;
low |= (current & 0x7F_00_00_00) >>> 3;
low |= (current & 0x7F_00_00) >>> 2;
low |= (current & 0x7F_00) >>> 1;
low |= (current & 0x7F) >>> 0;
low = low & ((1L << (end * 7)) - 1);
// middle bits
if (zeros == 64) {
current = block.getLong(blockOffset);
zeros = Long.numberOfTrailingZeros(~current & LONG_MASK);
end = (zeros + 1) / 8;
blockOffset += end;
middle = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7;
middle |= (current & 0x7F_00_00_00_00_00_00L) >>> 6;
middle |= (current & 0x7F_00_00_00_00_00L) >>> 5;
middle |= (current & 0x7F_00_00_00_00L) >>> 4;
middle |= (current & 0x7F_00_00_00) >>> 3;
middle |= (current & 0x7F_00_00) >>> 2;
middle |= (current & 0x7F_00) >>> 1;
middle |= (current & 0x7F) >>> 0;
middle = middle & ((1L << (end * 7)) - 1);
// high bits
if (zeros == 64) {
int last = block.getInt(blockOffset);
zeros = Integer.numberOfTrailingZeros(~last & INT_MASK);
end = (zeros + 1) / 8;
blockOffset += end;
high = (last & 0x7F_00_00) >>> 2;
high |= (last & 0x7F_00) >>> 1;
high |= (last & 0x7F) >>> 0;
high = high & ((1 << (end * 7)) - 1);
if (end == 4 || high > 0xFF_FF) { // only 127 - (55 + 56) = 16 bits allowed in high
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits");
}
}
}
emitLongDecimal(result, count, low, middle, high, negative);
count++;
if (count == batchSize) {
return;
}
}
// handle the tail of the current block
count = decodeLongDecimalTail(result, count, batchSize);
}
}
private int decodeLongDecimalTail(long[] result, int count, int batchSize)
throws IOException
{
boolean negative = false;
long low = 0;
long middle = 0;
int high = 0;
long value;
boolean last = false;
if (blockOffset == block.length()) {
advance();
}
int offset = 0;
while (true) {
value = block.getByte(blockOffset);
blockOffset++;
if (offset == 0) {
negative = (value & 1) == 1;
low |= (value & 0x7F);
}
else if (offset < 8) {
low |= (value & 0x7F) << (offset * 7);
}
else if (offset < 16) {
middle |= (value & 0x7F) << ((offset - 8) * 7);
}
else if (offset < 19) {
high = (int) (high | (value & 0x7F) << ((offset - 16) * 7));
}
else {
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits");
}
offset++;
if ((value & 0x80) == 0) {
if (high > 0xFF_FF) { // only 127 - (55 + 56) = 16 bits allowed in high
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits");
}
emitLongDecimal(result, count, low, middle, high, negative);
count++;
low = 0;
middle = 0;
high = 0;
offset = 0;
if (blockOffset == block.length()) {
// the last value aligns with the end of the block, so just
// reset the block and loop around to optimized decoding
break;
}
if (last || count == batchSize) {
break;
}
}
else if (blockOffset == block.length()) {
last = true;
advance();
}
}
return count;
}
private static void emitLongDecimal(long[] result, int offset, long low, long middle, long high, boolean negative)
{
long lower = (low >>> 1) | (middle << 55); // drop the sign bit from low
long upper = (middle >>> 9) | (high << 47);
if (negative) {
// ORC encodes decimals using a zig-zag vint strategy
// For negative values, the encoded value is given by:
// encoded = -value * 2 - 1
//
// Therefore,
// value = -(encoded + 1) / 2
// = -encoded / 2 - 1/2
//
// Given the identity -v = ~v + 1 for negating a value using
// two's complement representation,
//
// value = (~encoded + 1) / 2 - 1/2
// = ~encoded / 2 + 1/2 - 1/2
// = ~encoded / 2
//
// The shift is performed above as the bits are assembled. The negation
// is performed here.
lower = ~lower;
upper = ~upper;
}
result[2 * offset] = upper;
result[2 * offset + 1] = lower;
}
@SuppressWarnings("PointlessBitwiseExpression")
public void nextShortDecimal(long[] result, int batchSize)
throws IOException
{
verify(result.length >= batchSize);
int count = 0;
while (count < batchSize) {
if (blockOffset == block.length()) {
advance();
}
while (blockOffset <= block.length() - 12) { // we'll read 1 longs + 1 int
long low;
int high = 0;
// low bits
long current = block.getLong(blockOffset);
int zeros = Long.numberOfTrailingZeros(~current & LONG_MASK);
int end = (zeros + 1) / 8;
blockOffset += end;
low = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7;
low |= (current & 0x7F_00_00_00_00_00_00L) >>> 6;
low |= (current & 0x7F_00_00_00_00_00L) >>> 5;
low |= (current & 0x7F_00_00_00_00L) >>> 4;
low |= (current & 0x7F_00_00_00) >>> 3;
low |= (current & 0x7F_00_00) >>> 2;
low |= (current & 0x7F_00) >>> 1;
low |= (current & 0x7F) >>> 0;
low = low & ((1L << (end * 7)) - 1);
// high bits
if (zeros == 64) {
int last = block.getInt(blockOffset);
zeros = Integer.numberOfTrailingZeros(~last & INT_MASK);
end = (zeros + 1) / 8;
blockOffset += end;
high = (last & 0x7F_00) >>> 1;
high |= (last & 0x7F) >>> 0;
high = high & ((1 << (end * 7)) - 1);
if (end >= 3 || high > 0xFF) { // only 63 - (55) = 8 bits allowed in high
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)");
}
}
emitShortDecimal(result, count, low, high);
count++;
if (count == batchSize) {
return;
}
}
// handle the tail of the current block
count = decodeShortDecimalTail(result, count, batchSize);
}
}
private int decodeShortDecimalTail(long[] result, int count, int batchSize)
throws IOException
{
long low = 0;
long high = 0;
long value;
boolean last = false;
int offset = 0;
if (blockOffset == block.length()) {
advance();
}
while (true) {
value = block.getByte(blockOffset);
blockOffset++;
if (offset == 0) {
low |= (value & 0x7F);
}
else if (offset < 8) {
low |= (value & 0x7F) << (offset * 7);
}
else if (offset < 11) {
high |= (value & 0x7F) << ((offset - 8) * 7);
}
else {
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)");
}
offset++;
if ((value & 0x80) == 0) {
if (high > 0xFF) { // only 63 - (55) = 8 bits allowed in high
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)");
}
emitShortDecimal(result, count, low, high);
count++;
low = 0;
high = 0;
offset = 0;
if (blockOffset == block.length()) {
// the last value aligns with the end of the block, so just
// reset the block and loop around to optimized decoding
break;
}
if (last || count == batchSize) {
break;
}
}
else if (blockOffset == block.length()) {
last = true;
advance();
}
}
return count;
}
private static void emitShortDecimal(long[] result, int offset, long low, long high)
{
boolean negative = (low & 1) == 1;
long value = (low >>> 1) | (high << 55); // drop the sign bit from low
if (negative) {
value = ~value;
}
result[offset] = value;
}
@Override
public void skip(long items)
throws IOException
{
if (items == 0) {
return;
}
if (blockOffset == block.length()) {
advance();
}
int count = 0;
while (true) {
while (blockOffset <= block.length() - Long.BYTES) { // only safe if there's at least one long to read
long current = block.getLong(blockOffset);
int increment = Long.bitCount(~current & LONG_MASK);
if (count + increment >= items) {
// reached the tail, so bail out and process byte at a time
break;
}
count += increment;
blockOffset += Long.BYTES;
}
while (blockOffset < block.length()) { // tail -- byte at a time
byte current = block.getByte(blockOffset);
blockOffset++;
if ((current & 0x80) == 0) {
count++;
if (count == items) {
return;
}
}
}
advance();
}
}
private void advance()
throws IOException
{
block = chunkLoader.nextChunk();
lastCheckpoint = chunkLoader.getLastCheckpoint();
blockOffset = 0;
}
}
| trinodb/trino | lib/trino-orc/src/main/java/io/trino/orc/stream/DecimalInputStream.java | 4,417 | // ORC encodes decimals using a zig-zag vint strategy | line_comment | nl | /*
* 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 io.trino.orc.stream;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
import io.trino.orc.OrcCorruptionException;
import io.trino.orc.checkpoint.DecimalStreamCheckpoint;
import java.io.IOException;
import static com.google.common.base.Verify.verify;
import static io.trino.orc.checkpoint.InputStreamCheckpoint.decodeCompressedBlockOffset;
import static io.trino.orc.checkpoint.InputStreamCheckpoint.decodeDecompressedOffset;
public class DecimalInputStream
implements ValueInputStream<DecimalStreamCheckpoint>
{
private static final long LONG_MASK = 0x80_80_80_80_80_80_80_80L;
private static final int INT_MASK = 0x80_80_80_80;
private final OrcChunkLoader chunkLoader;
private Slice block = Slices.EMPTY_SLICE; // reference to current (decoded) data block. Can be either a reference to the buffer or to current chunk
private int blockOffset; // position within current data block
private long lastCheckpoint;
public DecimalInputStream(OrcChunkLoader chunkLoader)
{
this.chunkLoader = chunkLoader;
}
@Override
public void seekToCheckpoint(DecimalStreamCheckpoint checkpoint)
throws IOException
{
long newCheckpoint = checkpoint.getInputStreamCheckpoint();
// if checkpoint starts at the same compressed position...
// (we're checking for an empty block because empty blocks signify that we possibly read all the data in the existing
// buffer, so last checkpoint is no longer valid)
if (block.length() > 0 && decodeCompressedBlockOffset(newCheckpoint) == decodeCompressedBlockOffset(lastCheckpoint)) {
// and decompressed position is within our block, reposition in the block directly
int blockOffset = decodeDecompressedOffset(newCheckpoint) - decodeDecompressedOffset(lastCheckpoint);
if (blockOffset >= 0 && blockOffset < block.length()) {
this.blockOffset = blockOffset;
// do not change last checkpoint because we have not moved positions
return;
}
}
chunkLoader.seekToCheckpoint(newCheckpoint);
lastCheckpoint = newCheckpoint;
block = Slices.EMPTY_SLICE;
blockOffset = 0;
}
// result must have at least batchSize * 2 capacity
@SuppressWarnings("PointlessBitwiseExpression")
public void nextLongDecimal(long[] result, int batchSize)
throws IOException
{
verify(result.length >= batchSize * 2);
int count = 0;
while (count < batchSize) {
if (blockOffset == block.length()) {
advance();
}
while (blockOffset <= block.length() - 20) { // we'll read 2 longs + 1 int
long low;
long middle = 0;
int high = 0;
// low bits
long current = block.getLong(blockOffset);
int zeros = Long.numberOfTrailingZeros(~current & LONG_MASK);
int end = (zeros + 1) / 8;
blockOffset += end;
boolean negative = (current & 1) == 1;
low = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7;
low |= (current & 0x7F_00_00_00_00_00_00L) >>> 6;
low |= (current & 0x7F_00_00_00_00_00L) >>> 5;
low |= (current & 0x7F_00_00_00_00L) >>> 4;
low |= (current & 0x7F_00_00_00) >>> 3;
low |= (current & 0x7F_00_00) >>> 2;
low |= (current & 0x7F_00) >>> 1;
low |= (current & 0x7F) >>> 0;
low = low & ((1L << (end * 7)) - 1);
// middle bits
if (zeros == 64) {
current = block.getLong(blockOffset);
zeros = Long.numberOfTrailingZeros(~current & LONG_MASK);
end = (zeros + 1) / 8;
blockOffset += end;
middle = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7;
middle |= (current & 0x7F_00_00_00_00_00_00L) >>> 6;
middle |= (current & 0x7F_00_00_00_00_00L) >>> 5;
middle |= (current & 0x7F_00_00_00_00L) >>> 4;
middle |= (current & 0x7F_00_00_00) >>> 3;
middle |= (current & 0x7F_00_00) >>> 2;
middle |= (current & 0x7F_00) >>> 1;
middle |= (current & 0x7F) >>> 0;
middle = middle & ((1L << (end * 7)) - 1);
// high bits
if (zeros == 64) {
int last = block.getInt(blockOffset);
zeros = Integer.numberOfTrailingZeros(~last & INT_MASK);
end = (zeros + 1) / 8;
blockOffset += end;
high = (last & 0x7F_00_00) >>> 2;
high |= (last & 0x7F_00) >>> 1;
high |= (last & 0x7F) >>> 0;
high = high & ((1 << (end * 7)) - 1);
if (end == 4 || high > 0xFF_FF) { // only 127 - (55 + 56) = 16 bits allowed in high
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits");
}
}
}
emitLongDecimal(result, count, low, middle, high, negative);
count++;
if (count == batchSize) {
return;
}
}
// handle the tail of the current block
count = decodeLongDecimalTail(result, count, batchSize);
}
}
private int decodeLongDecimalTail(long[] result, int count, int batchSize)
throws IOException
{
boolean negative = false;
long low = 0;
long middle = 0;
int high = 0;
long value;
boolean last = false;
if (blockOffset == block.length()) {
advance();
}
int offset = 0;
while (true) {
value = block.getByte(blockOffset);
blockOffset++;
if (offset == 0) {
negative = (value & 1) == 1;
low |= (value & 0x7F);
}
else if (offset < 8) {
low |= (value & 0x7F) << (offset * 7);
}
else if (offset < 16) {
middle |= (value & 0x7F) << ((offset - 8) * 7);
}
else if (offset < 19) {
high = (int) (high | (value & 0x7F) << ((offset - 16) * 7));
}
else {
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits");
}
offset++;
if ((value & 0x80) == 0) {
if (high > 0xFF_FF) { // only 127 - (55 + 56) = 16 bits allowed in high
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal exceeds 128 bits");
}
emitLongDecimal(result, count, low, middle, high, negative);
count++;
low = 0;
middle = 0;
high = 0;
offset = 0;
if (blockOffset == block.length()) {
// the last value aligns with the end of the block, so just
// reset the block and loop around to optimized decoding
break;
}
if (last || count == batchSize) {
break;
}
}
else if (blockOffset == block.length()) {
last = true;
advance();
}
}
return count;
}
private static void emitLongDecimal(long[] result, int offset, long low, long middle, long high, boolean negative)
{
long lower = (low >>> 1) | (middle << 55); // drop the sign bit from low
long upper = (middle >>> 9) | (high << 47);
if (negative) {
// ORC encodes<SUF>
// For negative values, the encoded value is given by:
// encoded = -value * 2 - 1
//
// Therefore,
// value = -(encoded + 1) / 2
// = -encoded / 2 - 1/2
//
// Given the identity -v = ~v + 1 for negating a value using
// two's complement representation,
//
// value = (~encoded + 1) / 2 - 1/2
// = ~encoded / 2 + 1/2 - 1/2
// = ~encoded / 2
//
// The shift is performed above as the bits are assembled. The negation
// is performed here.
lower = ~lower;
upper = ~upper;
}
result[2 * offset] = upper;
result[2 * offset + 1] = lower;
}
@SuppressWarnings("PointlessBitwiseExpression")
public void nextShortDecimal(long[] result, int batchSize)
throws IOException
{
verify(result.length >= batchSize);
int count = 0;
while (count < batchSize) {
if (blockOffset == block.length()) {
advance();
}
while (blockOffset <= block.length() - 12) { // we'll read 1 longs + 1 int
long low;
int high = 0;
// low bits
long current = block.getLong(blockOffset);
int zeros = Long.numberOfTrailingZeros(~current & LONG_MASK);
int end = (zeros + 1) / 8;
blockOffset += end;
low = (current & 0x7F_00_00_00_00_00_00_00L) >>> 7;
low |= (current & 0x7F_00_00_00_00_00_00L) >>> 6;
low |= (current & 0x7F_00_00_00_00_00L) >>> 5;
low |= (current & 0x7F_00_00_00_00L) >>> 4;
low |= (current & 0x7F_00_00_00) >>> 3;
low |= (current & 0x7F_00_00) >>> 2;
low |= (current & 0x7F_00) >>> 1;
low |= (current & 0x7F) >>> 0;
low = low & ((1L << (end * 7)) - 1);
// high bits
if (zeros == 64) {
int last = block.getInt(blockOffset);
zeros = Integer.numberOfTrailingZeros(~last & INT_MASK);
end = (zeros + 1) / 8;
blockOffset += end;
high = (last & 0x7F_00) >>> 1;
high |= (last & 0x7F) >>> 0;
high = high & ((1 << (end * 7)) - 1);
if (end >= 3 || high > 0xFF) { // only 63 - (55) = 8 bits allowed in high
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)");
}
}
emitShortDecimal(result, count, low, high);
count++;
if (count == batchSize) {
return;
}
}
// handle the tail of the current block
count = decodeShortDecimalTail(result, count, batchSize);
}
}
private int decodeShortDecimalTail(long[] result, int count, int batchSize)
throws IOException
{
long low = 0;
long high = 0;
long value;
boolean last = false;
int offset = 0;
if (blockOffset == block.length()) {
advance();
}
while (true) {
value = block.getByte(blockOffset);
blockOffset++;
if (offset == 0) {
low |= (value & 0x7F);
}
else if (offset < 8) {
low |= (value & 0x7F) << (offset * 7);
}
else if (offset < 11) {
high |= (value & 0x7F) << ((offset - 8) * 7);
}
else {
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)");
}
offset++;
if ((value & 0x80) == 0) {
if (high > 0xFF) { // only 63 - (55) = 8 bits allowed in high
throw new OrcCorruptionException(chunkLoader.getOrcDataSourceId(), "Decimal does not fit long (invalid table schema?)");
}
emitShortDecimal(result, count, low, high);
count++;
low = 0;
high = 0;
offset = 0;
if (blockOffset == block.length()) {
// the last value aligns with the end of the block, so just
// reset the block and loop around to optimized decoding
break;
}
if (last || count == batchSize) {
break;
}
}
else if (blockOffset == block.length()) {
last = true;
advance();
}
}
return count;
}
private static void emitShortDecimal(long[] result, int offset, long low, long high)
{
boolean negative = (low & 1) == 1;
long value = (low >>> 1) | (high << 55); // drop the sign bit from low
if (negative) {
value = ~value;
}
result[offset] = value;
}
@Override
public void skip(long items)
throws IOException
{
if (items == 0) {
return;
}
if (blockOffset == block.length()) {
advance();
}
int count = 0;
while (true) {
while (blockOffset <= block.length() - Long.BYTES) { // only safe if there's at least one long to read
long current = block.getLong(blockOffset);
int increment = Long.bitCount(~current & LONG_MASK);
if (count + increment >= items) {
// reached the tail, so bail out and process byte at a time
break;
}
count += increment;
blockOffset += Long.BYTES;
}
while (blockOffset < block.length()) { // tail -- byte at a time
byte current = block.getByte(blockOffset);
blockOffset++;
if ((current & 0x80) == 0) {
count++;
if (count == items) {
return;
}
}
}
advance();
}
}
private void advance()
throws IOException
{
block = chunkLoader.nextChunk();
lastCheckpoint = chunkLoader.getLastCheckpoint();
blockOffset = 0;
}
}
|
101253_22 | import javax.swing.*;
import java.awt.*; import java.awt.event.*; import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.File; import java.io.IOException;
import javax.imageio.ImageIO;
/**
* Die Klasse VIEW zeigt das Spielfeld an und interagiert mit dem Spieler.
*
* @author (kinder)
*/
public class VIEW extends JPanel {
SPIELFELD spielfeld;
private CONTROLLER controller;
private Area spielbrett;
private int breite, hoehe; // Feldbreite und -höhe
private int size = 100; // Größe eines Basisquadrats
// Deklariert Zwischenspeicher für (Spielstein-)Bilder
private BufferedImage roterStein, gelberStein;
private BufferedImage roterSteinReihe, gelberSteinReihe;
private BufferedImage gelberGewinner, roterGewinner, unentschieden;
private BufferedImage gelbGibtAuf, rotGibtAuf;
private int spalte; // aktuell ausgewählte Spalte
static boolean drawNeeded; // Stein-Vorschau zeichen - ja/nein
// deklariert die für eine Siegeranzeige nötigen Variablen
public boolean showWinner;
private int winner;
public VIEW(SPIELFELD spielfeld, CONTROLLER controller) {
this.spielfeld = spielfeld; // Referenz auf Spielfeld
this.controller = controller; // Referenz auf Controller
breite = spielfeld.getBreite();
hoehe = spielfeld.getHoehe();
size = controller.getSize();
setPreferredSize(new Dimension(breite*size, (hoehe + 1)*size) ); // setzt bevorzugte Fenstergröße
loadImages();
spielbrettMitLoecherVorbereiten(); // zeichnet leeres Spielfeld
}
private void loadImages() {
try {
roterStein = ImageIO.read(new File("textures/roter_Stein.png"));
gelberStein = ImageIO.read(new File("textures/gelber_Stein.png"));
roterSteinReihe = ImageIO.read(new File("textures/roter_Stein_Reihe.png"));
gelberSteinReihe = ImageIO.read(new File("textures/gelber_Stein_Reihe.png"));
roterGewinner = ImageIO.read(new File("textures/roter Gewinner.jpg"));
gelberGewinner = ImageIO.read(new File("textures/gelber Gewinner.jpg"));
unentschieden = ImageIO.read(new File("textures/unentschieden.jpg"));
gelbGibtAuf = ImageIO.read(new File("textures/gelbGibtAuf.jpg"));
rotGibtAuf = ImageIO.read(new File("textures/rotGibtAuf.jpg"));
} catch (IOException ex) { }
}
public void spielbrettMitLoecherVorbereiten() {
size = controller.getSize();
// deklariert und initialisiert benötigte Variablen
Rectangle2D blauesFeld = new Rectangle2D.Float(0, 0 + size , breite * size, hoehe * size);
Ellipse2D loch = new Ellipse2D.Double(0, 0, 0, 0);
// zeichnet das leere Spielfeld
spielbrett = new Area(blauesFeld);
// spart die "Fenster" für die Spielsteine aus
for(int i = 0; i < spielfeld.getBreite(); i++) {
for(int j = 0 ; j < spielfeld.getHoehe(); j++) {
loch = new Ellipse2D.Double(i * size,(-j + 5) * size + size, (size*96)/100, (size*96)/100);
spielbrett.subtract(new Area(loch));
}
}
}
// Legt fest, ob Vorschau gezeigt werden soll
public void showPreview(boolean showPreview) { this.drawNeeded = showPreview; }
public void paintComponent(Graphics graphics) {
size = controller.getSize();
super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D) graphics;
// Blaue Spielfläche mit Löchern auf schwarzem Hintergrund
graphics.setColor(Color.BLACK);
graphics.fillRect(0, 0 + size , breite * size, hoehe * size);
int[][] s = spielfeld.getSpielfeld(); // lädt aktuelle Belegung des Spielfelds
// Zeichnet Stein-Vorschau, falls drawNeeded == true
if(controller.spieleramzug == 2 && drawNeeded) { graphics.drawImage(roterStein, spalte * size, 0, size, size, null); }
if(controller.spieleramzug == 1 && drawNeeded) { graphics.drawImage(gelberStein, spalte * size, 0, size, size, null); }
// Jetzt werden platzierte rote / gelbe Spielsteine auf dem Spielfeld gezeichnet
for(int i = 0; i < spielfeld.getBreite(); i++) {
for(int j = 0 ; j < spielfeld.getHoehe(); j++) {
if (s[i][j] == 1) { graphics.drawImage(roterStein, i * size,(-j + 5) * size + size, size, size, null); }
else if (s[i][j] == 2) { graphics.drawImage(gelberStein, i * size,(-j + 5) * size + size, size, size, null); }
else if (s[i][j] == 3) { graphics.drawImage(roterSteinReihe, i * size, (-j + 5) * size + size, size, size, null); }
else if (s[i][j] == 4) { graphics.drawImage(gelberSteinReihe, i * size, (-j + 5) * size + size, size, size, null); }
else { graphics.setColor(Color.BLACK); }
}
}
// Setzt die Farbe auf blau und füllt das Spielfeld aus
graphics.setColor(Color.BLUE);
graphics2D.fill(spielbrett);
// Zeigt, wenn gewollt, den Sieger an
if(showWinner) {
if (winner == 1) { graphics.drawImage(roterGewinner, 0, 0, breite * size, (hoehe + 1) * size, null); } // Rot hat gewonnen
else if (winner == 2) { graphics.drawImage(gelberGewinner, 0, 0, breite * size, (hoehe + 1) * size, null); } // Gelb hat gewonnen
else if (winner == 3) { graphics.drawImage(gelbGibtAuf, 0, 0, breite * size, (hoehe + 1) * size, null); } // Gelb gibt auf, Rot gewinnt
else if (winner == 4) { graphics.drawImage(rotGibtAuf, 0, 0, breite * size, (hoehe + 1) * size, null); } // Rot gibt auf, Gelb gewinnt
else if (winner == 5) { graphics.drawImage(unentschieden, 0, 0, breite * size, (hoehe + 1) * size, null); } // Unentschieden
}
}
// ändert die Attribute, damit der Gewinner in View ausgegeben wird
public void showWinner(int winner) {
this.winner = winner;
showWinner = true;
}
// Eingabemethode für aktuell ausgewählte Spalte
public void setSpalte(int xWert) {
size = controller.getSize();
spalte = (xWert / size);
// x-Wert außerhalb: Rückgabe des letztmöglichen x-Werts
if(spalte > (breite - 1)) { spalte = breite - 1; }
}
public Area getSpielbrett() { return spielbrett; }
} | ts12345/vier_gewinnt | VIER_GEWINNT/VIEW.java | 2,247 | // Gelb hat gewonnen | line_comment | nl | import javax.swing.*;
import java.awt.*; import java.awt.event.*; import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.File; import java.io.IOException;
import javax.imageio.ImageIO;
/**
* Die Klasse VIEW zeigt das Spielfeld an und interagiert mit dem Spieler.
*
* @author (kinder)
*/
public class VIEW extends JPanel {
SPIELFELD spielfeld;
private CONTROLLER controller;
private Area spielbrett;
private int breite, hoehe; // Feldbreite und -höhe
private int size = 100; // Größe eines Basisquadrats
// Deklariert Zwischenspeicher für (Spielstein-)Bilder
private BufferedImage roterStein, gelberStein;
private BufferedImage roterSteinReihe, gelberSteinReihe;
private BufferedImage gelberGewinner, roterGewinner, unentschieden;
private BufferedImage gelbGibtAuf, rotGibtAuf;
private int spalte; // aktuell ausgewählte Spalte
static boolean drawNeeded; // Stein-Vorschau zeichen - ja/nein
// deklariert die für eine Siegeranzeige nötigen Variablen
public boolean showWinner;
private int winner;
public VIEW(SPIELFELD spielfeld, CONTROLLER controller) {
this.spielfeld = spielfeld; // Referenz auf Spielfeld
this.controller = controller; // Referenz auf Controller
breite = spielfeld.getBreite();
hoehe = spielfeld.getHoehe();
size = controller.getSize();
setPreferredSize(new Dimension(breite*size, (hoehe + 1)*size) ); // setzt bevorzugte Fenstergröße
loadImages();
spielbrettMitLoecherVorbereiten(); // zeichnet leeres Spielfeld
}
private void loadImages() {
try {
roterStein = ImageIO.read(new File("textures/roter_Stein.png"));
gelberStein = ImageIO.read(new File("textures/gelber_Stein.png"));
roterSteinReihe = ImageIO.read(new File("textures/roter_Stein_Reihe.png"));
gelberSteinReihe = ImageIO.read(new File("textures/gelber_Stein_Reihe.png"));
roterGewinner = ImageIO.read(new File("textures/roter Gewinner.jpg"));
gelberGewinner = ImageIO.read(new File("textures/gelber Gewinner.jpg"));
unentschieden = ImageIO.read(new File("textures/unentschieden.jpg"));
gelbGibtAuf = ImageIO.read(new File("textures/gelbGibtAuf.jpg"));
rotGibtAuf = ImageIO.read(new File("textures/rotGibtAuf.jpg"));
} catch (IOException ex) { }
}
public void spielbrettMitLoecherVorbereiten() {
size = controller.getSize();
// deklariert und initialisiert benötigte Variablen
Rectangle2D blauesFeld = new Rectangle2D.Float(0, 0 + size , breite * size, hoehe * size);
Ellipse2D loch = new Ellipse2D.Double(0, 0, 0, 0);
// zeichnet das leere Spielfeld
spielbrett = new Area(blauesFeld);
// spart die "Fenster" für die Spielsteine aus
for(int i = 0; i < spielfeld.getBreite(); i++) {
for(int j = 0 ; j < spielfeld.getHoehe(); j++) {
loch = new Ellipse2D.Double(i * size,(-j + 5) * size + size, (size*96)/100, (size*96)/100);
spielbrett.subtract(new Area(loch));
}
}
}
// Legt fest, ob Vorschau gezeigt werden soll
public void showPreview(boolean showPreview) { this.drawNeeded = showPreview; }
public void paintComponent(Graphics graphics) {
size = controller.getSize();
super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D) graphics;
// Blaue Spielfläche mit Löchern auf schwarzem Hintergrund
graphics.setColor(Color.BLACK);
graphics.fillRect(0, 0 + size , breite * size, hoehe * size);
int[][] s = spielfeld.getSpielfeld(); // lädt aktuelle Belegung des Spielfelds
// Zeichnet Stein-Vorschau, falls drawNeeded == true
if(controller.spieleramzug == 2 && drawNeeded) { graphics.drawImage(roterStein, spalte * size, 0, size, size, null); }
if(controller.spieleramzug == 1 && drawNeeded) { graphics.drawImage(gelberStein, spalte * size, 0, size, size, null); }
// Jetzt werden platzierte rote / gelbe Spielsteine auf dem Spielfeld gezeichnet
for(int i = 0; i < spielfeld.getBreite(); i++) {
for(int j = 0 ; j < spielfeld.getHoehe(); j++) {
if (s[i][j] == 1) { graphics.drawImage(roterStein, i * size,(-j + 5) * size + size, size, size, null); }
else if (s[i][j] == 2) { graphics.drawImage(gelberStein, i * size,(-j + 5) * size + size, size, size, null); }
else if (s[i][j] == 3) { graphics.drawImage(roterSteinReihe, i * size, (-j + 5) * size + size, size, size, null); }
else if (s[i][j] == 4) { graphics.drawImage(gelberSteinReihe, i * size, (-j + 5) * size + size, size, size, null); }
else { graphics.setColor(Color.BLACK); }
}
}
// Setzt die Farbe auf blau und füllt das Spielfeld aus
graphics.setColor(Color.BLUE);
graphics2D.fill(spielbrett);
// Zeigt, wenn gewollt, den Sieger an
if(showWinner) {
if (winner == 1) { graphics.drawImage(roterGewinner, 0, 0, breite * size, (hoehe + 1) * size, null); } // Rot hat gewonnen
else if (winner == 2) { graphics.drawImage(gelberGewinner, 0, 0, breite * size, (hoehe + 1) * size, null); } // Gelb hat<SUF>
else if (winner == 3) { graphics.drawImage(gelbGibtAuf, 0, 0, breite * size, (hoehe + 1) * size, null); } // Gelb gibt auf, Rot gewinnt
else if (winner == 4) { graphics.drawImage(rotGibtAuf, 0, 0, breite * size, (hoehe + 1) * size, null); } // Rot gibt auf, Gelb gewinnt
else if (winner == 5) { graphics.drawImage(unentschieden, 0, 0, breite * size, (hoehe + 1) * size, null); } // Unentschieden
}
}
// ändert die Attribute, damit der Gewinner in View ausgegeben wird
public void showWinner(int winner) {
this.winner = winner;
showWinner = true;
}
// Eingabemethode für aktuell ausgewählte Spalte
public void setSpalte(int xWert) {
size = controller.getSize();
spalte = (xWert / size);
// x-Wert außerhalb: Rückgabe des letztmöglichen x-Werts
if(spalte > (breite - 1)) { spalte = breite - 1; }
}
public Area getSpielbrett() { return spielbrett; }
} |
200948_9 | /*
* c't-Sim - Robotersimulator für den c't-Bot
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307, USA.
*
*/
package ctSim;
import java.io.IOException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import ctSim.controller.BotReceiver;
import ctSim.controller.Config;
import ctSim.util.SaferThread;
/**
* Repräsentiert eine TCP-Verbindung
*
* @author Benjamin Benz
* @author Christoph Grimmer ([email protected])
*/
public class TcpConnection extends Connection {
/** Socket der Connection */
private Socket socket = null;
/**
* TCP-Verbindung
*
* @param sock Socket
* @throws IOException
*/
public TcpConnection(Socket sock) throws IOException {
this.socket = sock;
setInputStream(socket.getInputStream());
setOutputStream(socket.getOutputStream());
}
/**
* Wandelt den übergebenen String und die Portnummer in eine TCP/IP-Adresse und stellt dann die
* Verbindung her
*
* @param hostname Adresse als String
* @param port Portnummer
* @throws IOException
*/
public TcpConnection(String hostname, int port) throws IOException {
this(new Socket(hostname, port));
}
/**
* Beendet die laufende Verbindung
*
* @throws IOException
*/
@Override
public synchronized void close() throws IOException {
socket.close();
super.close();
}
/**
* @see ctSim.Connection#getName()
*/
@Override
public String getName() {
return
"TCP " + socket.getLocalAddress() + ":" + socket.getLocalPort() +
"->" + socket.getInetAddress() + ":" + socket.getPort();
}
/**
* @see ctSim.Connection#getShortName()
*/
@Override
public String getShortName() { return "TCP"; }
/**
* Beginnt zu lauschen
*
* @param receiver Bot-Receiver
*/
public static void startListening(final BotReceiver receiver) {
int p = 10001;
try {
p = Integer.parseInt(Config.getValue("botport"));
} catch(NumberFormatException nfe) {
lg.warning(nfe, "Problem beim Parsen der Konfiguration: Parameter 'botport' ist keine Ganzzahl");
}
lg.info("Warte auf Verbindung vom c't-Bot auf TCP-Port " + p);
try {
@SuppressWarnings("resource")
final ServerSocket srvSocket = new ServerSocket(p);
new SaferThread("ctSim-Listener-" + p + "/tcp") {
@Override
public void work() {
try {
Socket s = srvSocket.accept(); // blockiert
lg.fine("Verbindung auf Port " + srvSocket.getLocalPort() + "/tcp eingegangen");
new TcpConnection(s).doHandshake(receiver);
} catch (IOException e) {
lg.warn(e, "Thread " + getName() + " hat ein E/A-Problem beim Lauschen");
}
}
}.start();
} catch (IOException e) {
lg.warning(e, "E/A-Problem beim Binden an TCP-Port " + p + "; läuft der c't-Sim schon?");
System.exit(1);
}
}
/**
* Verbindet zu Host:Port
*
* @param hostname Host-Name des Bots
* @param port Port
* @param receiver Bot-Receiver
*/
public static void connectTo(final String hostname, final int port,
final BotReceiver receiver) {
final String address = hostname + ":" + port; // nur für Meldungen
lg.info("Verbinde mit " + address + " ...");
new SaferThread("ctSim-Connect-" + address) {
@Override
public void work() {
try {
new TcpConnection(hostname, port).doHandshake(receiver);
} catch (UnknownHostException e) {
lg.warn("Host '" + e.getMessage() + "' nicht gefunden");
} catch (ConnectException e) {
// ConnectExcp deckt so Sachen ab wie "connection refused" und "connection timed out"
lg.warn("Konnte Verbindung mit " + address + " nicht herstellen (" + e.getLocalizedMessage() + ")");
} catch (IOException e) {
lg.severe(e, "E/A-Problem beim Verbinden mit " + address);
}
// Arbeit ist getan, ob es funktioniert hat oder nicht...
die();
}
}.start();
}
}
| tsandmann/ct-sim | ctSim/TcpConnection.java | 1,502 | /**
* Verbindet zu Host:Port
*
* @param hostname Host-Name des Bots
* @param port Port
* @param receiver Bot-Receiver
*/ | block_comment | nl | /*
* c't-Sim - Robotersimulator für den c't-Bot
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307, USA.
*
*/
package ctSim;
import java.io.IOException;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import ctSim.controller.BotReceiver;
import ctSim.controller.Config;
import ctSim.util.SaferThread;
/**
* Repräsentiert eine TCP-Verbindung
*
* @author Benjamin Benz
* @author Christoph Grimmer ([email protected])
*/
public class TcpConnection extends Connection {
/** Socket der Connection */
private Socket socket = null;
/**
* TCP-Verbindung
*
* @param sock Socket
* @throws IOException
*/
public TcpConnection(Socket sock) throws IOException {
this.socket = sock;
setInputStream(socket.getInputStream());
setOutputStream(socket.getOutputStream());
}
/**
* Wandelt den übergebenen String und die Portnummer in eine TCP/IP-Adresse und stellt dann die
* Verbindung her
*
* @param hostname Adresse als String
* @param port Portnummer
* @throws IOException
*/
public TcpConnection(String hostname, int port) throws IOException {
this(new Socket(hostname, port));
}
/**
* Beendet die laufende Verbindung
*
* @throws IOException
*/
@Override
public synchronized void close() throws IOException {
socket.close();
super.close();
}
/**
* @see ctSim.Connection#getName()
*/
@Override
public String getName() {
return
"TCP " + socket.getLocalAddress() + ":" + socket.getLocalPort() +
"->" + socket.getInetAddress() + ":" + socket.getPort();
}
/**
* @see ctSim.Connection#getShortName()
*/
@Override
public String getShortName() { return "TCP"; }
/**
* Beginnt zu lauschen
*
* @param receiver Bot-Receiver
*/
public static void startListening(final BotReceiver receiver) {
int p = 10001;
try {
p = Integer.parseInt(Config.getValue("botport"));
} catch(NumberFormatException nfe) {
lg.warning(nfe, "Problem beim Parsen der Konfiguration: Parameter 'botport' ist keine Ganzzahl");
}
lg.info("Warte auf Verbindung vom c't-Bot auf TCP-Port " + p);
try {
@SuppressWarnings("resource")
final ServerSocket srvSocket = new ServerSocket(p);
new SaferThread("ctSim-Listener-" + p + "/tcp") {
@Override
public void work() {
try {
Socket s = srvSocket.accept(); // blockiert
lg.fine("Verbindung auf Port " + srvSocket.getLocalPort() + "/tcp eingegangen");
new TcpConnection(s).doHandshake(receiver);
} catch (IOException e) {
lg.warn(e, "Thread " + getName() + " hat ein E/A-Problem beim Lauschen");
}
}
}.start();
} catch (IOException e) {
lg.warning(e, "E/A-Problem beim Binden an TCP-Port " + p + "; läuft der c't-Sim schon?");
System.exit(1);
}
}
/**
* Verbindet zu Host:Port<SUF>*/
public static void connectTo(final String hostname, final int port,
final BotReceiver receiver) {
final String address = hostname + ":" + port; // nur für Meldungen
lg.info("Verbinde mit " + address + " ...");
new SaferThread("ctSim-Connect-" + address) {
@Override
public void work() {
try {
new TcpConnection(hostname, port).doHandshake(receiver);
} catch (UnknownHostException e) {
lg.warn("Host '" + e.getMessage() + "' nicht gefunden");
} catch (ConnectException e) {
// ConnectExcp deckt so Sachen ab wie "connection refused" und "connection timed out"
lg.warn("Konnte Verbindung mit " + address + " nicht herstellen (" + e.getLocalizedMessage() + ")");
} catch (IOException e) {
lg.severe(e, "E/A-Problem beim Verbinden mit " + address);
}
// Arbeit ist getan, ob es funktioniert hat oder nicht...
die();
}
}.start();
}
}
|
127139_11 |
package com.maiastra;
import java.util.Iterator;
import java.util.List;
//import org.eclipse.core.runtime.CoreException;
//import org.eclipse.core.runtime.FileLocator;
//import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.uml2.uml.AggregationKind;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Dependency;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Model;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Operation;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Profile;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;
import org.eclipse.uml2.uml.UMLPackage;
import org.eclipse.uml2.uml.resource.UMLResource;
import org.eclipse.uml2.uml.resources.util.UMLResourcesUtil;
//import org.osgi.framework.FrameworkUtil;
public class ReadUmlModel {
private static void iterateElement(Element elem , String identString) {
Iterator<Element> it = elem.getOwnedElements().iterator();
while (it.hasNext()) {
Element el = it.next();
if (el instanceof Class) {
Class cl = (Class) el;
System.out.printf("%sclass : %s\n", identString, cl.getName());
System.out.printf("%s\tin package : %s\n", identString, cl.getPackage().getName());
List<Property> pl = cl.getAllAttributes();
for (Property p : pl) {
System.out.printf("%s\tattribute : %s\n", identString, p.getName());
}
List<Operation> ol = cl.getAllOperations();
for (Operation o : ol) {
System.out.printf("%s\toperation : %s\n", identString, o.getName());
}
List<Stereotype> st = cl.getAppliedStereotypes();
for (Stereotype ster : st) {
System.out.printf("%s\tapplied stereotype : %s\n", identString, ster.getQualifiedName());
}
}
if (el instanceof Package) {
Package p = (Package) el;
System.out.printf("%spackage : %s\n", identString, p.getName());
iterateElement(el, new StringBuilder().append(identString).append("\t").toString());
}
if (el instanceof Association) {
Association a = (Association) el;
// List<Property> ends = a.getOwnedEnds();
//
// System.out.printf("%snumber of ends : %d\n", identString, ends.size());
// for (Property p : ends){
// System.out.printf("%sässoc end %s\n", identString, p.getName());
// }
List<Property> mems = a.getMemberEnds();
System.out.printf("%sAssociation number of members %s\n", identString, mems.size());
for (Property mem : mems){
System.out.printf("%s\tmember end: %s\n", identString, mem.getName());
if (mem.isNavigable()){
System.out.printf("%s\tisnavigable.\n", identString);
}else{
System.out.printf("%s\tisNOTnavigable.\n", identString);
}
AggregationKind ak = mem.getAggregation();
System.out.printf("%s\tagregation : %s\n", identString, ak.getName());
System.out.printf("%s\towner : %s\n",identString, mem.getOwner().getClass().getName());
if (mem.isMultivalued()){
System.out.printf("%s\tmultivalued\n", identString);
}
System.out.printf("%s\tlower : %d\n", identString, mem.getLower());
System.out.printf("%s\tupper : %d\n", identString, mem.getUpper());
System.out.println("");
}
System.out.println("\n");
}
if (el instanceof Dependency){
System.out.printf("%sdepenency : ", identString);
Dependency d = (Dependency)el;
List<NamedElement> nelems = d.getClients();
for (NamedElement nelem : nelems) {
System.out.printf("%sclient : %s\n", identString, nelem.getQualifiedName());
}
List<NamedElement> suplElems = d.getSuppliers();
for (NamedElement suplElem : suplElems){
System.out.printf("%ssupplier : ", identString, suplElem.getQualifiedName());
}
}
System.out.printf("***** type: %s\n", el.getClass().getName());
}
}
public static void main(String[] args) {
System.out.println("hallo hallo");
String workingDirectory = System.getProperty("user.dir");
String seperator = System.getProperty("file.separator");
String modelPathURI = "file://" + workingDirectory + seperator + "model" + seperator + "model.uml";
System.out.printf("model file : %s\n", modelPathURI);
ResourceSet rSet = new ResourceSetImpl();
rSet.getPackageRegistry().put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(UMLResource.FILE_EXTENSION,
UMLResource.Factory.INSTANCE);
// org.eclipse.emf.common.util.URI modelUri =
// URI.createURI("file:///home/tschoots/MAIASTRA_development/papyrus_java_ws/org.eclipse.uml2.examples.gettingstarted/ExtendedPO2.uml");
org.eclipse.emf.common.util.URI modelUri = URI.createURI(modelPathURI);
// java.net.URI modelUri = new
// java.net.URI("file:///home/tschoots/MAIASTRA_development/papyrus_java_ws/org.eclipse.uml2.examples.gettingstarted/ExtendedPO2.uml");
UMLResource r = (UMLResource) rSet.getResource(modelUri, true);
EcoreUtil.resolveAll(r);
UMLResourcesUtil.init(rSet);
System.out.println(r.getEncoding());
System.out.println(r.getXMINamespace());
Model umlModel = (Model) r.getContents().get(0);
System.out.println(umlModel.getName());
List<Profile> appliedProfiles = umlModel.getAllAppliedProfiles();
for (Profile p : appliedProfiles) {
System.out.printf("applied profile : %s\n", p.getName());
}
// iterate over the model elements
// Iterator<Element> it = umlModel.getOwnedElements().iterator();
// while (it.hasNext()) {
// Element el = it.next();
// if (el instanceof Class) {
// Class cl = (Class) el;
// System.out.printf("class : %s\n", cl.getName());
// System.out.printf("\tin package : %s\n", cl.getPackage().getName());
//
// List<Property> pl = cl.getAllAttributes();
// for (Property p : pl) {
// System.out.printf("\tattribute : %s\n", p.getName());
// }
//
// List<Operation> ol = cl.getAllOperations();
// for (Operation o : ol) {
// System.out.printf("\toperation : %s\n", o.getName());
// }
// List<Stereotype> st = cl.getAppliedStereotypes();
// for (Stereotype ster : st) {
// System.out.printf("\tapplied stereotype : %s\n", ster.getQualifiedName());
// }
// }
//
// if (el instanceof Package) {
// Package p = (Package) el;
// System.out.printf("package : %s\n", p.getName());
//
// }
//
// }
iterateElement(umlModel, "");
System.out.println("the end");
}
}
| tschoots/papurus_code_generation | ReadModelExample/javaproject/src/com/maiastra/ReadUmlModel.java | 2,444 | // Iterator<Element> it = umlModel.getOwnedElements().iterator(); | line_comment | nl |
package com.maiastra;
import java.util.Iterator;
import java.util.List;
//import org.eclipse.core.runtime.CoreException;
//import org.eclipse.core.runtime.FileLocator;
//import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.uml2.uml.AggregationKind;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Dependency;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Model;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Operation;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Profile;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;
import org.eclipse.uml2.uml.UMLPackage;
import org.eclipse.uml2.uml.resource.UMLResource;
import org.eclipse.uml2.uml.resources.util.UMLResourcesUtil;
//import org.osgi.framework.FrameworkUtil;
public class ReadUmlModel {
private static void iterateElement(Element elem , String identString) {
Iterator<Element> it = elem.getOwnedElements().iterator();
while (it.hasNext()) {
Element el = it.next();
if (el instanceof Class) {
Class cl = (Class) el;
System.out.printf("%sclass : %s\n", identString, cl.getName());
System.out.printf("%s\tin package : %s\n", identString, cl.getPackage().getName());
List<Property> pl = cl.getAllAttributes();
for (Property p : pl) {
System.out.printf("%s\tattribute : %s\n", identString, p.getName());
}
List<Operation> ol = cl.getAllOperations();
for (Operation o : ol) {
System.out.printf("%s\toperation : %s\n", identString, o.getName());
}
List<Stereotype> st = cl.getAppliedStereotypes();
for (Stereotype ster : st) {
System.out.printf("%s\tapplied stereotype : %s\n", identString, ster.getQualifiedName());
}
}
if (el instanceof Package) {
Package p = (Package) el;
System.out.printf("%spackage : %s\n", identString, p.getName());
iterateElement(el, new StringBuilder().append(identString).append("\t").toString());
}
if (el instanceof Association) {
Association a = (Association) el;
// List<Property> ends = a.getOwnedEnds();
//
// System.out.printf("%snumber of ends : %d\n", identString, ends.size());
// for (Property p : ends){
// System.out.printf("%sässoc end %s\n", identString, p.getName());
// }
List<Property> mems = a.getMemberEnds();
System.out.printf("%sAssociation number of members %s\n", identString, mems.size());
for (Property mem : mems){
System.out.printf("%s\tmember end: %s\n", identString, mem.getName());
if (mem.isNavigable()){
System.out.printf("%s\tisnavigable.\n", identString);
}else{
System.out.printf("%s\tisNOTnavigable.\n", identString);
}
AggregationKind ak = mem.getAggregation();
System.out.printf("%s\tagregation : %s\n", identString, ak.getName());
System.out.printf("%s\towner : %s\n",identString, mem.getOwner().getClass().getName());
if (mem.isMultivalued()){
System.out.printf("%s\tmultivalued\n", identString);
}
System.out.printf("%s\tlower : %d\n", identString, mem.getLower());
System.out.printf("%s\tupper : %d\n", identString, mem.getUpper());
System.out.println("");
}
System.out.println("\n");
}
if (el instanceof Dependency){
System.out.printf("%sdepenency : ", identString);
Dependency d = (Dependency)el;
List<NamedElement> nelems = d.getClients();
for (NamedElement nelem : nelems) {
System.out.printf("%sclient : %s\n", identString, nelem.getQualifiedName());
}
List<NamedElement> suplElems = d.getSuppliers();
for (NamedElement suplElem : suplElems){
System.out.printf("%ssupplier : ", identString, suplElem.getQualifiedName());
}
}
System.out.printf("***** type: %s\n", el.getClass().getName());
}
}
public static void main(String[] args) {
System.out.println("hallo hallo");
String workingDirectory = System.getProperty("user.dir");
String seperator = System.getProperty("file.separator");
String modelPathURI = "file://" + workingDirectory + seperator + "model" + seperator + "model.uml";
System.out.printf("model file : %s\n", modelPathURI);
ResourceSet rSet = new ResourceSetImpl();
rSet.getPackageRegistry().put(UMLPackage.eNS_URI, UMLPackage.eINSTANCE);
rSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(UMLResource.FILE_EXTENSION,
UMLResource.Factory.INSTANCE);
// org.eclipse.emf.common.util.URI modelUri =
// URI.createURI("file:///home/tschoots/MAIASTRA_development/papyrus_java_ws/org.eclipse.uml2.examples.gettingstarted/ExtendedPO2.uml");
org.eclipse.emf.common.util.URI modelUri = URI.createURI(modelPathURI);
// java.net.URI modelUri = new
// java.net.URI("file:///home/tschoots/MAIASTRA_development/papyrus_java_ws/org.eclipse.uml2.examples.gettingstarted/ExtendedPO2.uml");
UMLResource r = (UMLResource) rSet.getResource(modelUri, true);
EcoreUtil.resolveAll(r);
UMLResourcesUtil.init(rSet);
System.out.println(r.getEncoding());
System.out.println(r.getXMINamespace());
Model umlModel = (Model) r.getContents().get(0);
System.out.println(umlModel.getName());
List<Profile> appliedProfiles = umlModel.getAllAppliedProfiles();
for (Profile p : appliedProfiles) {
System.out.printf("applied profile : %s\n", p.getName());
}
// iterate over the model elements
// Iterator<Element> it<SUF>
// while (it.hasNext()) {
// Element el = it.next();
// if (el instanceof Class) {
// Class cl = (Class) el;
// System.out.printf("class : %s\n", cl.getName());
// System.out.printf("\tin package : %s\n", cl.getPackage().getName());
//
// List<Property> pl = cl.getAllAttributes();
// for (Property p : pl) {
// System.out.printf("\tattribute : %s\n", p.getName());
// }
//
// List<Operation> ol = cl.getAllOperations();
// for (Operation o : ol) {
// System.out.printf("\toperation : %s\n", o.getName());
// }
// List<Stereotype> st = cl.getAppliedStereotypes();
// for (Stereotype ster : st) {
// System.out.printf("\tapplied stereotype : %s\n", ster.getQualifiedName());
// }
// }
//
// if (el instanceof Package) {
// Package p = (Package) el;
// System.out.printf("package : %s\n", p.getName());
//
// }
//
// }
iterateElement(umlModel, "");
System.out.println("the end");
}
}
|
96410_9 | /**
* Copyright 2011, Tobias Senger
*
* This file is part of animamea.
*
* Animamea 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.
*
* Animamea 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 animamea. If not, see <http://www.gnu.org/licenses/>.
*/
package de.tsenger.animamea.tools;
import java.math.BigInteger;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;
/**
* Helfer-Klasse zum Konventieren verschiedener Datentypen und Strukturen
*
* @author Tobias Senger ([email protected])
*
*/
public class Converter {
public static Date BCDtoDate(byte[] yymmdd) {
if( yymmdd==null || yymmdd.length!=6 ){
throw new IllegalArgumentException("Argument must have length 6, was " + (yymmdd==null?0:yymmdd.length));
}
int year = 2000 + yymmdd[0]*10 + yymmdd[1];
int month = yymmdd[2]*10 + yymmdd[3] - 1; // Java month index starts with 0...
int day = yymmdd[4]*10 + yymmdd[5];
GregorianCalendar gregCal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
gregCal.set(year, month, day,0,0,0);
return gregCal.getTime();
}
/**
* Converts a byte into a unsigned integer value.
*
* @param value
* @return
*/
public static int toUnsignedInt(byte value) {
return (value & 0x7F) + (value < 0 ? 128 : 0);
}
public static long ByteArrayToLong(byte[] bytes) {
long lo = 0;
for (int i = 0; i < 8; i++) {
lo <<= 8;
lo += (bytes[i] & 0x000000FF);
}
return lo;
}
/**
* Writes a <code>long</code> to byte array as sixteen bytes, high byte
* first.
*
* @param v
* a <code>long</code> to be converted.
*/
public static byte[] longToByteArray(long v) {
byte[] ivByes = new byte[8];
ivByes[0] = (byte) (v >>> 56);
ivByes[1] = (byte) (v >>> 48);
ivByes[2] = (byte) (v >>> 40);
ivByes[3] = (byte) (v >>> 32);
ivByes[4] = (byte) (v >>> 24);
ivByes[5] = (byte) (v >>> 16);
ivByes[6] = (byte) (v >>> 8);
ivByes[7] = (byte) (v >>> 0);
return ivByes;
}
/**
* Konvertiert ein BigInteger in ein ByteArray. Ein führendes Byte mit dem
* Wert 0 wird dabei angeschnitten. (Kennzeichen für einen positiven Wert,
* bei BigIntger)
*
* @param bi
* Das zu konvertierende BigInteger-Objekt.
* @return Byte-Array ohne führendes 0-Byte
*/
public static byte[] bigIntToByteArray(BigInteger bi) {
byte[] temp = bi.toByteArray();
byte[] returnbytes = null;
if (temp[0] == 0) {
returnbytes = new byte[temp.length - 1];
System.arraycopy(temp, 1, returnbytes, 0, returnbytes.length);
return returnbytes;
} else
return temp;
}
/**
* Dekodiert aus dem übergebenen Byte-Array einen ECPoint. Das benötigte
* prime field p wird aus der übergebenen Kurve übernommen Das erste Byte
* muss den Wert 0x04 enthalten (uncompressed point).
*
* @param value
* Byte Array der Form {0x04 || x-Bytes[] || y-Bytes[]}
* @param curve
* Die Kurve auf der der Punkt liegen soll.
* @return Point generiert aus den Input-Daten
* @throws IllegalArgumentException
* Falls das erste Byte nicht den Wert 0x04 enthält, enthält das
* übergebene Byte-Array offensichtlich keinen unkomprimierten Punkt
*/
public static ECPoint byteArrayToECPoint(byte[] value, ECCurve.Fp curve)
throws IllegalArgumentException {
byte[] x = new byte[(value.length - 1) / 2];
byte[] y = new byte[(value.length - 1) / 2];
if (value[0] != (byte) 0x04)
throw new IllegalArgumentException("No uncompressed Point found!");
else {
System.arraycopy(value, 1, x, 0, (value.length - 1) / 2);
System.arraycopy(value, 1 + ((value.length - 1) / 2), y, 0,
(value.length - 1) / 2);
// ECFieldElement.Fp xE = new ECFieldElement.Fp(curve.getQ(),
// new BigInteger(1, x));
// ECFieldElement.Fp yE = new ECFieldElement.Fp(curve.getQ(),
// new BigInteger(1, y));
// ECPoint point = new ECPoint.Fp(curve, xE, yE);
ECPoint point = curve.createPoint(new BigInteger(1, x), new BigInteger(1, y));
return point;
}
}
}
| tsenger/animamea | animamea/src/de/tsenger/animamea/tools/Converter.java | 1,712 | // ECFieldElement.Fp yE = new ECFieldElement.Fp(curve.getQ(), | line_comment | nl | /**
* Copyright 2011, Tobias Senger
*
* This file is part of animamea.
*
* Animamea 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.
*
* Animamea 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 animamea. If not, see <http://www.gnu.org/licenses/>.
*/
package de.tsenger.animamea.tools;
import java.math.BigInteger;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;
/**
* Helfer-Klasse zum Konventieren verschiedener Datentypen und Strukturen
*
* @author Tobias Senger ([email protected])
*
*/
public class Converter {
public static Date BCDtoDate(byte[] yymmdd) {
if( yymmdd==null || yymmdd.length!=6 ){
throw new IllegalArgumentException("Argument must have length 6, was " + (yymmdd==null?0:yymmdd.length));
}
int year = 2000 + yymmdd[0]*10 + yymmdd[1];
int month = yymmdd[2]*10 + yymmdd[3] - 1; // Java month index starts with 0...
int day = yymmdd[4]*10 + yymmdd[5];
GregorianCalendar gregCal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
gregCal.set(year, month, day,0,0,0);
return gregCal.getTime();
}
/**
* Converts a byte into a unsigned integer value.
*
* @param value
* @return
*/
public static int toUnsignedInt(byte value) {
return (value & 0x7F) + (value < 0 ? 128 : 0);
}
public static long ByteArrayToLong(byte[] bytes) {
long lo = 0;
for (int i = 0; i < 8; i++) {
lo <<= 8;
lo += (bytes[i] & 0x000000FF);
}
return lo;
}
/**
* Writes a <code>long</code> to byte array as sixteen bytes, high byte
* first.
*
* @param v
* a <code>long</code> to be converted.
*/
public static byte[] longToByteArray(long v) {
byte[] ivByes = new byte[8];
ivByes[0] = (byte) (v >>> 56);
ivByes[1] = (byte) (v >>> 48);
ivByes[2] = (byte) (v >>> 40);
ivByes[3] = (byte) (v >>> 32);
ivByes[4] = (byte) (v >>> 24);
ivByes[5] = (byte) (v >>> 16);
ivByes[6] = (byte) (v >>> 8);
ivByes[7] = (byte) (v >>> 0);
return ivByes;
}
/**
* Konvertiert ein BigInteger in ein ByteArray. Ein führendes Byte mit dem
* Wert 0 wird dabei angeschnitten. (Kennzeichen für einen positiven Wert,
* bei BigIntger)
*
* @param bi
* Das zu konvertierende BigInteger-Objekt.
* @return Byte-Array ohne führendes 0-Byte
*/
public static byte[] bigIntToByteArray(BigInteger bi) {
byte[] temp = bi.toByteArray();
byte[] returnbytes = null;
if (temp[0] == 0) {
returnbytes = new byte[temp.length - 1];
System.arraycopy(temp, 1, returnbytes, 0, returnbytes.length);
return returnbytes;
} else
return temp;
}
/**
* Dekodiert aus dem übergebenen Byte-Array einen ECPoint. Das benötigte
* prime field p wird aus der übergebenen Kurve übernommen Das erste Byte
* muss den Wert 0x04 enthalten (uncompressed point).
*
* @param value
* Byte Array der Form {0x04 || x-Bytes[] || y-Bytes[]}
* @param curve
* Die Kurve auf der der Punkt liegen soll.
* @return Point generiert aus den Input-Daten
* @throws IllegalArgumentException
* Falls das erste Byte nicht den Wert 0x04 enthält, enthält das
* übergebene Byte-Array offensichtlich keinen unkomprimierten Punkt
*/
public static ECPoint byteArrayToECPoint(byte[] value, ECCurve.Fp curve)
throws IllegalArgumentException {
byte[] x = new byte[(value.length - 1) / 2];
byte[] y = new byte[(value.length - 1) / 2];
if (value[0] != (byte) 0x04)
throw new IllegalArgumentException("No uncompressed Point found!");
else {
System.arraycopy(value, 1, x, 0, (value.length - 1) / 2);
System.arraycopy(value, 1 + ((value.length - 1) / 2), y, 0,
(value.length - 1) / 2);
// ECFieldElement.Fp xE = new ECFieldElement.Fp(curve.getQ(),
// new BigInteger(1, x));
// ECFieldElement.Fp yE<SUF>
// new BigInteger(1, y));
// ECPoint point = new ECPoint.Fp(curve, xE, yE);
ECPoint point = curve.createPoint(new BigInteger(1, x), new BigInteger(1, y));
return point;
}
}
}
|
97552_107 | import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import com.tencent.av.ui.funchat.zimu.ZimuView;
import java.lang.ref.WeakReference;
public class jhg
extends jhf
{
private jhg.a a;
private Paint jdField_ap_of_type_AndroidGraphicsPaint = new Paint();
Rect jdField_ap_of_type_AndroidGraphicsRect = new Rect(0, 0, 0, 0);
Rect aq = new Rect(0, 0, 0, 0);
int azO = 10;
int azP = 8;
int azQ = 4;
private Bitmap bz;
private final int[] cO;
private Canvas f = new Canvas();
private long mStartTime = System.currentTimeMillis();
public jhg(Context paramContext, WeakReference<ZimuView> paramWeakReference, int paramInt1, int paramInt2, float paramFloat, jhg.a parama)
{
super(paramContext, paramWeakReference, paramInt1, paramInt2, paramFloat);
this.jdField_ap_of_type_AndroidGraphicsPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
this.mPaint.setTextAlign(Paint.Align.CENTER);
this.cO = new int[] { paramInt1 / 6, paramInt1 / 5 };
this.jdField_a_of_type_Jhg$a = parama;
awq();
}
/* Error */
private Bitmap O()
{
// Byte code:
// 0: iconst_0
// 1: istore 5
// 3: aload_0
// 4: getfield 111 jhg:jdField_a_of_type_Ijn Lijn;
// 7: getfield 117 ijn:l Ljava/lang/CharSequence;
// 10: checkcast 119 java/lang/String
// 13: astore 9
// 15: aload 9
// 17: invokevirtual 123 java/lang/String:length ()I
// 20: istore 6
// 22: aload_0
// 23: aload_0
// 24: getfield 96 jhg:jdField_a_of_type_Jhg$a Ljhg$a;
// 27: getfield 126 jhg$a:azS I
// 30: iload 6
// 32: imul
// 33: iload 6
// 35: iconst_1
// 36: isub
// 37: aload_0
// 38: getfield 49 jhg:azP I
// 41: imul
// 42: iadd
// 43: aload_0
// 44: getfield 96 jhg:jdField_a_of_type_Jhg$a Ljhg$a;
// 47: getfield 126 jhg$a:azS I
// 50: getstatic 132 android/graphics/Bitmap$Config:ARGB_8888 Landroid/graphics/Bitmap$Config;
// 53: invokestatic 138 android/graphics/Bitmap:createBitmap (IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;
// 56: putfield 140 jhg:bz Landroid/graphics/Bitmap;
// 59: aload_0
// 60: getfield 45 jhg:f Landroid/graphics/Canvas;
// 63: aload_0
// 64: getfield 140 jhg:bz Landroid/graphics/Bitmap;
// 67: invokevirtual 144 android/graphics/Canvas:setBitmap (Landroid/graphics/Bitmap;)V
// 70: aload_0
// 71: getfield 96 jhg:jdField_a_of_type_Jhg$a Ljhg$a;
// 74: getfield 126 jhg$a:azS I
// 77: iconst_2
// 78: idiv
// 79: i2f
// 80: fstore_2
// 81: aload_0
// 82: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 85: invokevirtual 148 android/graphics/Paint:getFontMetrics ()Landroid/graphics/Paint$FontMetrics;
// 88: astore 10
// 90: aload 10
// 92: getfield 154 android/graphics/Paint$FontMetrics:ascent F
// 95: fstore_1
// 96: aload 10
// 98: getfield 157 android/graphics/Paint$FontMetrics:descent F
// 101: fload_1
// 102: fadd
// 103: fconst_2
// 104: fdiv
// 105: fstore_3
// 106: aload_0
// 107: getfield 51 jhg:azQ I
// 110: iconst_2
// 111: idiv
// 112: i2f
// 113: fstore 4
// 115: fload_2
// 116: fstore_1
// 117: iload 5
// 119: iload 6
// 121: if_icmpge +194 -> 315
// 124: aload_0
// 125: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 128: iconst_0
// 129: invokevirtual 161 android/graphics/Paint:setAntiAlias (Z)V
// 132: aload_0
// 133: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 136: getstatic 167 android/graphics/Paint$Style:FILL Landroid/graphics/Paint$Style;
// 139: invokevirtual 171 android/graphics/Paint:setStyle (Landroid/graphics/Paint$Style;)V
// 142: aload_0
// 143: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 146: iconst_m1
// 147: invokevirtual 175 android/graphics/Paint:setColor (I)V
// 150: aload_0
// 151: getfield 45 jhg:f Landroid/graphics/Canvas;
// 154: fload_1
// 155: fload_2
// 156: fload_2
// 157: aload_0
// 158: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 161: invokevirtual 179 android/graphics/Canvas:drawCircle (FFFLandroid/graphics/Paint;)V
// 164: aload_0
// 165: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 168: iconst_1
// 169: invokevirtual 161 android/graphics/Paint:setAntiAlias (Z)V
// 172: aload_0
// 173: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 176: getstatic 182 android/graphics/Paint$Style:STROKE Landroid/graphics/Paint$Style;
// 179: invokevirtual 171 android/graphics/Paint:setStyle (Landroid/graphics/Paint$Style;)V
// 182: aload_0
// 183: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 186: ldc 183
// 188: invokevirtual 175 android/graphics/Paint:setColor (I)V
// 191: aload_0
// 192: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 195: aload_0
// 196: getfield 51 jhg:azQ I
// 199: i2f
// 200: invokevirtual 187 android/graphics/Paint:setStrokeWidth (F)V
// 203: aload_0
// 204: getfield 45 jhg:f Landroid/graphics/Canvas;
// 207: fload_1
// 208: fload_2
// 209: fload_2
// 210: fload 4
// 212: fsub
// 213: aload_0
// 214: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 217: invokevirtual 179 android/graphics/Canvas:drawCircle (FFFLandroid/graphics/Paint;)V
// 220: aload_0
// 221: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 224: fconst_0
// 225: invokevirtual 187 android/graphics/Paint:setStrokeWidth (F)V
// 228: aload_0
// 229: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 232: getstatic 167 android/graphics/Paint$Style:FILL Landroid/graphics/Paint$Style;
// 235: invokevirtual 171 android/graphics/Paint:setStyle (Landroid/graphics/Paint$Style;)V
// 238: aload_0
// 239: getfield 45 jhg:f Landroid/graphics/Canvas;
// 242: aload 9
// 244: iload 5
// 246: iload 5
// 248: iconst_1
// 249: iadd
// 250: fload_1
// 251: fload_2
// 252: fload_3
// 253: fsub
// 254: aload_0
// 255: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 258: invokevirtual 191 android/graphics/Canvas:drawText (Ljava/lang/String;IIFFLandroid/graphics/Paint;)V
// 261: aload_0
// 262: getfield 96 jhg:jdField_a_of_type_Jhg$a Ljhg$a;
// 265: getfield 126 jhg$a:azS I
// 268: istore 7
// 270: aload_0
// 271: getfield 49 jhg:azP I
// 274: istore 8
// 276: fload_1
// 277: iload 7
// 279: iload 8
// 281: iadd
// 282: i2f
// 283: fadd
// 284: fstore_1
// 285: iload 5
// 287: iconst_1
// 288: iadd
// 289: istore 5
// 291: goto -174 -> 117
// 294: astore 9
// 296: invokestatic 197 com/tencent/qphone/base/util/QLog:isColorLevel ()Z
// 299: ifeq +16 -> 315
// 302: aload_0
// 303: getfield 201 jhg:TAG Ljava/lang/String;
// 306: iconst_2
// 307: aload 9
// 309: invokevirtual 205 java/lang/OutOfMemoryError:getMessage ()Ljava/lang/String;
// 312: invokestatic 209 com/tencent/qphone/base/util/QLog:e (Ljava/lang/String;ILjava/lang/String;)V
// 315: aload_0
// 316: getfield 140 jhg:bz Landroid/graphics/Bitmap;
// 319: areturn
// 320: astore 9
// 322: invokestatic 197 com/tencent/qphone/base/util/QLog:isColorLevel ()Z
// 325: ifeq -10 -> 315
// 328: aload_0
// 329: getfield 201 jhg:TAG Ljava/lang/String;
// 332: iconst_2
// 333: aload 9
// 335: invokevirtual 210 java/lang/Exception:getMessage ()Ljava/lang/String;
// 338: invokestatic 209 com/tencent/qphone/base/util/QLog:e (Ljava/lang/String;ILjava/lang/String;)V
// 341: goto -26 -> 315
// Local variable table:
// start length slot name signature
// 0 344 0 this jhg
// 95 190 1 f1 float
// 80 172 2 f2 float
// 105 148 3 f3 float
// 113 98 4 f4 float
// 1 289 5 i int
// 20 102 6 j int
// 268 14 7 k int
// 274 8 8 m int
// 13 230 9 str String
// 294 14 9 localOutOfMemoryError java.lang.OutOfMemoryError
// 320 14 9 localException java.lang.Exception
// 88 9 10 localFontMetrics android.graphics.Paint.FontMetrics
// Exception table:
// from to target type
// 3 115 294 java/lang/OutOfMemoryError
// 124 276 294 java/lang/OutOfMemoryError
// 3 115 320 java/lang/Exception
// 124 276 320 java/lang/Exception
}
private boolean xp()
{
return this.mCurrentX < this.azH / 2;
}
public Bitmap I()
{
if ((this.bd == null) || (this.bd.isRecycled()))
{
O();
this.bd = H();
}
for (;;)
{
return this.bd;
d(this.mCanvas, getWidth(), getHeight());
}
}
public void a(jhg.a parama)
{
this.jdField_a_of_type_Jhg$a = parama;
}
void awq()
{
float f1 = 0.48F * this.hY;
this.azO = ((int)(this.azO * f1));
this.azP = ((int)(this.azP * f1));
this.azQ = ((int)(f1 * this.azQ));
}
protected int b(Paint paramPaint, String paramString)
{
if (this.jdField_a_of_type_Ijn != null) {}
for (int i = this.jdField_a_of_type_Ijn.l.length();; i = 0)
{
int j = this.jdField_a_of_type_Jhg$a.azR;
int k = this.azO;
int m = this.jdField_a_of_type_Jhg$a.azS;
return (i - 1) * this.azP + (j + k + m * i);
}
}
protected int c(Paint paramPaint)
{
this.mHeight = this.jdField_a_of_type_Jhg$a.azR;
this.aq.right = this.mHeight;
this.aq.bottom = this.mHeight;
return this.mHeight;
}
protected int cF(int paramInt)
{
if (paramInt < 8) {
return this.cO[0];
}
return this.cO[1];
}
protected void d(Canvas paramCanvas, int paramInt1, int paramInt2)
{
long l = System.currentTimeMillis();
paramCanvas.drawPaint(this.jdField_ap_of_type_AndroidGraphicsPaint);
paramCanvas.save();
paramCanvas.clipRect(this.jdField_a_of_type_Jhg$a.azR / 2, 0, paramInt1, paramInt2);
float f2 = this.jdField_a_of_type_Jhg$a.azR + this.azO;
float f1 = f2;
if (xp())
{
f1 = f2 - 100.0F * this.hY;
f1 = (f2 - f1) * (this.mCurrentX * 2) / this.azH + f1;
}
paramCanvas.drawBitmap(this.bz, f1, (this.jdField_a_of_type_Jhg$a.azR - this.jdField_a_of_type_Jhg$a.azS) / 2, this.mPaint);
paramCanvas.restore();
Bitmap localBitmap = this.jdField_a_of_type_Jhg$a.f[((int)((l - this.mStartTime) / 200L % this.jdField_a_of_type_Jhg$a.f.length))];
this.jdField_ap_of_type_AndroidGraphicsRect.right = localBitmap.getWidth();
this.jdField_ap_of_type_AndroidGraphicsRect.bottom = localBitmap.getHeight();
paramCanvas.drawBitmap(localBitmap, this.jdField_ap_of_type_AndroidGraphicsRect, this.aq, this.mPaint);
}
public int my()
{
return this.jdField_a_of_type_Jhg$a.azT;
}
void releaseBitmap()
{
super.releaseBitmap();
if (this.bz != null)
{
if (!this.bz.isRecycled()) {
this.bz.recycle();
}
this.bz = null;
}
}
public static class a
{
int azR;
int azS;
int azT;
Bitmap[] f;
public a(Bitmap[] paramArrayOfBitmap, int paramInt1, int paramInt2, int paramInt3)
{
this.f = paramArrayOfBitmap;
this.azR = paramInt1;
this.azS = paramInt2;
this.azT = paramInt3;
}
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.tim\classes13.jar
* Qualified Name: jhg
* JD-Core Version: 0.7.0.1
*/ | tsuzcx/qq_apk | com.tencent.tim/classes.jar/jhg.java | 5,579 | // 274 8 8 m int
| line_comment | nl | import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import com.tencent.av.ui.funchat.zimu.ZimuView;
import java.lang.ref.WeakReference;
public class jhg
extends jhf
{
private jhg.a a;
private Paint jdField_ap_of_type_AndroidGraphicsPaint = new Paint();
Rect jdField_ap_of_type_AndroidGraphicsRect = new Rect(0, 0, 0, 0);
Rect aq = new Rect(0, 0, 0, 0);
int azO = 10;
int azP = 8;
int azQ = 4;
private Bitmap bz;
private final int[] cO;
private Canvas f = new Canvas();
private long mStartTime = System.currentTimeMillis();
public jhg(Context paramContext, WeakReference<ZimuView> paramWeakReference, int paramInt1, int paramInt2, float paramFloat, jhg.a parama)
{
super(paramContext, paramWeakReference, paramInt1, paramInt2, paramFloat);
this.jdField_ap_of_type_AndroidGraphicsPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
this.mPaint.setTextAlign(Paint.Align.CENTER);
this.cO = new int[] { paramInt1 / 6, paramInt1 / 5 };
this.jdField_a_of_type_Jhg$a = parama;
awq();
}
/* Error */
private Bitmap O()
{
// Byte code:
// 0: iconst_0
// 1: istore 5
// 3: aload_0
// 4: getfield 111 jhg:jdField_a_of_type_Ijn Lijn;
// 7: getfield 117 ijn:l Ljava/lang/CharSequence;
// 10: checkcast 119 java/lang/String
// 13: astore 9
// 15: aload 9
// 17: invokevirtual 123 java/lang/String:length ()I
// 20: istore 6
// 22: aload_0
// 23: aload_0
// 24: getfield 96 jhg:jdField_a_of_type_Jhg$a Ljhg$a;
// 27: getfield 126 jhg$a:azS I
// 30: iload 6
// 32: imul
// 33: iload 6
// 35: iconst_1
// 36: isub
// 37: aload_0
// 38: getfield 49 jhg:azP I
// 41: imul
// 42: iadd
// 43: aload_0
// 44: getfield 96 jhg:jdField_a_of_type_Jhg$a Ljhg$a;
// 47: getfield 126 jhg$a:azS I
// 50: getstatic 132 android/graphics/Bitmap$Config:ARGB_8888 Landroid/graphics/Bitmap$Config;
// 53: invokestatic 138 android/graphics/Bitmap:createBitmap (IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap;
// 56: putfield 140 jhg:bz Landroid/graphics/Bitmap;
// 59: aload_0
// 60: getfield 45 jhg:f Landroid/graphics/Canvas;
// 63: aload_0
// 64: getfield 140 jhg:bz Landroid/graphics/Bitmap;
// 67: invokevirtual 144 android/graphics/Canvas:setBitmap (Landroid/graphics/Bitmap;)V
// 70: aload_0
// 71: getfield 96 jhg:jdField_a_of_type_Jhg$a Ljhg$a;
// 74: getfield 126 jhg$a:azS I
// 77: iconst_2
// 78: idiv
// 79: i2f
// 80: fstore_2
// 81: aload_0
// 82: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 85: invokevirtual 148 android/graphics/Paint:getFontMetrics ()Landroid/graphics/Paint$FontMetrics;
// 88: astore 10
// 90: aload 10
// 92: getfield 154 android/graphics/Paint$FontMetrics:ascent F
// 95: fstore_1
// 96: aload 10
// 98: getfield 157 android/graphics/Paint$FontMetrics:descent F
// 101: fload_1
// 102: fadd
// 103: fconst_2
// 104: fdiv
// 105: fstore_3
// 106: aload_0
// 107: getfield 51 jhg:azQ I
// 110: iconst_2
// 111: idiv
// 112: i2f
// 113: fstore 4
// 115: fload_2
// 116: fstore_1
// 117: iload 5
// 119: iload 6
// 121: if_icmpge +194 -> 315
// 124: aload_0
// 125: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 128: iconst_0
// 129: invokevirtual 161 android/graphics/Paint:setAntiAlias (Z)V
// 132: aload_0
// 133: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 136: getstatic 167 android/graphics/Paint$Style:FILL Landroid/graphics/Paint$Style;
// 139: invokevirtual 171 android/graphics/Paint:setStyle (Landroid/graphics/Paint$Style;)V
// 142: aload_0
// 143: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 146: iconst_m1
// 147: invokevirtual 175 android/graphics/Paint:setColor (I)V
// 150: aload_0
// 151: getfield 45 jhg:f Landroid/graphics/Canvas;
// 154: fload_1
// 155: fload_2
// 156: fload_2
// 157: aload_0
// 158: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 161: invokevirtual 179 android/graphics/Canvas:drawCircle (FFFLandroid/graphics/Paint;)V
// 164: aload_0
// 165: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 168: iconst_1
// 169: invokevirtual 161 android/graphics/Paint:setAntiAlias (Z)V
// 172: aload_0
// 173: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 176: getstatic 182 android/graphics/Paint$Style:STROKE Landroid/graphics/Paint$Style;
// 179: invokevirtual 171 android/graphics/Paint:setStyle (Landroid/graphics/Paint$Style;)V
// 182: aload_0
// 183: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 186: ldc 183
// 188: invokevirtual 175 android/graphics/Paint:setColor (I)V
// 191: aload_0
// 192: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 195: aload_0
// 196: getfield 51 jhg:azQ I
// 199: i2f
// 200: invokevirtual 187 android/graphics/Paint:setStrokeWidth (F)V
// 203: aload_0
// 204: getfield 45 jhg:f Landroid/graphics/Canvas;
// 207: fload_1
// 208: fload_2
// 209: fload_2
// 210: fload 4
// 212: fsub
// 213: aload_0
// 214: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 217: invokevirtual 179 android/graphics/Canvas:drawCircle (FFFLandroid/graphics/Paint;)V
// 220: aload_0
// 221: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 224: fconst_0
// 225: invokevirtual 187 android/graphics/Paint:setStrokeWidth (F)V
// 228: aload_0
// 229: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 232: getstatic 167 android/graphics/Paint$Style:FILL Landroid/graphics/Paint$Style;
// 235: invokevirtual 171 android/graphics/Paint:setStyle (Landroid/graphics/Paint$Style;)V
// 238: aload_0
// 239: getfield 45 jhg:f Landroid/graphics/Canvas;
// 242: aload 9
// 244: iload 5
// 246: iload 5
// 248: iconst_1
// 249: iadd
// 250: fload_1
// 251: fload_2
// 252: fload_3
// 253: fsub
// 254: aload_0
// 255: getfield 82 jhg:mPaint Landroid/graphics/Paint;
// 258: invokevirtual 191 android/graphics/Canvas:drawText (Ljava/lang/String;IIFFLandroid/graphics/Paint;)V
// 261: aload_0
// 262: getfield 96 jhg:jdField_a_of_type_Jhg$a Ljhg$a;
// 265: getfield 126 jhg$a:azS I
// 268: istore 7
// 270: aload_0
// 271: getfield 49 jhg:azP I
// 274: istore 8
// 276: fload_1
// 277: iload 7
// 279: iload 8
// 281: iadd
// 282: i2f
// 283: fadd
// 284: fstore_1
// 285: iload 5
// 287: iconst_1
// 288: iadd
// 289: istore 5
// 291: goto -174 -> 117
// 294: astore 9
// 296: invokestatic 197 com/tencent/qphone/base/util/QLog:isColorLevel ()Z
// 299: ifeq +16 -> 315
// 302: aload_0
// 303: getfield 201 jhg:TAG Ljava/lang/String;
// 306: iconst_2
// 307: aload 9
// 309: invokevirtual 205 java/lang/OutOfMemoryError:getMessage ()Ljava/lang/String;
// 312: invokestatic 209 com/tencent/qphone/base/util/QLog:e (Ljava/lang/String;ILjava/lang/String;)V
// 315: aload_0
// 316: getfield 140 jhg:bz Landroid/graphics/Bitmap;
// 319: areturn
// 320: astore 9
// 322: invokestatic 197 com/tencent/qphone/base/util/QLog:isColorLevel ()Z
// 325: ifeq -10 -> 315
// 328: aload_0
// 329: getfield 201 jhg:TAG Ljava/lang/String;
// 332: iconst_2
// 333: aload 9
// 335: invokevirtual 210 java/lang/Exception:getMessage ()Ljava/lang/String;
// 338: invokestatic 209 com/tencent/qphone/base/util/QLog:e (Ljava/lang/String;ILjava/lang/String;)V
// 341: goto -26 -> 315
// Local variable table:
// start length slot name signature
// 0 344 0 this jhg
// 95 190 1 f1 float
// 80 172 2 f2 float
// 105 148 3 f3 float
// 113 98 4 f4 float
// 1 289 5 i int
// 20 102 6 j int
// 268 14 7 k int
// 274 8<SUF>
// 13 230 9 str String
// 294 14 9 localOutOfMemoryError java.lang.OutOfMemoryError
// 320 14 9 localException java.lang.Exception
// 88 9 10 localFontMetrics android.graphics.Paint.FontMetrics
// Exception table:
// from to target type
// 3 115 294 java/lang/OutOfMemoryError
// 124 276 294 java/lang/OutOfMemoryError
// 3 115 320 java/lang/Exception
// 124 276 320 java/lang/Exception
}
private boolean xp()
{
return this.mCurrentX < this.azH / 2;
}
public Bitmap I()
{
if ((this.bd == null) || (this.bd.isRecycled()))
{
O();
this.bd = H();
}
for (;;)
{
return this.bd;
d(this.mCanvas, getWidth(), getHeight());
}
}
public void a(jhg.a parama)
{
this.jdField_a_of_type_Jhg$a = parama;
}
void awq()
{
float f1 = 0.48F * this.hY;
this.azO = ((int)(this.azO * f1));
this.azP = ((int)(this.azP * f1));
this.azQ = ((int)(f1 * this.azQ));
}
protected int b(Paint paramPaint, String paramString)
{
if (this.jdField_a_of_type_Ijn != null) {}
for (int i = this.jdField_a_of_type_Ijn.l.length();; i = 0)
{
int j = this.jdField_a_of_type_Jhg$a.azR;
int k = this.azO;
int m = this.jdField_a_of_type_Jhg$a.azS;
return (i - 1) * this.azP + (j + k + m * i);
}
}
protected int c(Paint paramPaint)
{
this.mHeight = this.jdField_a_of_type_Jhg$a.azR;
this.aq.right = this.mHeight;
this.aq.bottom = this.mHeight;
return this.mHeight;
}
protected int cF(int paramInt)
{
if (paramInt < 8) {
return this.cO[0];
}
return this.cO[1];
}
protected void d(Canvas paramCanvas, int paramInt1, int paramInt2)
{
long l = System.currentTimeMillis();
paramCanvas.drawPaint(this.jdField_ap_of_type_AndroidGraphicsPaint);
paramCanvas.save();
paramCanvas.clipRect(this.jdField_a_of_type_Jhg$a.azR / 2, 0, paramInt1, paramInt2);
float f2 = this.jdField_a_of_type_Jhg$a.azR + this.azO;
float f1 = f2;
if (xp())
{
f1 = f2 - 100.0F * this.hY;
f1 = (f2 - f1) * (this.mCurrentX * 2) / this.azH + f1;
}
paramCanvas.drawBitmap(this.bz, f1, (this.jdField_a_of_type_Jhg$a.azR - this.jdField_a_of_type_Jhg$a.azS) / 2, this.mPaint);
paramCanvas.restore();
Bitmap localBitmap = this.jdField_a_of_type_Jhg$a.f[((int)((l - this.mStartTime) / 200L % this.jdField_a_of_type_Jhg$a.f.length))];
this.jdField_ap_of_type_AndroidGraphicsRect.right = localBitmap.getWidth();
this.jdField_ap_of_type_AndroidGraphicsRect.bottom = localBitmap.getHeight();
paramCanvas.drawBitmap(localBitmap, this.jdField_ap_of_type_AndroidGraphicsRect, this.aq, this.mPaint);
}
public int my()
{
return this.jdField_a_of_type_Jhg$a.azT;
}
void releaseBitmap()
{
super.releaseBitmap();
if (this.bz != null)
{
if (!this.bz.isRecycled()) {
this.bz.recycle();
}
this.bz = null;
}
}
public static class a
{
int azR;
int azS;
int azT;
Bitmap[] f;
public a(Bitmap[] paramArrayOfBitmap, int paramInt1, int paramInt2, int paramInt3)
{
this.f = paramArrayOfBitmap;
this.azR = paramInt1;
this.azS = paramInt2;
this.azT = paramInt3;
}
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.tim\classes13.jar
* Qualified Name: jhg
* JD-Core Version: 0.7.0.1
*/ |
125621_34 | package org.vufind.index;
/**
* Geographic indexing routines.
*
* This code is designed to get latitude and longitude coordinates.
* Records can have multiple coordinates sets of points and/or rectangles.
* Points are represented by coordinate sets where N=S E=W.
*
* code adapted from xrosecky - Moravian Library
* https://github.com/moravianlibrary/VuFind-2.x/blob/master/import/index_scripts/geo.bsh
*
* Copyright (C) Villanova University 2017.
*
* 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.
*
* 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
*/
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.marc4j.marc.ControlField;
import org.marc4j.marc.DataField;
import org.marc4j.marc.Record;
import org.marc4j.marc.Subfield;
import org.marc4j.marc.VariableField;
import org.solrmarc.index.indexer.ValueIndexerFactory;
import org.solrmarc.index.SolrIndexer;
import org.solrmarc.tools.PropertyUtils;
import org.solrmarc.tools.SolrMarcIndexerException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Geographic indexing routines.
*/
public class GeoTools
{
private static final Pattern COORDINATES_PATTERN = Pattern.compile("^([eEwWnNsS])(\\d{3})(\\d{2})(\\d{2})");
private static final Pattern HDMSHDD_PATTERN = Pattern.compile("^([eEwWnNsS])(\\d+(\\.\\d+)?)");
private static final Pattern PMDD_PATTERN = Pattern.compile("^([-+]?\\d+(\\.\\d+)?)");
static String datePrefix = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
static String vufindLocal = System.getenv("VUFIND_LOCAL_DIR");
static String vufindHome = System.getenv("VUFIND_HOME");
private static Properties vufindConfigs = null;
// Initialize logging category
static Logger logger = Logger.getLogger(GeoTools.class.getName());
/**
* Constructor
*/
public GeoTools()
{
try {
vufindConfigs = PropertyUtils.loadProperties(ValueIndexerFactory.instance().getHomeDirs(), "vufind.properties");
} catch (IllegalArgumentException e) {
// If the properties load failed, don't worry about it -- we'll use defaults.
}
}
/**
* Convert MARC coordinates into long_lat format.
*
* @param Record record
* @return List geo_coordinates
*/
public List<String> getAllCoordinates(Record record) {
List<String> geo_coordinates = new ArrayList<String>();
List<VariableField> list034 = record.getVariableFields("034");
if (list034 != null) {
for (VariableField vf : list034) {
HashMap<Character, String> coords = getCoordinateValues(vf);
// Check for null coordinates
if (validateCoordinateValues(record, coords)) {
// Check and convert coordinates to +/- decimal degrees
Double west = convertCoordinate(coords.get('d'));
Double east = convertCoordinate(coords.get('e'));
Double north = convertCoordinate(coords.get('f'));
Double south = convertCoordinate(coords.get('g'));
if (validateDDCoordinates(record, west, east, north, south)) {
// New Format for indexing coordinates in Solr 5.0 - minX, maxX, maxY, minY
// Note - storage in Solr follows the WENS order, but display is WSEN order
String result = String.format("ENVELOPE(%s,%s,%s,%s)", new Object[] { west, east, north, south });
geo_coordinates.add(result);
}
}
}
}
return geo_coordinates;
}
/**
* Get all available coordinates from the record.
*
* @param Record record
* @return List geo_coordinates
*/
public List<String> getDisplayCoordinates(Record record) {
List<String> geo_coordinates = new ArrayList<String>();
List<VariableField> list034 = record.getVariableFields("034");
if (list034 != null) {
for (VariableField vf : list034) {
HashMap<Character, String> coords = getCoordinateValues(vf);
// Check for null coordinates
if (validateCoordinateValues(record, coords)) {
String result = String.format("%s %s %s %s", new Object[] { coords.get('d'), coords.get('e'), coords.get('f'), coords.get('g') });
geo_coordinates.add(result);
}
}
}
return geo_coordinates;
}
/**
* Log coordinate indexing errors to external log file.
*
* @param Record record
* @param HashMap coords
* @param String error message
*/
public static void logErrorMessage(Record record, HashMap coords, String message) {
// Initialize error logging variables
String msgError = message;
String recNum = "Not available";
ControlField recID = (ControlField) record.getVariableField("001");
if (recID != null) {
recNum = recID.getData().trim();
}
String coordinates = "Coordinates: {" + coords.get('d') + "} {" + coords.get('e') + "} {" + coords.get('f') + "} {" + coords.get('g') + "}";
String logPath = getLogPath();
String logFilename = datePrefix + "_CoordinateErrors.txt";
String outPath = logPath + "/" + logFilename;
// Output Error message
logger.error("Not indexing INVALID coordinates for Record ID: " + recNum);
logger.error("... " + msgError);
if (logPath != null) {
logger.error("... Check coordinate error log: " + outPath);
// Log ID and error message and coordinates in error file
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outPath, true)));
out.println(logFilename + "\t" + recNum + "\t" + msgError + "\t" + coordinates);
out.close();
} catch (IOException e) {
System.out.println("io exception occurred");
e.printStackTrace();
}
} else {
// output error that log file cannot be created
logger.error("..... No coordinate error log. Check vufind.properties settings...");
}
}
/**
* Get path for coordinate error log file.
*
* @return String logPath
*/
public static String getLogPath() {
// Get coordinate error log path setting
String coordLogPath = PropertyUtils.getProperty(vufindConfigs, "coordinate.log.path");
//If coordinate.log.path doesn't exist or is not set, try some other places
if (coordLogPath == null) {
if (vufindLocal != null) {
File dir = new File(vufindLocal + "/import");
if (dir.exists()) {
coordLogPath = vufindLocal + "/import";
}
} else if (vufindLocal == null && vufindHome != null) {
File dir = new File(vufindHome + "/import");
if (dir.exists()) {
coordLogPath = vufindHome + "/import";
}
} else {
coordLogPath = null;
}
}
return coordLogPath;
}
/**
* Get all coordinate values from list034
*
* @param VariableField vf
* @return HashMap full_coords
*/
protected HashMap<Character, String> getCoordinateValues(VariableField vf) {
DataField df = (DataField) vf;
HashMap<Character, String> coords = new HashMap();
for (char code = 'd'; code <= 'g'; code++) {
Subfield subfield = df.getSubfield(code);
if (subfield != null) {
coords.put(code, subfield.getData());
}
}
// If coordinate set is a point with 2 coordinates, fill the empty values.
HashMap<Character, String> full_coords = fillEmptyPointCoordinates(coords);
return full_coords;
}
/**
* If coordinates are a point, fill empty N/S or E/W coordinate
*
* @param HashMap coords
* @return HashMap full_coords
*/
protected HashMap<Character, String> fillEmptyPointCoordinates(HashMap coords) {
HashMap<Character, String> full_coords = coords;
if (coords.containsKey('d') && !coords.containsKey('e') && coords.containsKey('f') && !coords.containsKey('g')) {
full_coords.put('e', coords.get('d').toString());
full_coords.put('g', coords.get('f').toString());
}
if (coords.containsKey('e') && !coords.containsKey('d') && coords.containsKey('g') && !coords.containsKey('h')) {
full_coords.put('d', coords.get('e').toString());
full_coords.put('f', coords.get('g').toString());
}
return full_coords;
}
/**
* Check record coordinates to make sure they do not contain null values.
*
* @param Record record
* @param HashMap coords
* @return boolean
*/
protected boolean validateCoordinateValues(Record record, HashMap coords) {
if (coords.containsKey('d') && coords.containsKey('e') && coords.containsKey('f') && coords.containsKey('g')) {
return true;
}
String msgError = "Coordinate values contain null values.";
logErrorMessage(record, coords, msgError);
return false;
}
/**
* Check coordinate type HDMS HDD or +/-DD.
*
* @param String coordinateStr
* @return Double coordinate
*/
protected Double convertCoordinate(String coordinateStr) {
Double coordinate = Double.NaN;
Matcher HDmatcher = HDMSHDD_PATTERN.matcher(coordinateStr);
Matcher PMDmatcher = PMDD_PATTERN.matcher(coordinateStr);
if (HDmatcher.matches()) {
String hemisphere = HDmatcher.group(1).toUpperCase();
Double degrees = Double.parseDouble(HDmatcher.group(2));
// Check for HDD or HDMS
if (hemisphere.equals("N") || hemisphere.equals("S")) {
if (degrees > 90) {
String hdmsCoordinate = hemisphere+"0"+HDmatcher.group(2);
coordinate = coordinateToDecimal(hdmsCoordinate);
} else {
coordinate = Double.parseDouble(HDmatcher.group(2));
if (hemisphere.equals("S")) {
coordinate *= -1;
}
}
}
if (hemisphere.equals("E") || hemisphere.equals("W")) {
if (degrees > 180) {
String hdmsCoordinate = HDmatcher.group(0);
coordinate = coordinateToDecimal(hdmsCoordinate);
} else {
coordinate = Double.parseDouble(HDmatcher.group(2));
if (hemisphere.equals("W")) {
coordinate *= -1;
}
}
}
return coordinate;
} else if (PMDmatcher.matches()) {
coordinate = Double.parseDouble(PMDmatcher.group(1));
return coordinate;
} else {
return Double.NaN;
}
}
/**
* Convert HDMS coordinates to decimal degrees.
*
* @param String coordinateStr
* @return Double coordinate
*/
protected Double coordinateToDecimal(String coordinateStr) {
Matcher matcher = COORDINATES_PATTERN.matcher(coordinateStr);
if (matcher.matches()) {
String hemisphere = matcher.group(1).toUpperCase();
int degrees = Integer.parseInt(matcher.group(2));
int minutes = Integer.parseInt(matcher.group(3));
int seconds = Integer.parseInt(matcher.group(4));
double coordinate = degrees + (minutes / 60.0) + (seconds / 3600.0);
if (hemisphere.equals("W") || hemisphere.equals("S")) {
coordinate *= -1;
}
return coordinate;
}
return Double.NaN;
}
/**
* Check decimal degree coordinates to make sure they are valid.
*
* @param Record record
* @param Double west, east, north, south
* @return boolean
*/
protected boolean validateDDCoordinates(Record record, Double west, Double east, Double north, Double south) {
boolean validValues = true;
boolean validLines = true;
boolean validExtent = true;
boolean validNorthSouth = true;
boolean validEastWest = true;
boolean validCoordDist = true;
if (validateValues(record, west, east, north, south)) {
validLines = validateLines(record, west, east, north, south);
validExtent = validateExtent(record, west, east, north, south);
validNorthSouth = validateNorthSouth(record, north, south);
validEastWest = validateEastWest(record, east, west);
validCoordDist = validateCoordinateDistance(record, west, east, north, south);
} else {
return false;
}
// Validate all coordinate combinations
if (!validLines || !validExtent || !validNorthSouth || !validEastWest || !validCoordDist) {
return false;
} else {
return true;
}
}
/**
* Check decimal degree coordinates to make sure they do not form a line at the poles.
*
* @param Record record
* @param Double west, east, north, south
* @return boolean
*/
public boolean validateLines(Record record, Double west, Double east, Double north, Double south) {
if ((!west.equals(east) && north.equals(south)) && (north == 90 || south == -90)) {
String msgError = "Coordinates form a line at the pole";
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
return true;
}
/**
* Check decimal degree coordinates to make sure they do not contain null values.
*
* @param Record record
* @param Double west, east, north, south
* @return boolean
*/
public boolean validateValues(Record record, Double west, Double east, Double north, Double south) {
if (west.isNaN() || east.isNaN() || north.isNaN() || south.isNaN()) {
String msgError = "Decimal Degree coordinates contain invalid values";
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
return true;
}
/**
* Check decimal degree coordinates to make sure they are within map extent.
*
* @param Record record
* @param Double west, east, north, south
* @return boolean
*/
public boolean validateExtent(Record record, Double west, Double east, Double north, Double south) {
if (west > 180.0 || west < -180.0 || east > 180.0 || east < -180.0
|| north > 90.0 || north < -90.0 || south > 90.0 || south < -90.0
) {
String msgError = "Coordinates exceed map extent.";
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
return true;
}
/**
* Check decimal degree coordinates to make sure that north is not less than south.
*
* @param Record record
* @param Double north, south
* @return boolean
*/
public boolean validateNorthSouth(Record record, Double north, Double south) {
if (north < south) {
String msgError = "North < South.";
HashMap<Character, String> coords = buildCoordinateHashMap(Double.NaN, Double.NaN, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
return true;
}
/**
* Check decimal degree coordinates to make sure that east is not less than west.
*
* @param Record record
* @param Double east, west
* @return boolean
*/
public boolean validateEastWest(Record record, Double east, Double west) {
if (east < west) {
// Convert to 360 degree grid
if (east <= 0) {
east = 360 + east;
}
if (west < 0) {
west = 360 + west;
}
// Check again
if (east < west) {
String msgError = "East < West.";
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, Double.NaN, Double.NaN);
logErrorMessage(record, coords, msgError);
return false;
}
}
return true;
}
/**
* Check decimal degree coordinates to make sure they are not too close.
* Coordinates too close will cause Solr to run out of memory during indexing.
*
* @param Record record
* @param Double west, east, north, south
* @return boolean
*/
public boolean validateCoordinateDistance(Record record, Double west, Double east, Double north, Double south) {
Double distEW = east - west;
Double distNS = north - south;
//Check for South Pole coordinate distance
if ((north == -90 || south == -90) && (distNS > 0 && distNS < 0.167)) {
String msgError = "Coordinates < 0.167 degrees from South Pole. Coordinate Distance: "+distNS;
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
//Check for East-West coordinate distance
if ((west == 0 || east == 0) && (distEW > -2 && distEW <0)) {
String msgError = "Coordinates within 2 degrees of Prime Meridian. Coordinate Distance: "+distEW;
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
return true;
}
/**
* Build coordinate hash map for logging.
*
* @param Double west, east, north, south
* @return HashMap coords
*/
public HashMap buildCoordinateHashMap (Double west, Double east, Double north, Double south) {
HashMap<Character, String> coords = new HashMap();
coords.put('d', Double.toString(west));
coords.put('e', Double.toString(east));
coords.put('f', Double.toString(north));
coords.put('g', Double.toString(south));
return coords;
}
}
| tubhh/vufind | import/index_java/src/org/vufind/index/GeoTools.java | 5,509 | // Convert to 360 degree grid | line_comment | nl | package org.vufind.index;
/**
* Geographic indexing routines.
*
* This code is designed to get latitude and longitude coordinates.
* Records can have multiple coordinates sets of points and/or rectangles.
* Points are represented by coordinate sets where N=S E=W.
*
* code adapted from xrosecky - Moravian Library
* https://github.com/moravianlibrary/VuFind-2.x/blob/master/import/index_scripts/geo.bsh
*
* Copyright (C) Villanova University 2017.
*
* 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.
*
* 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
*/
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.marc4j.marc.ControlField;
import org.marc4j.marc.DataField;
import org.marc4j.marc.Record;
import org.marc4j.marc.Subfield;
import org.marc4j.marc.VariableField;
import org.solrmarc.index.indexer.ValueIndexerFactory;
import org.solrmarc.index.SolrIndexer;
import org.solrmarc.tools.PropertyUtils;
import org.solrmarc.tools.SolrMarcIndexerException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Geographic indexing routines.
*/
public class GeoTools
{
private static final Pattern COORDINATES_PATTERN = Pattern.compile("^([eEwWnNsS])(\\d{3})(\\d{2})(\\d{2})");
private static final Pattern HDMSHDD_PATTERN = Pattern.compile("^([eEwWnNsS])(\\d+(\\.\\d+)?)");
private static final Pattern PMDD_PATTERN = Pattern.compile("^([-+]?\\d+(\\.\\d+)?)");
static String datePrefix = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
static String vufindLocal = System.getenv("VUFIND_LOCAL_DIR");
static String vufindHome = System.getenv("VUFIND_HOME");
private static Properties vufindConfigs = null;
// Initialize logging category
static Logger logger = Logger.getLogger(GeoTools.class.getName());
/**
* Constructor
*/
public GeoTools()
{
try {
vufindConfigs = PropertyUtils.loadProperties(ValueIndexerFactory.instance().getHomeDirs(), "vufind.properties");
} catch (IllegalArgumentException e) {
// If the properties load failed, don't worry about it -- we'll use defaults.
}
}
/**
* Convert MARC coordinates into long_lat format.
*
* @param Record record
* @return List geo_coordinates
*/
public List<String> getAllCoordinates(Record record) {
List<String> geo_coordinates = new ArrayList<String>();
List<VariableField> list034 = record.getVariableFields("034");
if (list034 != null) {
for (VariableField vf : list034) {
HashMap<Character, String> coords = getCoordinateValues(vf);
// Check for null coordinates
if (validateCoordinateValues(record, coords)) {
// Check and convert coordinates to +/- decimal degrees
Double west = convertCoordinate(coords.get('d'));
Double east = convertCoordinate(coords.get('e'));
Double north = convertCoordinate(coords.get('f'));
Double south = convertCoordinate(coords.get('g'));
if (validateDDCoordinates(record, west, east, north, south)) {
// New Format for indexing coordinates in Solr 5.0 - minX, maxX, maxY, minY
// Note - storage in Solr follows the WENS order, but display is WSEN order
String result = String.format("ENVELOPE(%s,%s,%s,%s)", new Object[] { west, east, north, south });
geo_coordinates.add(result);
}
}
}
}
return geo_coordinates;
}
/**
* Get all available coordinates from the record.
*
* @param Record record
* @return List geo_coordinates
*/
public List<String> getDisplayCoordinates(Record record) {
List<String> geo_coordinates = new ArrayList<String>();
List<VariableField> list034 = record.getVariableFields("034");
if (list034 != null) {
for (VariableField vf : list034) {
HashMap<Character, String> coords = getCoordinateValues(vf);
// Check for null coordinates
if (validateCoordinateValues(record, coords)) {
String result = String.format("%s %s %s %s", new Object[] { coords.get('d'), coords.get('e'), coords.get('f'), coords.get('g') });
geo_coordinates.add(result);
}
}
}
return geo_coordinates;
}
/**
* Log coordinate indexing errors to external log file.
*
* @param Record record
* @param HashMap coords
* @param String error message
*/
public static void logErrorMessage(Record record, HashMap coords, String message) {
// Initialize error logging variables
String msgError = message;
String recNum = "Not available";
ControlField recID = (ControlField) record.getVariableField("001");
if (recID != null) {
recNum = recID.getData().trim();
}
String coordinates = "Coordinates: {" + coords.get('d') + "} {" + coords.get('e') + "} {" + coords.get('f') + "} {" + coords.get('g') + "}";
String logPath = getLogPath();
String logFilename = datePrefix + "_CoordinateErrors.txt";
String outPath = logPath + "/" + logFilename;
// Output Error message
logger.error("Not indexing INVALID coordinates for Record ID: " + recNum);
logger.error("... " + msgError);
if (logPath != null) {
logger.error("... Check coordinate error log: " + outPath);
// Log ID and error message and coordinates in error file
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outPath, true)));
out.println(logFilename + "\t" + recNum + "\t" + msgError + "\t" + coordinates);
out.close();
} catch (IOException e) {
System.out.println("io exception occurred");
e.printStackTrace();
}
} else {
// output error that log file cannot be created
logger.error("..... No coordinate error log. Check vufind.properties settings...");
}
}
/**
* Get path for coordinate error log file.
*
* @return String logPath
*/
public static String getLogPath() {
// Get coordinate error log path setting
String coordLogPath = PropertyUtils.getProperty(vufindConfigs, "coordinate.log.path");
//If coordinate.log.path doesn't exist or is not set, try some other places
if (coordLogPath == null) {
if (vufindLocal != null) {
File dir = new File(vufindLocal + "/import");
if (dir.exists()) {
coordLogPath = vufindLocal + "/import";
}
} else if (vufindLocal == null && vufindHome != null) {
File dir = new File(vufindHome + "/import");
if (dir.exists()) {
coordLogPath = vufindHome + "/import";
}
} else {
coordLogPath = null;
}
}
return coordLogPath;
}
/**
* Get all coordinate values from list034
*
* @param VariableField vf
* @return HashMap full_coords
*/
protected HashMap<Character, String> getCoordinateValues(VariableField vf) {
DataField df = (DataField) vf;
HashMap<Character, String> coords = new HashMap();
for (char code = 'd'; code <= 'g'; code++) {
Subfield subfield = df.getSubfield(code);
if (subfield != null) {
coords.put(code, subfield.getData());
}
}
// If coordinate set is a point with 2 coordinates, fill the empty values.
HashMap<Character, String> full_coords = fillEmptyPointCoordinates(coords);
return full_coords;
}
/**
* If coordinates are a point, fill empty N/S or E/W coordinate
*
* @param HashMap coords
* @return HashMap full_coords
*/
protected HashMap<Character, String> fillEmptyPointCoordinates(HashMap coords) {
HashMap<Character, String> full_coords = coords;
if (coords.containsKey('d') && !coords.containsKey('e') && coords.containsKey('f') && !coords.containsKey('g')) {
full_coords.put('e', coords.get('d').toString());
full_coords.put('g', coords.get('f').toString());
}
if (coords.containsKey('e') && !coords.containsKey('d') && coords.containsKey('g') && !coords.containsKey('h')) {
full_coords.put('d', coords.get('e').toString());
full_coords.put('f', coords.get('g').toString());
}
return full_coords;
}
/**
* Check record coordinates to make sure they do not contain null values.
*
* @param Record record
* @param HashMap coords
* @return boolean
*/
protected boolean validateCoordinateValues(Record record, HashMap coords) {
if (coords.containsKey('d') && coords.containsKey('e') && coords.containsKey('f') && coords.containsKey('g')) {
return true;
}
String msgError = "Coordinate values contain null values.";
logErrorMessage(record, coords, msgError);
return false;
}
/**
* Check coordinate type HDMS HDD or +/-DD.
*
* @param String coordinateStr
* @return Double coordinate
*/
protected Double convertCoordinate(String coordinateStr) {
Double coordinate = Double.NaN;
Matcher HDmatcher = HDMSHDD_PATTERN.matcher(coordinateStr);
Matcher PMDmatcher = PMDD_PATTERN.matcher(coordinateStr);
if (HDmatcher.matches()) {
String hemisphere = HDmatcher.group(1).toUpperCase();
Double degrees = Double.parseDouble(HDmatcher.group(2));
// Check for HDD or HDMS
if (hemisphere.equals("N") || hemisphere.equals("S")) {
if (degrees > 90) {
String hdmsCoordinate = hemisphere+"0"+HDmatcher.group(2);
coordinate = coordinateToDecimal(hdmsCoordinate);
} else {
coordinate = Double.parseDouble(HDmatcher.group(2));
if (hemisphere.equals("S")) {
coordinate *= -1;
}
}
}
if (hemisphere.equals("E") || hemisphere.equals("W")) {
if (degrees > 180) {
String hdmsCoordinate = HDmatcher.group(0);
coordinate = coordinateToDecimal(hdmsCoordinate);
} else {
coordinate = Double.parseDouble(HDmatcher.group(2));
if (hemisphere.equals("W")) {
coordinate *= -1;
}
}
}
return coordinate;
} else if (PMDmatcher.matches()) {
coordinate = Double.parseDouble(PMDmatcher.group(1));
return coordinate;
} else {
return Double.NaN;
}
}
/**
* Convert HDMS coordinates to decimal degrees.
*
* @param String coordinateStr
* @return Double coordinate
*/
protected Double coordinateToDecimal(String coordinateStr) {
Matcher matcher = COORDINATES_PATTERN.matcher(coordinateStr);
if (matcher.matches()) {
String hemisphere = matcher.group(1).toUpperCase();
int degrees = Integer.parseInt(matcher.group(2));
int minutes = Integer.parseInt(matcher.group(3));
int seconds = Integer.parseInt(matcher.group(4));
double coordinate = degrees + (minutes / 60.0) + (seconds / 3600.0);
if (hemisphere.equals("W") || hemisphere.equals("S")) {
coordinate *= -1;
}
return coordinate;
}
return Double.NaN;
}
/**
* Check decimal degree coordinates to make sure they are valid.
*
* @param Record record
* @param Double west, east, north, south
* @return boolean
*/
protected boolean validateDDCoordinates(Record record, Double west, Double east, Double north, Double south) {
boolean validValues = true;
boolean validLines = true;
boolean validExtent = true;
boolean validNorthSouth = true;
boolean validEastWest = true;
boolean validCoordDist = true;
if (validateValues(record, west, east, north, south)) {
validLines = validateLines(record, west, east, north, south);
validExtent = validateExtent(record, west, east, north, south);
validNorthSouth = validateNorthSouth(record, north, south);
validEastWest = validateEastWest(record, east, west);
validCoordDist = validateCoordinateDistance(record, west, east, north, south);
} else {
return false;
}
// Validate all coordinate combinations
if (!validLines || !validExtent || !validNorthSouth || !validEastWest || !validCoordDist) {
return false;
} else {
return true;
}
}
/**
* Check decimal degree coordinates to make sure they do not form a line at the poles.
*
* @param Record record
* @param Double west, east, north, south
* @return boolean
*/
public boolean validateLines(Record record, Double west, Double east, Double north, Double south) {
if ((!west.equals(east) && north.equals(south)) && (north == 90 || south == -90)) {
String msgError = "Coordinates form a line at the pole";
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
return true;
}
/**
* Check decimal degree coordinates to make sure they do not contain null values.
*
* @param Record record
* @param Double west, east, north, south
* @return boolean
*/
public boolean validateValues(Record record, Double west, Double east, Double north, Double south) {
if (west.isNaN() || east.isNaN() || north.isNaN() || south.isNaN()) {
String msgError = "Decimal Degree coordinates contain invalid values";
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
return true;
}
/**
* Check decimal degree coordinates to make sure they are within map extent.
*
* @param Record record
* @param Double west, east, north, south
* @return boolean
*/
public boolean validateExtent(Record record, Double west, Double east, Double north, Double south) {
if (west > 180.0 || west < -180.0 || east > 180.0 || east < -180.0
|| north > 90.0 || north < -90.0 || south > 90.0 || south < -90.0
) {
String msgError = "Coordinates exceed map extent.";
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
return true;
}
/**
* Check decimal degree coordinates to make sure that north is not less than south.
*
* @param Record record
* @param Double north, south
* @return boolean
*/
public boolean validateNorthSouth(Record record, Double north, Double south) {
if (north < south) {
String msgError = "North < South.";
HashMap<Character, String> coords = buildCoordinateHashMap(Double.NaN, Double.NaN, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
return true;
}
/**
* Check decimal degree coordinates to make sure that east is not less than west.
*
* @param Record record
* @param Double east, west
* @return boolean
*/
public boolean validateEastWest(Record record, Double east, Double west) {
if (east < west) {
// Convert to<SUF>
if (east <= 0) {
east = 360 + east;
}
if (west < 0) {
west = 360 + west;
}
// Check again
if (east < west) {
String msgError = "East < West.";
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, Double.NaN, Double.NaN);
logErrorMessage(record, coords, msgError);
return false;
}
}
return true;
}
/**
* Check decimal degree coordinates to make sure they are not too close.
* Coordinates too close will cause Solr to run out of memory during indexing.
*
* @param Record record
* @param Double west, east, north, south
* @return boolean
*/
public boolean validateCoordinateDistance(Record record, Double west, Double east, Double north, Double south) {
Double distEW = east - west;
Double distNS = north - south;
//Check for South Pole coordinate distance
if ((north == -90 || south == -90) && (distNS > 0 && distNS < 0.167)) {
String msgError = "Coordinates < 0.167 degrees from South Pole. Coordinate Distance: "+distNS;
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
//Check for East-West coordinate distance
if ((west == 0 || east == 0) && (distEW > -2 && distEW <0)) {
String msgError = "Coordinates within 2 degrees of Prime Meridian. Coordinate Distance: "+distEW;
HashMap<Character, String> coords = buildCoordinateHashMap(west, east, north, south);
logErrorMessage(record, coords, msgError);
return false;
}
return true;
}
/**
* Build coordinate hash map for logging.
*
* @param Double west, east, north, south
* @return HashMap coords
*/
public HashMap buildCoordinateHashMap (Double west, Double east, Double north, Double south) {
HashMap<Character, String> coords = new HashMap();
coords.put('d', Double.toString(west));
coords.put('e', Double.toString(east));
coords.put('f', Double.toString(north));
coords.put('g', Double.toString(south));
return coords;
}
}
|
169112_19 | /*
* j-Algo - j-Algo is an algorithm visualization tool, especially useful for
* students and lecturers of computer science. It is written in Java and platform
* independent. j-Algo is developed with the help of Dresden University of
* Technology.
*
* Copyright (C) 2004-2010 j-Algo-Team, [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., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* WARNING: This is generated code. DO *NOT* MODIFY IT! */
package org.jalgo.module.am0c0.parser.c0;
import java.util.ArrayList;
import org.jalgo.module.am0c0.model.c0.ast.*;
import org.jalgo.module.am0c0.parser.ParserUtils;
import beaver.*;
import org.jalgo.module.am0c0.parser.ErrorEvents;
import org.jalgo.module.am0c0.model.c0.trans.AtomicTrans.AtomicType;
/**
* This class is a LALR parser generated by
* <a href="http://beaver.sourceforge.net">Beaver</a> v0.9.6.1
* from the grammar specification "c0-parser.g".
*/
public class GeneratedC0Parser extends Parser {
static public class Terminals {
static public final short EOF = 0;
static public final short IDENT = 1;
static public final short MINUS = 2;
static public final short PLUS = 3;
static public final short SEMICOLON = 4;
static public final short LPAREN = 5;
static public final short NUMBER = 6;
static public final short LBRACKET = 7;
static public final short SCANF = 8;
static public final short PRINTF = 9;
static public final short IF = 10;
static public final short WHILE = 11;
static public final short RPAREN = 12;
static public final short RETURN = 13;
static public final short EQ = 14;
static public final short NE = 15;
static public final short LE = 16;
static public final short GE = 17;
static public final short LT = 18;
static public final short GT = 19;
static public final short RBRACKET = 20;
static public final short MULT = 21;
static public final short DIV = 22;
static public final short MOD = 23;
static public final short COMMA = 24;
static public final short ELSE = 25;
static public final short INT = 26;
static public final short ASSIGN = 27;
static public final short IFORMAT = 28;
static public final short AMP = 29;
static public final short DFORMAT = 30;
static public final short INCLUDE = 31;
static public final short STDIO = 32;
static public final short MAIN = 33;
static public final short CONST = 34;
}
static final ParsingTables PARSING_TABLES = new ParsingTables(
"U9obbbjiL4K0Xl#pjrBPbW8LjYsrq7OBhQMW8Du0kNW1lA9o4PHI5E#9ngWFFXYZYI$6nCk" +
"3HatGX0TzyS6O#6vCr0TVC055MwsY8hG52wK5AkCtS#PiTxUx98tdpzz$vf$$pENCdZcLOg" +
"tc5mjbj51PtQ9wrMawzLZeUnpK75sc#UPdYuBiJTItXBvlZVlIZnO#ctJP#wbl2ttVcl2b7" +
"onyDkMost7#2NtVMk5BVHO#MscpvFhCSEZxrcb#lZyv77KmxkymzTFUTz0CNphiy9U5gfsU" +
"fdxA#mwgygLUXpyTBhY$fqol7lI#WsRwqY67Fomqr$tTJlsCzntKv4k$EHonq0AdPwYFUDz" +
"17Nvj$Gw$MwZJwOZfrsBlEsY9p$vgeMQrwWfjqEMsH7rMw7kS2xEQfrfpBeUJ#7lKeajqBs" +
"KFBOVBjCDcDLlNu9tG2Zsag$6lDISYQ3UqetOpwfNAu0rfbTlVBbrdXYBG0hNQjTWT7JA3k" +
"jxDSaWDPZ02EQWrkToW6T1QbnlK9ZCGWHpKkbnkm1mdTIbxFQ0RpF48MW$j6fhL2DlmZg6B" +
"pD$u6ysn27eKtgExzOZvLrjr7zvvxTG3seM$rvoFe1xui1dNOt8NtdW4QkDkB7zP9tVTgjj" +
"qk#xGdRhBd9smpTa8gidpRzHANQLsBLMDDbFVCSbD#$j79rmpciCOldIpIun5O8GnttzDNb" +
"$vlUgYxJ75bL3WrBxnAIrY7asgrWpkcAbP$5Aws8CvcbiccoZ8pY#HNU2ocKdP#XBPP9bik" +
"aIseansSOciocIp9RArPRA9AVJRK2BRKYRRCeLiiaGsdSjcBxAs5jxefDeuWMqfJIa$6#Hb" +
"ApY9ApaxfkDMyIj9S$PqvhbPt3Ix5$QRuNa5zDpCELH7QI8N8sV7IhbH0v#pSwtZ$i9H0ju" +
"oss9fS#5ywxYpEDTOa0lAvj85EPlAailavHBamcVTwXZbqkGwYjPHIph5RhVxTLWq5AqtHQ" +
"u19sNSHIxNHisDPKpKPd9NuJxa#GKhAkUglbosO6x5TzLEzQxS#ANRfSTViYUJuQmMhdYEO" +
"atIUhW1ReFFIW7lJ700zb9$2puFFwJ#7lecZ56U1wlXSlgxWAx5jsTm1rm3CtZiHc3xtefk" +
"GPz4xHWlmtVXf$0hF7kg7qQVG4$2xs4NFCXGTYxDAFCDLk0DknDP0QTcR3Qw2JP1sru95yA" +
"baFK4k#0os0vtmvMm6$R05#0pz67dUHI#2Z#6duVdVl0Y#ZJ4rmVmC$WDxAEDPn3mA8Dtg3" +
"UYNwDsd45erxKHVH#rOt5ly0hifFuSodFKQ$0ZodmNWdtmTVW6tXVeVlGxlqz7h1QJQvLN#" +
"xzNFxgpJExGH3dOxBst2pD1XzTktxxFwoUJ#mjwlExD6#E0ro#zVfkNh$BUIAdvJOMiSpHQ" +
"W#zx3rmzbJx8F$L$vp6vJtUryskju9kMWac#k06CSI8BnZmJdC#MISyKTyMW$KudtBSwIny" +
"JEWt6EPFZl551IROvnZpZZgruhKv3jhZpqZAk9Vy1gTSq70==");
public ErrorEvents getErrorEvents() {
return (ErrorEvents) report;
}
private int convert(final Symbol symbol) {
return ParserUtils.safeSymbolToInt(symbol, (ErrorEvents) report);
}
private final Action[] actions;
public GeneratedC0Parser() {
super(PARSING_TABLES);
actions = new Action[] {
new Action() { // [0] Program = INCLUDE STDIO INT MAIN LPAREN RPAREN Block.b
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_b = _symbols[offset + 7];
final Block b = (Block) _symbol_b.value;
return new Symbol(new Program(b));
}
},
new Action() { // [1] Block = LBRACKET Declaration.d StatementSequence.s RETURN SEMICOLON RBRACKET
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_d = _symbols[offset + 2];
final Declaration d = (Declaration) _symbol_d.value;
final Symbol _symbol_s = _symbols[offset + 3];
final StatementSequence s = (StatementSequence) _symbol_s.value;
return new Symbol(new Block(d, s));
}
},
new Action() { // [2] Block = LBRACKET Declaration.d RETURN SEMICOLON RBRACKET
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_d = _symbols[offset + 2];
final Declaration d = (Declaration) _symbol_d.value;
return new Symbol(new Block(d, null));
}
},
new Action() { // [3] StatementSequence = Statement.stat
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_stat = _symbols[offset + 1];
final Statement stat = (Statement) _symbol_stat.value;
return new Symbol(new StatementSequence(stat));
}
},
new Action() { // [4] StatementSequence = StatementSequence.seq Statement.stat
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_seq = _symbols[offset + 1];
final StatementSequence seq = (StatementSequence) _symbol_seq.value;
final Symbol _symbol_stat = _symbols[offset + 2];
final Statement stat = (Statement) _symbol_stat.value;
seq.addStatement(stat); return new Symbol(seq);
}
},
new Action() { // [5] Declaration =
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(new Declaration(null, null));
}
},
new Action() { // [6] Declaration = ConstDeclaration.constdecl SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_constdecl = _symbols[offset + 1];
final ConstDeclaration constdecl = (ConstDeclaration) _symbol_constdecl.value;
return new Symbol(new Declaration(constdecl, null));
}
},
new Action() { // [7] Declaration = VarDeclaration.vardecl SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_vardecl = _symbols[offset + 1];
final VarDeclaration vardecl = (VarDeclaration) _symbol_vardecl.value;
return new Symbol(new Declaration(null, vardecl));
}
},
new Action() { // [8] Declaration = ConstDeclaration.constdecl SEMICOLON VarDeclaration.vardecl SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_constdecl = _symbols[offset + 1];
final ConstDeclaration constdecl = (ConstDeclaration) _symbol_constdecl.value;
final Symbol _symbol_vardecl = _symbols[offset + 3];
final VarDeclaration vardecl = (VarDeclaration) _symbol_vardecl.value;
return new Symbol(new Declaration(constdecl, vardecl));
}
},
new Action() { // [9] ConstDeclaration = CONST IDENT.i ASSIGN NUMBER.n
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 2];
final String i = (String) _symbol_i.value;
final Symbol n = _symbols[offset + 4];
return new Symbol(new ConstDeclaration(new C0AST.ConstIdent(i, convert(n))));
}
},
new Action() { // [10] ConstDeclaration = CONST IDENT.i ASSIGN MINUS NUMBER.n
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 2];
final String i = (String) _symbol_i.value;
final Symbol n = _symbols[offset + 5];
return new Symbol(new ConstDeclaration(new C0AST.ConstIdent(i, -convert(n))));
}
},
new Action() { // [11] ConstDeclaration = ConstDeclaration.d COMMA IDENT.i ASSIGN NUMBER.n
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_d = _symbols[offset + 1];
final ConstDeclaration d = (ConstDeclaration) _symbol_d.value;
final Symbol _symbol_i = _symbols[offset + 3];
final String i = (String) _symbol_i.value;
final Symbol n = _symbols[offset + 5];
d.addConstant(new C0AST.ConstIdent(i, convert(n))); return new Symbol(d);
}
},
new Action() { // [12] ConstDeclaration = ConstDeclaration.d COMMA IDENT.i ASSIGN MINUS NUMBER.n
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_d = _symbols[offset + 1];
final ConstDeclaration d = (ConstDeclaration) _symbol_d.value;
final Symbol _symbol_i = _symbols[offset + 3];
final String i = (String) _symbol_i.value;
final Symbol n = _symbols[offset + 6];
d.addConstant(new C0AST.ConstIdent(i, -convert(n))); return new Symbol(d);
}
},
new Action() { // [13] VarDeclaration = INT IDENT.i
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 2];
final String i = (String) _symbol_i.value;
return new Symbol(new VarDeclaration(new C0AST.Ident(i)));
}
},
new Action() { // [14] VarDeclaration = VarDeclaration.d COMMA IDENT.i
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_d = _symbols[offset + 1];
final VarDeclaration d = (VarDeclaration) _symbol_d.value;
final Symbol _symbol_i = _symbols[offset + 3];
final String i = (String) _symbol_i.value;
d.addVariable(new C0AST.Ident(i)); return new Symbol(d);
}
},
new Action() { // [15] Statement = IDENT.i ASSIGN SimpleExpr.e SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 1];
final String i = (String) _symbol_i.value;
final Symbol _symbol_e = _symbols[offset + 3];
final SimpleExpr e = (SimpleExpr) _symbol_e.value;
return new Symbol(new Statement.AssignmentStatement(i, e));
}
},
new Action() { // [16] Statement = IF LPAREN BoolExpr.e RPAREN Statement.s
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_e = _symbols[offset + 3];
final BoolExpression e = (BoolExpression) _symbol_e.value;
final Symbol _symbol_s = _symbols[offset + 5];
final Statement s = (Statement) _symbol_s.value;
return new Symbol(new Statement.IfStatement(e, s));
}
},
new Action() { // [17] Statement = IF LPAREN BoolExpr.e RPAREN Statement.s1 ELSE Statement.s2
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_e = _symbols[offset + 3];
final BoolExpression e = (BoolExpression) _symbol_e.value;
final Symbol _symbol_s1 = _symbols[offset + 5];
final Statement s1 = (Statement) _symbol_s1.value;
final Symbol _symbol_s2 = _symbols[offset + 7];
final Statement s2 = (Statement) _symbol_s2.value;
return new Symbol(new Statement.IfElseStatement(e, s1, s2));
}
},
new Action() { // [18] Statement = WHILE LPAREN BoolExpr.e RPAREN Statement.s
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_e = _symbols[offset + 3];
final BoolExpression e = (BoolExpression) _symbol_e.value;
final Symbol _symbol_s = _symbols[offset + 5];
final Statement s = (Statement) _symbol_s.value;
return new Symbol(new Statement.WhileStatement(e, s));
}
},
new Action() { // [19] Statement = PRINTF LPAREN DFORMAT COMMA IDENT.i RPAREN SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 5];
final String i = (String) _symbol_i.value;
return new Symbol(new Statement.PrintfStatement(i));
}
},
new Action() { // [20] Statement = SCANF LPAREN IFORMAT COMMA AMP IDENT.i RPAREN SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 6];
final String i = (String) _symbol_i.value;
return new Symbol(new Statement.ScanfStatement(i));
}
},
new Action() { // [21] Statement = LBRACKET StatementSequence.s RBRACKET
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_s = _symbols[offset + 2];
final StatementSequence s = (StatementSequence) _symbol_s.value;
return new Symbol(new Statement.CompStatement(s));
}
},
new Action() { // [22] BoolExpr = SimpleExpr.l Relation.rel SimpleExpr.r
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_l = _symbols[offset + 1];
final SimpleExpr l = (SimpleExpr) _symbol_l.value;
final Symbol _symbol_rel = _symbols[offset + 2];
final AtomicType rel = (AtomicType) _symbol_rel.value;
final Symbol _symbol_r = _symbols[offset + 3];
final SimpleExpr r = (SimpleExpr) _symbol_r.value;
return new Symbol(new BoolExpression(l, rel, r));
}
},
new Action() { // [23] Relation = EQ
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.EQ);
}
},
new Action() { // [24] Relation = NE
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.NE);
}
},
new Action() { // [25] Relation = LE
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.LE);
}
},
new Action() { // [26] Relation = GE
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.GE);
}
},
new Action() { // [27] Relation = LT
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.LT);
}
},
new Action() { // [28] Relation = GT
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.GT);
}
},
new Action() { // [29] SimpleExpr = Term.t
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 1];
final Term t = (Term) _symbol_t.value;
return new Symbol(new SimpleExpr.UnaryPlusExpr(t));
}
},
new Action() { // [30] SimpleExpr = PLUS Term.t
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 2];
final Term t = (Term) _symbol_t.value;
return new Symbol(new SimpleExpr.UnaryPlusExpr(t));
}
},
new Action() { // [31] SimpleExpr = MINUS Term.t
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 2];
final Term t = (Term) _symbol_t.value;
return new Symbol(new SimpleExpr.UnaryMinusExpr(t));
}
},
new Action() { // [32] SimpleExpr = SimpleExpr.s PLUS Term.t
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_s = _symbols[offset + 1];
final SimpleExpr s = (SimpleExpr) _symbol_s.value;
final Symbol _symbol_t = _symbols[offset + 3];
final Term t = (Term) _symbol_t.value;
return new Symbol(new SimpleExpr.PlusExpr(s, t));
}
},
new Action() { // [33] SimpleExpr = SimpleExpr.s MINUS Term.t
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_s = _symbols[offset + 1];
final SimpleExpr s = (SimpleExpr) _symbol_s.value;
final Symbol _symbol_t = _symbols[offset + 3];
final Term t = (Term) _symbol_t.value;
return new Symbol(new SimpleExpr.MinusExpr(s, t));
}
},
new Action() { // [34] Term = Factor.f
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_f = _symbols[offset + 1];
final Factor f = (Factor) _symbol_f.value;
return new Symbol(new Term.FactorTerm(f));
}
},
new Action() { // [35] Term = Term.t MULT Factor.f
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 1];
final Term t = (Term) _symbol_t.value;
final Symbol _symbol_f = _symbols[offset + 3];
final Factor f = (Factor) _symbol_f.value;
return new Symbol(new Term.MultTerm(t, f));
}
},
new Action() { // [36] Term = Term.t DIV Factor.f
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 1];
final Term t = (Term) _symbol_t.value;
final Symbol _symbol_f = _symbols[offset + 3];
final Factor f = (Factor) _symbol_f.value;
return new Symbol(new Term.DivTerm(t, f));
}
},
new Action() { // [37] Term = Term.t MOD Factor.f
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 1];
final Term t = (Term) _symbol_t.value;
final Symbol _symbol_f = _symbols[offset + 3];
final Factor f = (Factor) _symbol_f.value;
return new Symbol(new Term.ModTerm(t, f));
}
},
new Action() { // [38] Factor = IDENT.i
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 1];
final String i = (String) _symbol_i.value;
return new Symbol(new Factor.IdentFactor(i));
}
},
new Action() { // [39] Factor = NUMBER.n
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol n = _symbols[offset + 1];
return new Symbol(new Factor.NumberFactor(convert(n)));
}
},
new Action() { // [40] Factor = LPAREN SimpleExpr.s RPAREN
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_s = _symbols[offset + 2];
final SimpleExpr s = (SimpleExpr) _symbol_s.value;
return new Symbol(new Factor.CompExprFactor(s));
}
}
};
this.report = ErrorEvents.forC0();
}
protected Symbol invokeReduceAction(int rule_num, int offset) {
return actions[rule_num].reduce(_symbols, offset);
}
}
| tud-fop/j-Algo | src/main/java/org/jalgo/module/am0c0/parser/c0/GeneratedC0Parser.java | 7,179 | // [16] Statement = IF LPAREN BoolExpr.e RPAREN Statement.s | line_comment | nl | /*
* j-Algo - j-Algo is an algorithm visualization tool, especially useful for
* students and lecturers of computer science. It is written in Java and platform
* independent. j-Algo is developed with the help of Dresden University of
* Technology.
*
* Copyright (C) 2004-2010 j-Algo-Team, [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., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* WARNING: This is generated code. DO *NOT* MODIFY IT! */
package org.jalgo.module.am0c0.parser.c0;
import java.util.ArrayList;
import org.jalgo.module.am0c0.model.c0.ast.*;
import org.jalgo.module.am0c0.parser.ParserUtils;
import beaver.*;
import org.jalgo.module.am0c0.parser.ErrorEvents;
import org.jalgo.module.am0c0.model.c0.trans.AtomicTrans.AtomicType;
/**
* This class is a LALR parser generated by
* <a href="http://beaver.sourceforge.net">Beaver</a> v0.9.6.1
* from the grammar specification "c0-parser.g".
*/
public class GeneratedC0Parser extends Parser {
static public class Terminals {
static public final short EOF = 0;
static public final short IDENT = 1;
static public final short MINUS = 2;
static public final short PLUS = 3;
static public final short SEMICOLON = 4;
static public final short LPAREN = 5;
static public final short NUMBER = 6;
static public final short LBRACKET = 7;
static public final short SCANF = 8;
static public final short PRINTF = 9;
static public final short IF = 10;
static public final short WHILE = 11;
static public final short RPAREN = 12;
static public final short RETURN = 13;
static public final short EQ = 14;
static public final short NE = 15;
static public final short LE = 16;
static public final short GE = 17;
static public final short LT = 18;
static public final short GT = 19;
static public final short RBRACKET = 20;
static public final short MULT = 21;
static public final short DIV = 22;
static public final short MOD = 23;
static public final short COMMA = 24;
static public final short ELSE = 25;
static public final short INT = 26;
static public final short ASSIGN = 27;
static public final short IFORMAT = 28;
static public final short AMP = 29;
static public final short DFORMAT = 30;
static public final short INCLUDE = 31;
static public final short STDIO = 32;
static public final short MAIN = 33;
static public final short CONST = 34;
}
static final ParsingTables PARSING_TABLES = new ParsingTables(
"U9obbbjiL4K0Xl#pjrBPbW8LjYsrq7OBhQMW8Du0kNW1lA9o4PHI5E#9ngWFFXYZYI$6nCk" +
"3HatGX0TzyS6O#6vCr0TVC055MwsY8hG52wK5AkCtS#PiTxUx98tdpzz$vf$$pENCdZcLOg" +
"tc5mjbj51PtQ9wrMawzLZeUnpK75sc#UPdYuBiJTItXBvlZVlIZnO#ctJP#wbl2ttVcl2b7" +
"onyDkMost7#2NtVMk5BVHO#MscpvFhCSEZxrcb#lZyv77KmxkymzTFUTz0CNphiy9U5gfsU" +
"fdxA#mwgygLUXpyTBhY$fqol7lI#WsRwqY67Fomqr$tTJlsCzntKv4k$EHonq0AdPwYFUDz" +
"17Nvj$Gw$MwZJwOZfrsBlEsY9p$vgeMQrwWfjqEMsH7rMw7kS2xEQfrfpBeUJ#7lKeajqBs" +
"KFBOVBjCDcDLlNu9tG2Zsag$6lDISYQ3UqetOpwfNAu0rfbTlVBbrdXYBG0hNQjTWT7JA3k" +
"jxDSaWDPZ02EQWrkToW6T1QbnlK9ZCGWHpKkbnkm1mdTIbxFQ0RpF48MW$j6fhL2DlmZg6B" +
"pD$u6ysn27eKtgExzOZvLrjr7zvvxTG3seM$rvoFe1xui1dNOt8NtdW4QkDkB7zP9tVTgjj" +
"qk#xGdRhBd9smpTa8gidpRzHANQLsBLMDDbFVCSbD#$j79rmpciCOldIpIun5O8GnttzDNb" +
"$vlUgYxJ75bL3WrBxnAIrY7asgrWpkcAbP$5Aws8CvcbiccoZ8pY#HNU2ocKdP#XBPP9bik" +
"aIseansSOciocIp9RArPRA9AVJRK2BRKYRRCeLiiaGsdSjcBxAs5jxefDeuWMqfJIa$6#Hb" +
"ApY9ApaxfkDMyIj9S$PqvhbPt3Ix5$QRuNa5zDpCELH7QI8N8sV7IhbH0v#pSwtZ$i9H0ju" +
"oss9fS#5ywxYpEDTOa0lAvj85EPlAailavHBamcVTwXZbqkGwYjPHIph5RhVxTLWq5AqtHQ" +
"u19sNSHIxNHisDPKpKPd9NuJxa#GKhAkUglbosO6x5TzLEzQxS#ANRfSTViYUJuQmMhdYEO" +
"atIUhW1ReFFIW7lJ700zb9$2puFFwJ#7lecZ56U1wlXSlgxWAx5jsTm1rm3CtZiHc3xtefk" +
"GPz4xHWlmtVXf$0hF7kg7qQVG4$2xs4NFCXGTYxDAFCDLk0DknDP0QTcR3Qw2JP1sru95yA" +
"baFK4k#0os0vtmvMm6$R05#0pz67dUHI#2Z#6duVdVl0Y#ZJ4rmVmC$WDxAEDPn3mA8Dtg3" +
"UYNwDsd45erxKHVH#rOt5ly0hifFuSodFKQ$0ZodmNWdtmTVW6tXVeVlGxlqz7h1QJQvLN#" +
"xzNFxgpJExGH3dOxBst2pD1XzTktxxFwoUJ#mjwlExD6#E0ro#zVfkNh$BUIAdvJOMiSpHQ" +
"W#zx3rmzbJx8F$L$vp6vJtUryskju9kMWac#k06CSI8BnZmJdC#MISyKTyMW$KudtBSwIny" +
"JEWt6EPFZl551IROvnZpZZgruhKv3jhZpqZAk9Vy1gTSq70==");
public ErrorEvents getErrorEvents() {
return (ErrorEvents) report;
}
private int convert(final Symbol symbol) {
return ParserUtils.safeSymbolToInt(symbol, (ErrorEvents) report);
}
private final Action[] actions;
public GeneratedC0Parser() {
super(PARSING_TABLES);
actions = new Action[] {
new Action() { // [0] Program = INCLUDE STDIO INT MAIN LPAREN RPAREN Block.b
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_b = _symbols[offset + 7];
final Block b = (Block) _symbol_b.value;
return new Symbol(new Program(b));
}
},
new Action() { // [1] Block = LBRACKET Declaration.d StatementSequence.s RETURN SEMICOLON RBRACKET
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_d = _symbols[offset + 2];
final Declaration d = (Declaration) _symbol_d.value;
final Symbol _symbol_s = _symbols[offset + 3];
final StatementSequence s = (StatementSequence) _symbol_s.value;
return new Symbol(new Block(d, s));
}
},
new Action() { // [2] Block = LBRACKET Declaration.d RETURN SEMICOLON RBRACKET
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_d = _symbols[offset + 2];
final Declaration d = (Declaration) _symbol_d.value;
return new Symbol(new Block(d, null));
}
},
new Action() { // [3] StatementSequence = Statement.stat
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_stat = _symbols[offset + 1];
final Statement stat = (Statement) _symbol_stat.value;
return new Symbol(new StatementSequence(stat));
}
},
new Action() { // [4] StatementSequence = StatementSequence.seq Statement.stat
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_seq = _symbols[offset + 1];
final StatementSequence seq = (StatementSequence) _symbol_seq.value;
final Symbol _symbol_stat = _symbols[offset + 2];
final Statement stat = (Statement) _symbol_stat.value;
seq.addStatement(stat); return new Symbol(seq);
}
},
new Action() { // [5] Declaration =
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(new Declaration(null, null));
}
},
new Action() { // [6] Declaration = ConstDeclaration.constdecl SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_constdecl = _symbols[offset + 1];
final ConstDeclaration constdecl = (ConstDeclaration) _symbol_constdecl.value;
return new Symbol(new Declaration(constdecl, null));
}
},
new Action() { // [7] Declaration = VarDeclaration.vardecl SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_vardecl = _symbols[offset + 1];
final VarDeclaration vardecl = (VarDeclaration) _symbol_vardecl.value;
return new Symbol(new Declaration(null, vardecl));
}
},
new Action() { // [8] Declaration = ConstDeclaration.constdecl SEMICOLON VarDeclaration.vardecl SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_constdecl = _symbols[offset + 1];
final ConstDeclaration constdecl = (ConstDeclaration) _symbol_constdecl.value;
final Symbol _symbol_vardecl = _symbols[offset + 3];
final VarDeclaration vardecl = (VarDeclaration) _symbol_vardecl.value;
return new Symbol(new Declaration(constdecl, vardecl));
}
},
new Action() { // [9] ConstDeclaration = CONST IDENT.i ASSIGN NUMBER.n
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 2];
final String i = (String) _symbol_i.value;
final Symbol n = _symbols[offset + 4];
return new Symbol(new ConstDeclaration(new C0AST.ConstIdent(i, convert(n))));
}
},
new Action() { // [10] ConstDeclaration = CONST IDENT.i ASSIGN MINUS NUMBER.n
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 2];
final String i = (String) _symbol_i.value;
final Symbol n = _symbols[offset + 5];
return new Symbol(new ConstDeclaration(new C0AST.ConstIdent(i, -convert(n))));
}
},
new Action() { // [11] ConstDeclaration = ConstDeclaration.d COMMA IDENT.i ASSIGN NUMBER.n
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_d = _symbols[offset + 1];
final ConstDeclaration d = (ConstDeclaration) _symbol_d.value;
final Symbol _symbol_i = _symbols[offset + 3];
final String i = (String) _symbol_i.value;
final Symbol n = _symbols[offset + 5];
d.addConstant(new C0AST.ConstIdent(i, convert(n))); return new Symbol(d);
}
},
new Action() { // [12] ConstDeclaration = ConstDeclaration.d COMMA IDENT.i ASSIGN MINUS NUMBER.n
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_d = _symbols[offset + 1];
final ConstDeclaration d = (ConstDeclaration) _symbol_d.value;
final Symbol _symbol_i = _symbols[offset + 3];
final String i = (String) _symbol_i.value;
final Symbol n = _symbols[offset + 6];
d.addConstant(new C0AST.ConstIdent(i, -convert(n))); return new Symbol(d);
}
},
new Action() { // [13] VarDeclaration = INT IDENT.i
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 2];
final String i = (String) _symbol_i.value;
return new Symbol(new VarDeclaration(new C0AST.Ident(i)));
}
},
new Action() { // [14] VarDeclaration = VarDeclaration.d COMMA IDENT.i
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_d = _symbols[offset + 1];
final VarDeclaration d = (VarDeclaration) _symbol_d.value;
final Symbol _symbol_i = _symbols[offset + 3];
final String i = (String) _symbol_i.value;
d.addVariable(new C0AST.Ident(i)); return new Symbol(d);
}
},
new Action() { // [15] Statement = IDENT.i ASSIGN SimpleExpr.e SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 1];
final String i = (String) _symbol_i.value;
final Symbol _symbol_e = _symbols[offset + 3];
final SimpleExpr e = (SimpleExpr) _symbol_e.value;
return new Symbol(new Statement.AssignmentStatement(i, e));
}
},
new Action() { // [16] Statement<SUF>
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_e = _symbols[offset + 3];
final BoolExpression e = (BoolExpression) _symbol_e.value;
final Symbol _symbol_s = _symbols[offset + 5];
final Statement s = (Statement) _symbol_s.value;
return new Symbol(new Statement.IfStatement(e, s));
}
},
new Action() { // [17] Statement = IF LPAREN BoolExpr.e RPAREN Statement.s1 ELSE Statement.s2
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_e = _symbols[offset + 3];
final BoolExpression e = (BoolExpression) _symbol_e.value;
final Symbol _symbol_s1 = _symbols[offset + 5];
final Statement s1 = (Statement) _symbol_s1.value;
final Symbol _symbol_s2 = _symbols[offset + 7];
final Statement s2 = (Statement) _symbol_s2.value;
return new Symbol(new Statement.IfElseStatement(e, s1, s2));
}
},
new Action() { // [18] Statement = WHILE LPAREN BoolExpr.e RPAREN Statement.s
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_e = _symbols[offset + 3];
final BoolExpression e = (BoolExpression) _symbol_e.value;
final Symbol _symbol_s = _symbols[offset + 5];
final Statement s = (Statement) _symbol_s.value;
return new Symbol(new Statement.WhileStatement(e, s));
}
},
new Action() { // [19] Statement = PRINTF LPAREN DFORMAT COMMA IDENT.i RPAREN SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 5];
final String i = (String) _symbol_i.value;
return new Symbol(new Statement.PrintfStatement(i));
}
},
new Action() { // [20] Statement = SCANF LPAREN IFORMAT COMMA AMP IDENT.i RPAREN SEMICOLON
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 6];
final String i = (String) _symbol_i.value;
return new Symbol(new Statement.ScanfStatement(i));
}
},
new Action() { // [21] Statement = LBRACKET StatementSequence.s RBRACKET
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_s = _symbols[offset + 2];
final StatementSequence s = (StatementSequence) _symbol_s.value;
return new Symbol(new Statement.CompStatement(s));
}
},
new Action() { // [22] BoolExpr = SimpleExpr.l Relation.rel SimpleExpr.r
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_l = _symbols[offset + 1];
final SimpleExpr l = (SimpleExpr) _symbol_l.value;
final Symbol _symbol_rel = _symbols[offset + 2];
final AtomicType rel = (AtomicType) _symbol_rel.value;
final Symbol _symbol_r = _symbols[offset + 3];
final SimpleExpr r = (SimpleExpr) _symbol_r.value;
return new Symbol(new BoolExpression(l, rel, r));
}
},
new Action() { // [23] Relation = EQ
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.EQ);
}
},
new Action() { // [24] Relation = NE
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.NE);
}
},
new Action() { // [25] Relation = LE
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.LE);
}
},
new Action() { // [26] Relation = GE
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.GE);
}
},
new Action() { // [27] Relation = LT
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.LT);
}
},
new Action() { // [28] Relation = GT
public Symbol reduce(Symbol[] _symbols, int offset) {
return new Symbol(AtomicType.GT);
}
},
new Action() { // [29] SimpleExpr = Term.t
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 1];
final Term t = (Term) _symbol_t.value;
return new Symbol(new SimpleExpr.UnaryPlusExpr(t));
}
},
new Action() { // [30] SimpleExpr = PLUS Term.t
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 2];
final Term t = (Term) _symbol_t.value;
return new Symbol(new SimpleExpr.UnaryPlusExpr(t));
}
},
new Action() { // [31] SimpleExpr = MINUS Term.t
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 2];
final Term t = (Term) _symbol_t.value;
return new Symbol(new SimpleExpr.UnaryMinusExpr(t));
}
},
new Action() { // [32] SimpleExpr = SimpleExpr.s PLUS Term.t
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_s = _symbols[offset + 1];
final SimpleExpr s = (SimpleExpr) _symbol_s.value;
final Symbol _symbol_t = _symbols[offset + 3];
final Term t = (Term) _symbol_t.value;
return new Symbol(new SimpleExpr.PlusExpr(s, t));
}
},
new Action() { // [33] SimpleExpr = SimpleExpr.s MINUS Term.t
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_s = _symbols[offset + 1];
final SimpleExpr s = (SimpleExpr) _symbol_s.value;
final Symbol _symbol_t = _symbols[offset + 3];
final Term t = (Term) _symbol_t.value;
return new Symbol(new SimpleExpr.MinusExpr(s, t));
}
},
new Action() { // [34] Term = Factor.f
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_f = _symbols[offset + 1];
final Factor f = (Factor) _symbol_f.value;
return new Symbol(new Term.FactorTerm(f));
}
},
new Action() { // [35] Term = Term.t MULT Factor.f
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 1];
final Term t = (Term) _symbol_t.value;
final Symbol _symbol_f = _symbols[offset + 3];
final Factor f = (Factor) _symbol_f.value;
return new Symbol(new Term.MultTerm(t, f));
}
},
new Action() { // [36] Term = Term.t DIV Factor.f
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 1];
final Term t = (Term) _symbol_t.value;
final Symbol _symbol_f = _symbols[offset + 3];
final Factor f = (Factor) _symbol_f.value;
return new Symbol(new Term.DivTerm(t, f));
}
},
new Action() { // [37] Term = Term.t MOD Factor.f
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_t = _symbols[offset + 1];
final Term t = (Term) _symbol_t.value;
final Symbol _symbol_f = _symbols[offset + 3];
final Factor f = (Factor) _symbol_f.value;
return new Symbol(new Term.ModTerm(t, f));
}
},
new Action() { // [38] Factor = IDENT.i
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_i = _symbols[offset + 1];
final String i = (String) _symbol_i.value;
return new Symbol(new Factor.IdentFactor(i));
}
},
new Action() { // [39] Factor = NUMBER.n
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol n = _symbols[offset + 1];
return new Symbol(new Factor.NumberFactor(convert(n)));
}
},
new Action() { // [40] Factor = LPAREN SimpleExpr.s RPAREN
public Symbol reduce(Symbol[] _symbols, int offset) {
final Symbol _symbol_s = _symbols[offset + 2];
final SimpleExpr s = (SimpleExpr) _symbol_s.value;
return new Symbol(new Factor.CompExprFactor(s));
}
}
};
this.report = ErrorEvents.forC0();
}
protected Symbol invokeReduceAction(int rule_num, int offset) {
return actions[rule_num].reduce(_symbols, offset);
}
}
|
131121_1 |
import java.io.File;
import java.util.ArrayList;
import javax.xml.bind.JAXBException;
import org.citygml4j.CityGMLContext;
import org.citygml4j.builder.jaxb.JAXBBuilder;
import org.citygml4j.model.citygml.CityGML;
import org.citygml4j.model.citygml.CityGMLClass;
import org.citygml4j.model.citygml.building.Building;
import org.citygml4j.model.citygml.core.AbstractCityObject;
import org.citygml4j.model.citygml.core.CityModel;
import org.citygml4j.model.citygml.core.CityObjectMember;
import org.citygml4j.xml.io.CityGMLInputFactory;
import org.citygml4j.xml.io.reader.CityGMLReadException;
import org.citygml4j.xml.io.reader.CityGMLReader;
/**
* Responsible for reading CityGML file and producing a building list
* @author kooijmanj1
*
*/
public class VInputFile {
private File file = null;
private CityGMLReader reader = null;
public VInputFile(File file){
this.file = file;
}
public ArrayList<Building> readAllBuildings() throws VInputOutputException {
ArrayList<Building> buildings = new ArrayList<Building>();
CityGMLContext ctx = new CityGMLContext();
JAXBBuilder builder;
try {
builder = ctx.createJAXBBuilder();
}
catch (JAXBException e) {
throw new VInputOutputException("JAXB problem" + e.getMessage());
}
try {
CityGMLInputFactory in = builder.createCityGMLInputFactory();
CityGMLReader reader = in.createCityGMLReader(file);
CityGML citygml = reader.nextFeature();
CityModel cityModel = (CityModel)citygml;
//int aantalGebouwen = 0;
for(CityObjectMember cityObjectMember : cityModel.getCityObjectMember()){
AbstractCityObject cityObject = cityObjectMember.getCityObject();
if(cityObject.getCityGMLClass() == CityGMLClass.BUILDING){
Building building = (Building)cityObject;
buildings.add(building);
//aantalGebouwen++;
}
}
}
catch (CityGMLReadException e) {
throw new VInputOutputException("CityGMLReadException");
}
finally {
if(reader != null){
try {reader.close();}
catch (CityGMLReadException e){
throw new VInputOutputException("Closing problem" + e.getMessage());
}
}
}
return buildings;
}
}
| tudelft3d/citygml2poly | VInputFile.java | 773 | //int aantalGebouwen = 0;
| line_comment | nl |
import java.io.File;
import java.util.ArrayList;
import javax.xml.bind.JAXBException;
import org.citygml4j.CityGMLContext;
import org.citygml4j.builder.jaxb.JAXBBuilder;
import org.citygml4j.model.citygml.CityGML;
import org.citygml4j.model.citygml.CityGMLClass;
import org.citygml4j.model.citygml.building.Building;
import org.citygml4j.model.citygml.core.AbstractCityObject;
import org.citygml4j.model.citygml.core.CityModel;
import org.citygml4j.model.citygml.core.CityObjectMember;
import org.citygml4j.xml.io.CityGMLInputFactory;
import org.citygml4j.xml.io.reader.CityGMLReadException;
import org.citygml4j.xml.io.reader.CityGMLReader;
/**
* Responsible for reading CityGML file and producing a building list
* @author kooijmanj1
*
*/
public class VInputFile {
private File file = null;
private CityGMLReader reader = null;
public VInputFile(File file){
this.file = file;
}
public ArrayList<Building> readAllBuildings() throws VInputOutputException {
ArrayList<Building> buildings = new ArrayList<Building>();
CityGMLContext ctx = new CityGMLContext();
JAXBBuilder builder;
try {
builder = ctx.createJAXBBuilder();
}
catch (JAXBException e) {
throw new VInputOutputException("JAXB problem" + e.getMessage());
}
try {
CityGMLInputFactory in = builder.createCityGMLInputFactory();
CityGMLReader reader = in.createCityGMLReader(file);
CityGML citygml = reader.nextFeature();
CityModel cityModel = (CityModel)citygml;
//int aantalGebouwen<SUF>
for(CityObjectMember cityObjectMember : cityModel.getCityObjectMember()){
AbstractCityObject cityObject = cityObjectMember.getCityObject();
if(cityObject.getCityGMLClass() == CityGMLClass.BUILDING){
Building building = (Building)cityObject;
buildings.add(building);
//aantalGebouwen++;
}
}
}
catch (CityGMLReadException e) {
throw new VInputOutputException("CityGMLReadException");
}
finally {
if(reader != null){
try {reader.close();}
catch (CityGMLReadException e){
throw new VInputOutputException("Closing problem" + e.getMessage());
}
}
}
return buildings;
}
}
|
49000_10 | package algorithms.honors;
import model.HexagonalMap;
import model.HexagonalMap.BarycentricCoordinate;
import model.Network.Vertex;
public class TreeToHexagonGrid {
public static HexagonalMap computeHexagonGrid(Tree dual) {
HexagonalMap h = new HexagonalMap();
addTree(h, dual, null, null);
return h;
}
private static void addTree(HexagonalMap h, Tree t, Tree leftParentTree, Tree topParentTree) {
if (t.face == null) {
return;
}
// find the neighbouring trees
Tree bottomSubTree = null, rightSubTree = null;
if (t.subTree1 != null && t.xCoordinate == t.subTree1.xCoordinate) {
bottomSubTree = t.subTree1;
rightSubTree = t.subTree2;
}
if (t.subTree2 != null && t.xCoordinate == t.subTree2.xCoordinate) {
if (bottomSubTree != null) {
throw new RuntimeException("Something is really wrong with the hv-drawing: "
+ "both subtrees are at the same x-coordinate as their parent node:\n"
+ t.toString());
}
bottomSubTree = t.subTree2;
rightSubTree = t.subTree1;
}
/*// color type-1 vertices
if (bottomSubTree != null && rightSubTree != null) {
Vertex bottomRight = findCommonVertex(bottomSubTree, rightSubTree);
setVertex(h, 3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate - 1, bottomRight);
}
if (topParentTree != null && rightSubTree != null) {
Vertex topRight = findCommonVertex(topParentTree, rightSubTree);
setVertex(h, 3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate, topRight);
}
if (bottomSubTree != null && leftParentTree != null) {
Vertex bottomLeft = findCommonVertex(bottomSubTree, leftParentTree);
setVertex(h, 3 * t.xCoordinate, 0, 3 * -t.yCoordinate - 1, bottomLeft);
}
if (topParentTree != null && leftParentTree != null) {
Vertex topLeft = findCommonVertex(topParentTree, leftParentTree);
setVertex(h, 3 * t.xCoordinate, 0, 3 * -t.yCoordinate, topLeft);
}*/
tryToColor(h, t, topParentTree, rightSubTree, bottomSubTree, leftParentTree);
// augment the hexagons of this tree
// that is: if we can infer one of the colors, fill that one in
// note: this is now commented out for debugging... it shouldn't hurt to
// augment, but it should also work without it
//augmentColoring(h, t);
// handle subtrees
if (t.subTree1 != null) {
addSubtree(h, t, t.subTree1);
}
if (t.subTree2 != null) {
addSubtree(h, t, t.subTree2);
}
tryToColor(h, t, topParentTree, rightSubTree, bottomSubTree, leftParentTree);
//augmentColoring(h, t);
}
private static void tryToColor(HexagonalMap h, Tree t, Tree topParentTree,
Tree rightSubTree, Tree bottomSubTree, Tree leftParentTree) {
// je mag alleen spieken bij je ouders :D
int caseId =
(topParentTree != null ? 0b1000 : 0b0000)
+ (rightSubTree != null ? 0b0100 : 0b0000)
+ (bottomSubTree != null ? 0b0010 : 0b0000)
+ (leftParentTree != null ? 0b0001 : 0b0000);
switch (caseId) {
case 0b0000:
// lonely node
setTLVertex(h, t, t.face.vertices.get(0));
setTRVertex(h, t, t.face.vertices.get(0));
setBLVertex(h, t, t.face.vertices.get(1));
setBRVertex(h, t, t.face.vertices.get(2));
break;
case 0b0001:
// only left
setTLVertex(h, t, getTRVertex(h, leftParentTree));
setTRVertex(h, t, findOtherVertex(t, leftParentTree));
setBLVertex(h, t, getBRVertex(h, leftParentTree));
setBRVertex(h, t, getTRVertex(h, t));
if (getTLVertex(h, t) == null && getBLVertex(h, t) == null) {
setTLVertex(h, t, findCommonVertex(t, leftParentTree));
}
augmentColoring(h, t);
break;
case 0b0010:
// only bottom
setTLVertex(h, t, findOtherVertex(t, bottomSubTree));
setTRVertex(h, t, getTLVertex(h, t));
setBLVertex(h, t, getTLVertex(h, bottomSubTree)); // spiek (maar dat is onvermijdelijk)
setBRVertex(h, t, getTRVertex(h, bottomSubTree)); // spiek (maar dat is onvermijdelijk)
break;
case 0b0011:
// bottom and left
setTLVertex(h, t, findCommonVertexExcept(t, leftParentTree, getBLVertex(h, t)));
setTRVertex(h, t, getTLVertex(h, t));
setBLVertex(h, t, findCommonVertex(bottomSubTree, leftParentTree));
setBRVertex(h, t, findCommonVertexExcept(t, bottomSubTree, getBLVertex(h, t)));
break;
case 0b0100:
// only right
setTLVertex(h, t, findOtherVertex(t, rightSubTree));
setTRVertex(h, t, getTLVertex(h, rightSubTree)); // spiek (maar dat is onvermijdelijk)
setBLVertex(h, t, getTLVertex(h, t));
setBRVertex(h, t, getBLVertex(h, rightSubTree)); // spiek (maar dat is onvermijdelijk)
break;
case 0b0101:
// right and left
setTLVertex(h, t, getTRVertex(h, leftParentTree));
setBLVertex(h, t, getBRVertex(h, leftParentTree));
if (getTLVertex(h, t) == findCommonVertex(leftParentTree, rightSubTree)) {
setTRVertex(h, t, getTLVertex(h, t));
setBRVertex(h, t, findCommonVertexExcept(t, rightSubTree, getTRVertex(h, t)));
} else {
setBRVertex(h, t, getBLVertex(h, t));
setTRVertex(h, t, findCommonVertexExcept(t, rightSubTree, getBRVertex(h, t)));
}
break;
case 0b0110:
// right and bottom
setBRVertex(h, t, findCommonVertex(bottomSubTree, rightSubTree));
setTRVertex(h, t, findCommonVertexExcept(t, rightSubTree, getBRVertex(h, t)));
setTLVertex(h, t, getTRVertex(h, t));
setBLVertex(h, t, findCommonVertexExcept(t, bottomSubTree, getBRVertex(h, t)));
break;
case 0b0111:
// right, bottom and left
setTLVertex(h, t, findCommonVertex(leftParentTree, rightSubTree));
setTRVertex(h, t, findCommonVertex(leftParentTree, rightSubTree));
setBLVertex(h, t, findCommonVertex(leftParentTree, bottomSubTree));
setBRVertex(h, t, findCommonVertex(rightSubTree, bottomSubTree));
break;
case 0b1000:
// only top
setTLVertex(h, t, getBLVertex(h, topParentTree));
setTRVertex(h, t, getBRVertex(h, topParentTree));
setBLVertex(h, t, findOtherVertex(t, topParentTree));
setBRVertex(h, t, getBLVertex(h, t));
if (getTLVertex(h, t) == null && getTRVertex(h, t) == null) {
setTLVertex(h, t, findCommonVertex(t, topParentTree));
}
augmentColoring(h, t);
break;
case 0b1001:
// top and left
throw new RuntimeException("OH NEEEEE");
case 0b1010:
// top and bottom
setTLVertex(h, t, getBLVertex(h, topParentTree));
setTRVertex(h, t, getBRVertex(h, topParentTree));
setBLVertex(h, t, getTLVertex(h, bottomSubTree));
setBRVertex(h, t, getTRVertex(h, bottomSubTree));
if (getTLVertex(h, t) == findCommonVertex(topParentTree, bottomSubTree)
|| getBLVertex(h, t) == findCommonVertex(topParentTree, bottomSubTree)) {
setTLVertex(h, t, findCommonVertex(topParentTree, bottomSubTree));
setTRVertex(h, t, findCommonVertexExcept(t, topParentTree, getTLVertex(h, t)));
setBLVertex(h, t, getTLVertex(h, t));
setBRVertex(h, t, findCommonVertexExcept(t, bottomSubTree, getBLVertex(h, t)));
} else {
setTRVertex(h, t, findCommonVertex(topParentTree, bottomSubTree));
setTLVertex(h, t, findCommonVertexExcept(t, topParentTree, getTRVertex(h, t)));
setBRVertex(h, t, getTRVertex(h, t));
setBLVertex(h, t, findCommonVertexExcept(t, bottomSubTree, getBRVertex(h, t)));
}
break;
case 0b1011:
// top, bottom and left
throw new RuntimeException("OEIIIII");
case 0b1100:
// top and right
setTRVertex(h, t, findCommonVertex(topParentTree, rightSubTree));
setTLVertex(h, t, findCommonVertexExcept(t, topParentTree, getTRVertex(h, t)));
setBRVertex(h, t, findCommonVertexExcept(t, rightSubTree, getTRVertex(h, t)));
setBLVertex(h, t, getBRVertex(h, t));
break;
case 0b1101:
// top, right and left
throw new RuntimeException("STOPPPP");
case 0b1110:
// top, right and bottom
setTLVertex(h, t, findCommonVertex(topParentTree, bottomSubTree));
setTRVertex(h, t, findCommonVertex(topParentTree, rightSubTree));
setBLVertex(h, t, findCommonVertex(topParentTree, bottomSubTree));
setBRVertex(h, t, findCommonVertex(rightSubTree, bottomSubTree));
break;
case 0b1111:
// everything
throw new RuntimeException("OEPSSSS");
}
}
private static Vertex both(Vertex v1, Vertex v2) {
if (v1 == null && v2 == null) {
return null;
}
if (v1 == null && v2 != null) {
return v2;
}
if (v2 != null && v1 != v2) {
throw new RuntimeException("HELP HELP");
}
return v1;
}
/**
* Sets the vertex for the TL hexagon of the given tree.
*/
private static void setTLVertex(HexagonalMap h, Tree t, Vertex v) {
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, 3 * -t.yCoordinate), v);
}
/**
* Gets the vertex for the TL hexagon of the given tree.
*/
private static Vertex getTLVertex(HexagonalMap h, Tree t) {
return h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, 3 * -t.yCoordinate));
}
/**
* Sets the vertex for the TR hexagon of the given tree.
*/
private static void setTRVertex(HexagonalMap h, Tree t, Vertex v) {
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate), v);
}
/**
* Gets the vertex for the TR hexagon of the given tree.
*/
private static Vertex getTRVertex(HexagonalMap h, Tree t) {
return h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate));
}
/**
* Sets the vertex for the BL hexagon of the given tree.
*/
private static void setBLVertex(HexagonalMap h, Tree t, Vertex v) {
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, 3 * -t.yCoordinate - 1), v);
}
/**
* Gets the vertex for the BL hexagon of the given tree.
*/
private static Vertex getBLVertex(HexagonalMap h, Tree t) {
return h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, 3 * -t.yCoordinate - 1));
}
/**
* Sets the vertex for the BR hexagon of the given tree.
*/
private static void setBRVertex(HexagonalMap h, Tree t, Vertex v) {
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate - 1), v);
}
/**
* Gets the vertex for the BR hexagon of the given tree.
*/
private static Vertex getBRVertex(HexagonalMap h, Tree t) {
return h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate - 1));
}
/**
* Finds a vertex (color) that is shared by the faces of the given trees.
*
* @param t1 The first tree.
* @param t2 The second tree.
* @return A vertex <code>v</code> with <pre>
* t1.face.vertices.contains(v) && t2.face.vertices.contains(v)
* </pre> If one doesn't exist, <code>null</code> is returned.
*/
private static Vertex findCommonVertex(Tree t1, Tree t2) {
return findCommonVertexExcept(t1, t2, null);
}
/**
* Finds a vertex (color) that is shared by the faces of the given trees.
* Ignores the vertex given.
*
* @param t1 The first tree.
* @param t2 The second tree.
* @param except The vertex to ignore.
* @return A vertex <code>v != except</code> with <pre>
* t1.face.vertices.contains(v) && t2.face.vertices.contains(v)
* </pre> If one doesn't exist, <code>null</code> is returned.
*/
private static Vertex findCommonVertexExcept(Tree t1, Tree t2, Vertex except) {
if (t2.face.vertices.get(0) != except
&& t1.face.vertices.contains(t2.face.vertices.get(0))) {
return t2.face.vertices.get(0);
}
if (t2.face.vertices.get(1) != except
&& t1.face.vertices.contains(t2.face.vertices.get(1))) {
return t2.face.vertices.get(1);
}
if (t2.face.vertices.get(2) != except
&& t1.face.vertices.contains(t2.face.vertices.get(2))) {
return t2.face.vertices.get(2);
}
return null;
}
/**
* Finds a vertex (color) that is in the face of one tree, and not in the
* other.
*
* @param t1 The first tree.
* @param t2 The second tree.
* @return A vertex <code>v</code> with <pre>
* t1.face.vertices.contains(v) && !t2.face.vertices.contains(v)
* </pre> If one doesn't exist, <code>null</code> is returned.
*/
private static Vertex findOtherVertex(Tree t1, Tree t2) {
if (!t2.face.vertices.contains(t1.face.vertices.get(0))) {
return t1.face.vertices.get(0);
}
if (!t2.face.vertices.contains(t1.face.vertices.get(1))) {
return t1.face.vertices.get(1);
}
if (!t2.face.vertices.contains(t1.face.vertices.get(2))) {
return t1.face.vertices.get(2);
}
return null;
}
private static void augmentColoring(HexagonalMap h, Tree t) {
Vertex[] vertices = new Vertex[]{
getTLVertex(h, t), getTRVertex(h, t), getBLVertex(h, t), getBRVertex(h, t)
};
Vertex first = null;
Vertex second = null;
Vertex third = null;
int numNulls = 0;
for (Vertex v : vertices) {
if (v == null) {
numNulls++;
continue;
}
if (first == null) {
first = v;
} else if (first != v) {
if (second == null) {
second = v;
} else if (second != v) {
third = v;
}
}
}
// only continue if we have exactly two colors and 1 unknown
if (numNulls != 1 || first == null || second == null || third != null) {
return;
}
for (Vertex v : t.face.vertices) {
if (v != first && v != second) {
third = v;
if (v == null) {
throw new StackOverflowError("WHAA");
}
break;
}
}
if (getTLVertex(h, t) == null) {
setTLVertex(h, t, third);
}
if (getTRVertex(h, t) == null) {
setTRVertex(h, t, third);
}
if (getBLVertex(h, t) == null) {
setBLVertex(h, t, third);
}
if (getBRVertex(h, t) == null) {
setBRVertex(h, t, third);
}
}
private static void addSubtree(HexagonalMap h, Tree origin, Tree t) {
// the edge to the subtree
if (origin.xCoordinate == t.xCoordinate) {
// the actual subtree: recursive call to addTree()
addTree(h, t, null, origin);
// it is a vertical edge
for (int z = -3 * t.yCoordinate + 1; z <= -3 * origin.yCoordinate - 2; z++) {
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, z),
h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, z - 1)));
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, z),
h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, z - 1)));
}
} else {
// the actual subtree: recursive call to addTree()
addTree(h, t, origin, null);
// it is a horizontal edge
for (int x = 3 * t.xCoordinate - 1; x >= 3 * origin.xCoordinate + 2; x--) {
h.setVertex(new BarycentricCoordinate(x, 0, -3 * t.yCoordinate),
h.getVertex(new BarycentricCoordinate(x + 1, 0, -3 * t.yCoordinate)));
h.setVertex(new BarycentricCoordinate(x, 0, -3 * t.yCoordinate - 1),
h.getVertex(new BarycentricCoordinate(x + 1, 0, -3 * t.yCoordinate - 1)));
}
}
}
}
| tue-alga/Gridmap | mosaic-maps/src/algorithms/honors/TreeToHexagonGrid.java | 5,584 | // spiek (maar dat is onvermijdelijk) | line_comment | nl | package algorithms.honors;
import model.HexagonalMap;
import model.HexagonalMap.BarycentricCoordinate;
import model.Network.Vertex;
public class TreeToHexagonGrid {
public static HexagonalMap computeHexagonGrid(Tree dual) {
HexagonalMap h = new HexagonalMap();
addTree(h, dual, null, null);
return h;
}
private static void addTree(HexagonalMap h, Tree t, Tree leftParentTree, Tree topParentTree) {
if (t.face == null) {
return;
}
// find the neighbouring trees
Tree bottomSubTree = null, rightSubTree = null;
if (t.subTree1 != null && t.xCoordinate == t.subTree1.xCoordinate) {
bottomSubTree = t.subTree1;
rightSubTree = t.subTree2;
}
if (t.subTree2 != null && t.xCoordinate == t.subTree2.xCoordinate) {
if (bottomSubTree != null) {
throw new RuntimeException("Something is really wrong with the hv-drawing: "
+ "both subtrees are at the same x-coordinate as their parent node:\n"
+ t.toString());
}
bottomSubTree = t.subTree2;
rightSubTree = t.subTree1;
}
/*// color type-1 vertices
if (bottomSubTree != null && rightSubTree != null) {
Vertex bottomRight = findCommonVertex(bottomSubTree, rightSubTree);
setVertex(h, 3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate - 1, bottomRight);
}
if (topParentTree != null && rightSubTree != null) {
Vertex topRight = findCommonVertex(topParentTree, rightSubTree);
setVertex(h, 3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate, topRight);
}
if (bottomSubTree != null && leftParentTree != null) {
Vertex bottomLeft = findCommonVertex(bottomSubTree, leftParentTree);
setVertex(h, 3 * t.xCoordinate, 0, 3 * -t.yCoordinate - 1, bottomLeft);
}
if (topParentTree != null && leftParentTree != null) {
Vertex topLeft = findCommonVertex(topParentTree, leftParentTree);
setVertex(h, 3 * t.xCoordinate, 0, 3 * -t.yCoordinate, topLeft);
}*/
tryToColor(h, t, topParentTree, rightSubTree, bottomSubTree, leftParentTree);
// augment the hexagons of this tree
// that is: if we can infer one of the colors, fill that one in
// note: this is now commented out for debugging... it shouldn't hurt to
// augment, but it should also work without it
//augmentColoring(h, t);
// handle subtrees
if (t.subTree1 != null) {
addSubtree(h, t, t.subTree1);
}
if (t.subTree2 != null) {
addSubtree(h, t, t.subTree2);
}
tryToColor(h, t, topParentTree, rightSubTree, bottomSubTree, leftParentTree);
//augmentColoring(h, t);
}
private static void tryToColor(HexagonalMap h, Tree t, Tree topParentTree,
Tree rightSubTree, Tree bottomSubTree, Tree leftParentTree) {
// je mag alleen spieken bij je ouders :D
int caseId =
(topParentTree != null ? 0b1000 : 0b0000)
+ (rightSubTree != null ? 0b0100 : 0b0000)
+ (bottomSubTree != null ? 0b0010 : 0b0000)
+ (leftParentTree != null ? 0b0001 : 0b0000);
switch (caseId) {
case 0b0000:
// lonely node
setTLVertex(h, t, t.face.vertices.get(0));
setTRVertex(h, t, t.face.vertices.get(0));
setBLVertex(h, t, t.face.vertices.get(1));
setBRVertex(h, t, t.face.vertices.get(2));
break;
case 0b0001:
// only left
setTLVertex(h, t, getTRVertex(h, leftParentTree));
setTRVertex(h, t, findOtherVertex(t, leftParentTree));
setBLVertex(h, t, getBRVertex(h, leftParentTree));
setBRVertex(h, t, getTRVertex(h, t));
if (getTLVertex(h, t) == null && getBLVertex(h, t) == null) {
setTLVertex(h, t, findCommonVertex(t, leftParentTree));
}
augmentColoring(h, t);
break;
case 0b0010:
// only bottom
setTLVertex(h, t, findOtherVertex(t, bottomSubTree));
setTRVertex(h, t, getTLVertex(h, t));
setBLVertex(h, t, getTLVertex(h, bottomSubTree)); // spiek (maar dat is onvermijdelijk)
setBRVertex(h, t, getTRVertex(h, bottomSubTree)); // spiek (maar dat is onvermijdelijk)
break;
case 0b0011:
// bottom and left
setTLVertex(h, t, findCommonVertexExcept(t, leftParentTree, getBLVertex(h, t)));
setTRVertex(h, t, getTLVertex(h, t));
setBLVertex(h, t, findCommonVertex(bottomSubTree, leftParentTree));
setBRVertex(h, t, findCommonVertexExcept(t, bottomSubTree, getBLVertex(h, t)));
break;
case 0b0100:
// only right
setTLVertex(h, t, findOtherVertex(t, rightSubTree));
setTRVertex(h, t, getTLVertex(h, rightSubTree)); // spiek (maar<SUF>
setBLVertex(h, t, getTLVertex(h, t));
setBRVertex(h, t, getBLVertex(h, rightSubTree)); // spiek (maar dat is onvermijdelijk)
break;
case 0b0101:
// right and left
setTLVertex(h, t, getTRVertex(h, leftParentTree));
setBLVertex(h, t, getBRVertex(h, leftParentTree));
if (getTLVertex(h, t) == findCommonVertex(leftParentTree, rightSubTree)) {
setTRVertex(h, t, getTLVertex(h, t));
setBRVertex(h, t, findCommonVertexExcept(t, rightSubTree, getTRVertex(h, t)));
} else {
setBRVertex(h, t, getBLVertex(h, t));
setTRVertex(h, t, findCommonVertexExcept(t, rightSubTree, getBRVertex(h, t)));
}
break;
case 0b0110:
// right and bottom
setBRVertex(h, t, findCommonVertex(bottomSubTree, rightSubTree));
setTRVertex(h, t, findCommonVertexExcept(t, rightSubTree, getBRVertex(h, t)));
setTLVertex(h, t, getTRVertex(h, t));
setBLVertex(h, t, findCommonVertexExcept(t, bottomSubTree, getBRVertex(h, t)));
break;
case 0b0111:
// right, bottom and left
setTLVertex(h, t, findCommonVertex(leftParentTree, rightSubTree));
setTRVertex(h, t, findCommonVertex(leftParentTree, rightSubTree));
setBLVertex(h, t, findCommonVertex(leftParentTree, bottomSubTree));
setBRVertex(h, t, findCommonVertex(rightSubTree, bottomSubTree));
break;
case 0b1000:
// only top
setTLVertex(h, t, getBLVertex(h, topParentTree));
setTRVertex(h, t, getBRVertex(h, topParentTree));
setBLVertex(h, t, findOtherVertex(t, topParentTree));
setBRVertex(h, t, getBLVertex(h, t));
if (getTLVertex(h, t) == null && getTRVertex(h, t) == null) {
setTLVertex(h, t, findCommonVertex(t, topParentTree));
}
augmentColoring(h, t);
break;
case 0b1001:
// top and left
throw new RuntimeException("OH NEEEEE");
case 0b1010:
// top and bottom
setTLVertex(h, t, getBLVertex(h, topParentTree));
setTRVertex(h, t, getBRVertex(h, topParentTree));
setBLVertex(h, t, getTLVertex(h, bottomSubTree));
setBRVertex(h, t, getTRVertex(h, bottomSubTree));
if (getTLVertex(h, t) == findCommonVertex(topParentTree, bottomSubTree)
|| getBLVertex(h, t) == findCommonVertex(topParentTree, bottomSubTree)) {
setTLVertex(h, t, findCommonVertex(topParentTree, bottomSubTree));
setTRVertex(h, t, findCommonVertexExcept(t, topParentTree, getTLVertex(h, t)));
setBLVertex(h, t, getTLVertex(h, t));
setBRVertex(h, t, findCommonVertexExcept(t, bottomSubTree, getBLVertex(h, t)));
} else {
setTRVertex(h, t, findCommonVertex(topParentTree, bottomSubTree));
setTLVertex(h, t, findCommonVertexExcept(t, topParentTree, getTRVertex(h, t)));
setBRVertex(h, t, getTRVertex(h, t));
setBLVertex(h, t, findCommonVertexExcept(t, bottomSubTree, getBRVertex(h, t)));
}
break;
case 0b1011:
// top, bottom and left
throw new RuntimeException("OEIIIII");
case 0b1100:
// top and right
setTRVertex(h, t, findCommonVertex(topParentTree, rightSubTree));
setTLVertex(h, t, findCommonVertexExcept(t, topParentTree, getTRVertex(h, t)));
setBRVertex(h, t, findCommonVertexExcept(t, rightSubTree, getTRVertex(h, t)));
setBLVertex(h, t, getBRVertex(h, t));
break;
case 0b1101:
// top, right and left
throw new RuntimeException("STOPPPP");
case 0b1110:
// top, right and bottom
setTLVertex(h, t, findCommonVertex(topParentTree, bottomSubTree));
setTRVertex(h, t, findCommonVertex(topParentTree, rightSubTree));
setBLVertex(h, t, findCommonVertex(topParentTree, bottomSubTree));
setBRVertex(h, t, findCommonVertex(rightSubTree, bottomSubTree));
break;
case 0b1111:
// everything
throw new RuntimeException("OEPSSSS");
}
}
private static Vertex both(Vertex v1, Vertex v2) {
if (v1 == null && v2 == null) {
return null;
}
if (v1 == null && v2 != null) {
return v2;
}
if (v2 != null && v1 != v2) {
throw new RuntimeException("HELP HELP");
}
return v1;
}
/**
* Sets the vertex for the TL hexagon of the given tree.
*/
private static void setTLVertex(HexagonalMap h, Tree t, Vertex v) {
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, 3 * -t.yCoordinate), v);
}
/**
* Gets the vertex for the TL hexagon of the given tree.
*/
private static Vertex getTLVertex(HexagonalMap h, Tree t) {
return h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, 3 * -t.yCoordinate));
}
/**
* Sets the vertex for the TR hexagon of the given tree.
*/
private static void setTRVertex(HexagonalMap h, Tree t, Vertex v) {
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate), v);
}
/**
* Gets the vertex for the TR hexagon of the given tree.
*/
private static Vertex getTRVertex(HexagonalMap h, Tree t) {
return h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate));
}
/**
* Sets the vertex for the BL hexagon of the given tree.
*/
private static void setBLVertex(HexagonalMap h, Tree t, Vertex v) {
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, 3 * -t.yCoordinate - 1), v);
}
/**
* Gets the vertex for the BL hexagon of the given tree.
*/
private static Vertex getBLVertex(HexagonalMap h, Tree t) {
return h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, 3 * -t.yCoordinate - 1));
}
/**
* Sets the vertex for the BR hexagon of the given tree.
*/
private static void setBRVertex(HexagonalMap h, Tree t, Vertex v) {
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate - 1), v);
}
/**
* Gets the vertex for the BR hexagon of the given tree.
*/
private static Vertex getBRVertex(HexagonalMap h, Tree t) {
return h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, 3 * -t.yCoordinate - 1));
}
/**
* Finds a vertex (color) that is shared by the faces of the given trees.
*
* @param t1 The first tree.
* @param t2 The second tree.
* @return A vertex <code>v</code> with <pre>
* t1.face.vertices.contains(v) && t2.face.vertices.contains(v)
* </pre> If one doesn't exist, <code>null</code> is returned.
*/
private static Vertex findCommonVertex(Tree t1, Tree t2) {
return findCommonVertexExcept(t1, t2, null);
}
/**
* Finds a vertex (color) that is shared by the faces of the given trees.
* Ignores the vertex given.
*
* @param t1 The first tree.
* @param t2 The second tree.
* @param except The vertex to ignore.
* @return A vertex <code>v != except</code> with <pre>
* t1.face.vertices.contains(v) && t2.face.vertices.contains(v)
* </pre> If one doesn't exist, <code>null</code> is returned.
*/
private static Vertex findCommonVertexExcept(Tree t1, Tree t2, Vertex except) {
if (t2.face.vertices.get(0) != except
&& t1.face.vertices.contains(t2.face.vertices.get(0))) {
return t2.face.vertices.get(0);
}
if (t2.face.vertices.get(1) != except
&& t1.face.vertices.contains(t2.face.vertices.get(1))) {
return t2.face.vertices.get(1);
}
if (t2.face.vertices.get(2) != except
&& t1.face.vertices.contains(t2.face.vertices.get(2))) {
return t2.face.vertices.get(2);
}
return null;
}
/**
* Finds a vertex (color) that is in the face of one tree, and not in the
* other.
*
* @param t1 The first tree.
* @param t2 The second tree.
* @return A vertex <code>v</code> with <pre>
* t1.face.vertices.contains(v) && !t2.face.vertices.contains(v)
* </pre> If one doesn't exist, <code>null</code> is returned.
*/
private static Vertex findOtherVertex(Tree t1, Tree t2) {
if (!t2.face.vertices.contains(t1.face.vertices.get(0))) {
return t1.face.vertices.get(0);
}
if (!t2.face.vertices.contains(t1.face.vertices.get(1))) {
return t1.face.vertices.get(1);
}
if (!t2.face.vertices.contains(t1.face.vertices.get(2))) {
return t1.face.vertices.get(2);
}
return null;
}
private static void augmentColoring(HexagonalMap h, Tree t) {
Vertex[] vertices = new Vertex[]{
getTLVertex(h, t), getTRVertex(h, t), getBLVertex(h, t), getBRVertex(h, t)
};
Vertex first = null;
Vertex second = null;
Vertex third = null;
int numNulls = 0;
for (Vertex v : vertices) {
if (v == null) {
numNulls++;
continue;
}
if (first == null) {
first = v;
} else if (first != v) {
if (second == null) {
second = v;
} else if (second != v) {
third = v;
}
}
}
// only continue if we have exactly two colors and 1 unknown
if (numNulls != 1 || first == null || second == null || third != null) {
return;
}
for (Vertex v : t.face.vertices) {
if (v != first && v != second) {
third = v;
if (v == null) {
throw new StackOverflowError("WHAA");
}
break;
}
}
if (getTLVertex(h, t) == null) {
setTLVertex(h, t, third);
}
if (getTRVertex(h, t) == null) {
setTRVertex(h, t, third);
}
if (getBLVertex(h, t) == null) {
setBLVertex(h, t, third);
}
if (getBRVertex(h, t) == null) {
setBRVertex(h, t, third);
}
}
private static void addSubtree(HexagonalMap h, Tree origin, Tree t) {
// the edge to the subtree
if (origin.xCoordinate == t.xCoordinate) {
// the actual subtree: recursive call to addTree()
addTree(h, t, null, origin);
// it is a vertical edge
for (int z = -3 * t.yCoordinate + 1; z <= -3 * origin.yCoordinate - 2; z++) {
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, z),
h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate, 0, z - 1)));
h.setVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, z),
h.getVertex(new BarycentricCoordinate(3 * t.xCoordinate + 1, 0, z - 1)));
}
} else {
// the actual subtree: recursive call to addTree()
addTree(h, t, origin, null);
// it is a horizontal edge
for (int x = 3 * t.xCoordinate - 1; x >= 3 * origin.xCoordinate + 2; x--) {
h.setVertex(new BarycentricCoordinate(x, 0, -3 * t.yCoordinate),
h.getVertex(new BarycentricCoordinate(x + 1, 0, -3 * t.yCoordinate)));
h.setVertex(new BarycentricCoordinate(x, 0, -3 * t.yCoordinate - 1),
h.getVertex(new BarycentricCoordinate(x + 1, 0, -3 * t.yCoordinate - 1)));
}
}
}
}
|
197481_35 | package org.openRealmOfStars.game;
/*
* Open Realm of Stars game project
* Copyright (C) 2016-2023 Tuomo Untinen
*
* 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, see http://www.gnu.org/licenses/
*/
/**
*
* Game states in enum
*
*/
public enum GameState {
/**
* Main Menu state where Main menu is shown
*/
MAIN_MENU,
/**
* State where universum is being created. This is so called pseudo state
* it does not have actual screen.
*/
NEW_GAME,
/**
* Star Map view where Star map of the game is shown
*/
STARMAP,
/**
* Planet View is state where planet information is shown and player
* can handling planet constructions.
*/
PLANETVIEW,
/**
* State where fleet is being shown. Fleet can be either in space or
* orbiting a planet
*/
FLEETVIEW,
/**
* Research view is state where player can select which techs to focus
* and view techs which have already researched.
*/
RESEARCHVIEW,
/**
* View ships is state where player can browse through his or her
* ships.
*/
VIEWSHIPS,
/**
* Ship Design is state where player can design totally new ships.
*/
SHIPDESIGN,
/**
* Combat state is when two fleets encounter and battle begins.
*/
COMBAT,
/**
* Credits state is state which shows license information and people
* who has contributed to this game.
*/
CREDITS,
/**
* AI Turn is state where ai is doing it's own turn and random planet
* is being shown to player.
*/
AITURN,
/**
* State which is shown when enemy's planet is being bombed.
*/
PLANETBOMBINGVIEW,
/**
* Galaxy creation is state where basic settings for galaxy is being
* configured.
*/
GALAXY_CREATION,
/**
* State where player can select which saved game is about to be loaded.
*/
LOAD_GAME,
/**
* View player stats info
*/
VIEWSTATS,
/**
* Diplomacy view
*/
DIPLOMACY_VIEW,
/**
* News corp view which will tell highlights of previous turn
*/
NEWS_CORP_VIEW,
/**
* Espionage view show spy information about other reals
* and add possibility to pay GNBC to create fake news
*/
ESPIONAGE_VIEW,
/**
* History view showing historical game events
*/
HISTORY_VIEW,
/**
* Options view to configure sound/music volume and resolution.
*/
OPTIONS_VIEW,
/**
* State where trade fleet is being shown.
* Fleet needs to be orbiting own planet.
*/
FLEET_TRADE_VIEW,
/**
* Realm View
*/
REALM_VIEW,
/**
* Planet list view containing all the planets in single list.
*/
PLANET_LIST_VIEW,
/**
* Voting view
*/
VOTE_VIEW,
/**
* View where save game file name is defined when starting new game.
*/
SAVE_GAME_NAME_VIEW,
/**
* View where all tutorial/help text is being shown.
*/
HELP_VIEW,
/**
* Show all the leaders for realm.
*/
LEADER_VIEW,
/**
* Espionage mission view.
*/
ESPIONAGE_MISSIONS_VIEW,
/**
* View for setuping ambient lights for the game.
*/
SETUP_AMBIENT_LIGHTS,
/**
* View for ship upgrade.
*/
SHIP_UPGRADE_VIEW,
/**
* Text screen on top of planet screen
*/
TEXT_SCREEN_VIEW,
/**
* Text screen when game ends.
*/
GAME_END_VIEW,
/**
* View where human player can select next galactic voting.
*/
VOTING_SELECTION_VIEW,
/**
* View Change Log.
*/
CHANGE_LOG,
/**
* Story view for viewing background story of the realm.
*/
STORY_VIEW,
/**
* Story view for viewing full story of the realm when game ends.
*/
END_STORY_VIEW,
/** View for configuring individual realm */
REALM_SETUP_VIEW,
/** View for configuring all AI realms */
AI_REALM_SETUP_VIEW;
}
| tuomount/Open-Realms-of-Stars | src/main/java/org/openRealmOfStars/game/GameState.java | 1,358 | /**
* View Change Log.
*/ | block_comment | nl | package org.openRealmOfStars.game;
/*
* Open Realm of Stars game project
* Copyright (C) 2016-2023 Tuomo Untinen
*
* 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, see http://www.gnu.org/licenses/
*/
/**
*
* Game states in enum
*
*/
public enum GameState {
/**
* Main Menu state where Main menu is shown
*/
MAIN_MENU,
/**
* State where universum is being created. This is so called pseudo state
* it does not have actual screen.
*/
NEW_GAME,
/**
* Star Map view where Star map of the game is shown
*/
STARMAP,
/**
* Planet View is state where planet information is shown and player
* can handling planet constructions.
*/
PLANETVIEW,
/**
* State where fleet is being shown. Fleet can be either in space or
* orbiting a planet
*/
FLEETVIEW,
/**
* Research view is state where player can select which techs to focus
* and view techs which have already researched.
*/
RESEARCHVIEW,
/**
* View ships is state where player can browse through his or her
* ships.
*/
VIEWSHIPS,
/**
* Ship Design is state where player can design totally new ships.
*/
SHIPDESIGN,
/**
* Combat state is when two fleets encounter and battle begins.
*/
COMBAT,
/**
* Credits state is state which shows license information and people
* who has contributed to this game.
*/
CREDITS,
/**
* AI Turn is state where ai is doing it's own turn and random planet
* is being shown to player.
*/
AITURN,
/**
* State which is shown when enemy's planet is being bombed.
*/
PLANETBOMBINGVIEW,
/**
* Galaxy creation is state where basic settings for galaxy is being
* configured.
*/
GALAXY_CREATION,
/**
* State where player can select which saved game is about to be loaded.
*/
LOAD_GAME,
/**
* View player stats info
*/
VIEWSTATS,
/**
* Diplomacy view
*/
DIPLOMACY_VIEW,
/**
* News corp view which will tell highlights of previous turn
*/
NEWS_CORP_VIEW,
/**
* Espionage view show spy information about other reals
* and add possibility to pay GNBC to create fake news
*/
ESPIONAGE_VIEW,
/**
* History view showing historical game events
*/
HISTORY_VIEW,
/**
* Options view to configure sound/music volume and resolution.
*/
OPTIONS_VIEW,
/**
* State where trade fleet is being shown.
* Fleet needs to be orbiting own planet.
*/
FLEET_TRADE_VIEW,
/**
* Realm View
*/
REALM_VIEW,
/**
* Planet list view containing all the planets in single list.
*/
PLANET_LIST_VIEW,
/**
* Voting view
*/
VOTE_VIEW,
/**
* View where save game file name is defined when starting new game.
*/
SAVE_GAME_NAME_VIEW,
/**
* View where all tutorial/help text is being shown.
*/
HELP_VIEW,
/**
* Show all the leaders for realm.
*/
LEADER_VIEW,
/**
* Espionage mission view.
*/
ESPIONAGE_MISSIONS_VIEW,
/**
* View for setuping ambient lights for the game.
*/
SETUP_AMBIENT_LIGHTS,
/**
* View for ship upgrade.
*/
SHIP_UPGRADE_VIEW,
/**
* Text screen on top of planet screen
*/
TEXT_SCREEN_VIEW,
/**
* Text screen when game ends.
*/
GAME_END_VIEW,
/**
* View where human player can select next galactic voting.
*/
VOTING_SELECTION_VIEW,
/**
* View Change Log.<SUF>*/
CHANGE_LOG,
/**
* Story view for viewing background story of the realm.
*/
STORY_VIEW,
/**
* Story view for viewing full story of the realm when game ends.
*/
END_STORY_VIEW,
/** View for configuring individual realm */
REALM_SETUP_VIEW,
/** View for configuring all AI realms */
AI_REALM_SETUP_VIEW;
}
|
188485_23 | /*
* Copyright (c) 2002-2004
* All rights reserved.
*/
package com.atlassian.jira.web.action.issue.bulkedit;
import com.atlassian.core.util.map.EasyMap;
import com.atlassian.jira.bc.issue.search.SearchService;
import com.atlassian.jira.bulkedit.BulkOperationManager;
import com.atlassian.jira.bulkedit.operation.BulkEditAction;
import com.atlassian.jira.bulkedit.operation.BulkEditOperation;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.IssueFactory;
import com.atlassian.jira.issue.customfields.impl.FieldValidationException;
import com.atlassian.jira.issue.fields.FieldManager;
import com.atlassian.jira.issue.fields.OrderableField;
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutItem;
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutManager;
import com.atlassian.jira.issue.fields.screen.FieldScreenRenderLayoutItem;
import com.atlassian.jira.issue.fields.screen.FieldScreenRenderLayoutItemImpl;
import com.atlassian.jira.security.PermissionManager;
import com.atlassian.jira.security.Permissions;
import com.atlassian.jira.security.xsrf.RequiresXsrfCheck;
import com.atlassian.jira.task.TaskManager;
import com.atlassian.jira.util.I18nHelper;
import com.atlassian.jira.util.collect.MapBuilder;
import com.atlassian.jira.web.bean.BulkEditBean;
import com.atlassian.jira.web.bean.BulkEditBeanSessionHelper;
import org.apache.commons.jelly.util.NestedRuntimeException;
import org.ofbiz.core.entity.GenericValue;
import webwork.action.ActionContext;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class BulkEdit extends AbstractBulkOperationDetailsAction
{
public static final String RADIO_ERROR_MSG = "buik.edit.must.select.one.action.to.perform";
public static final String SHOW_BULK_EDIT_WARNING = "showBulkEditWarning";
private BulkEditOperation bulkEditOperation;
// actions array is retrieved from the checkbox group in the JSP called "actions"
// this stores the fields that the user has indicated an intention to bulk edit (ie. my checking it)
private String[] actions;
private Map editActions;
private Map selectedActions;
ArrayList visibleActions;
ArrayList hiddenActions;
private List customFields;
private final FieldManager fieldManager;
private final FieldLayoutManager fieldLayoutManager;
private final IssueFactory issueFactory;
private final PermissionManager permissionManager;
public BulkEdit(SearchService searchService, BulkOperationManager bulkOperationManager, FieldManager fieldManager,
IssueFactory issueFactory, PermissionManager permissionManager,
final FieldLayoutManager fieldLayoutManager,
final BulkEditBeanSessionHelper bulkEditBeanSessionHelper, final TaskManager taskManager,
final I18nHelper i18nHelper)
{
super(searchService, bulkEditBeanSessionHelper, taskManager, i18nHelper);
this.fieldManager = fieldManager;
this.bulkEditOperation = (BulkEditOperation) bulkOperationManager.getProgressAwareOperation(
BulkEditOperation.NAME_KEY);
this.issueFactory = issueFactory;
this.permissionManager = permissionManager;
this.fieldLayoutManager = fieldLayoutManager;
}
public String getFieldHtml(String fieldId) throws Exception
{
OrderableField orderableField = fieldManager.getOrderableField(fieldId);
final Map displayParameters =
EasyMap.build(OrderableField.NO_HEADER_PARAM_KEY, Boolean.TRUE, SHOW_BULK_EDIT_WARNING, Boolean.TRUE);
return orderableField.getBulkEditHtml(getBulkEditBean(), this, getBulkEditBean(), displayParameters);
}
public String getFieldViewHtml(OrderableField orderableField)
{
// There is a validation that will not allow an edit to occur on a field that has different renderer types
// defined in the field layout item so if we get here then we know it is safe to grab the first layout
// item we can find for the field and that this will imply the correct renderer type.
FieldLayoutItem layoutItem = null;
if (!getBulkEditBean().getFieldLayouts().isEmpty())
{
layoutItem = getBulkEditBean().getFieldLayouts().iterator().next().getFieldLayoutItem(orderableField);
}
final Map<String, Object> displayParams = MapBuilder.<String, Object>newBuilder("readonly", Boolean.TRUE)
.add("nolink", Boolean.TRUE)
.add("bulkoperation", getBulkEditBean().getOperationName())
.add("prefix", "new_").toMutableMap();
return orderableField.getViewHtml(layoutItem, this, getBulkEditBean().getSelectedIssues().iterator().next(),
getBulkEditBean().getFieldValues().get(orderableField.getId()), displayParams);
}
protected Issue getIssueObject(GenericValue issueGV)
{
return issueFactory.getIssue(issueGV);
}
protected FieldScreenRenderLayoutItem buildFieldScreenRenderLayoutItem(final OrderableField field,
GenericValue issue)
{
return new FieldScreenRenderLayoutItemImpl(null,
fieldLayoutManager.getFieldLayout(issue).getFieldLayoutItem(field));
}
public String doDetails()
{
BulkEditBean bulkEditBean = getBulkEditBean();
// Check that we have a BulkEditBean - i.e. the user got here by following the wizard - not by
// clicking the "back" button of the browser (or something like that)
if (bulkEditBean == null)
{
// If we do not have BulkEditBean, send the user to the first step of the wizard
return redirectToStart();
}
setFieldDefaults();
bulkEditBean.clearAvailablePreviousSteps();
bulkEditBean.addAvailablePreviousStep(1);
bulkEditBean.addAvailablePreviousStep(2);
// Ensure that bulk notification can be disabled
if (isCanDisableMailNotifications())
bulkEditBean.setSendBulkNotification(false);
else
bulkEditBean.setSendBulkNotification(true);
setCurrentStep(3);
return INPUT;
}
private void setFieldDefaults()
{
for (final Object o : getEditActions().values())
{
BulkEditAction bulkEditAction = (BulkEditAction) o;
if (bulkEditAction.isAvailable(getBulkEditBean()))
{
// TODO Might have to create another method - populateForBulkEdit
bulkEditAction.getField()
.populateDefaults(getBulkEditBean().getFieldValuesHolder(), getIssueObject(null));
}
}
}
@RequiresXsrfCheck
public String doDetailsValidation() throws Exception
{
// Check that we have a BulkEditBean - i.e. the user got here by following the wizard - not by
// clicking the "back" button of the browser (or something like that)
if (getBulkEditBean() == null)
{
// If we do not have BulkEditBean, send the user to the first step of the wizard
return redirectToStart();
}
validateInput();
if (invalidInput())
return ERROR;
else
updateBean();
return getResult();
}
@RequiresXsrfCheck
public String doPerform() throws Exception
{
if (getBulkEditBean() == null)
{
return redirectToStart();
}
doValidationPerform();
if (invalidInput())
{
return ERROR;
}
final String taskName = getText("bulk.operation.progress.taskname.edit",
getRootBulkEditBean().getSelectedIssuesIncludingSubTasks().size());
return submitBulkOperationTask(getBulkEditBean(), getBulkEditOperation(), taskName);
}
private void doValidationPerform()
{
try
{
// Ensure the user has the global BULK CHANGE permission
if (!permissionManager.hasPermission(Permissions.BULK_CHANGE, getLoggedInUser()))
{
addErrorMessage(getText("bulk.change.no.permission",
String.valueOf(getBulkEditBean().getSelectedIssues().size())));
return;
}
// Ensure the user can perform the operation
if (!getBulkEditOperation().canPerform(getBulkEditBean(), getLoggedInApplicationUser()))
{
addErrorMessage(getText("bulk.edit.cannotperform.error",
String.valueOf(getBulkEditBean().getSelectedIssues().size())));
return;
}
}
catch (Exception e)
{
log.error("Error occurred while testing operation.", e);
addErrorMessage(getText("bulk.canperform.error"));
return;
}
try
{
for (BulkEditAction bulkEditAction : getBulkEditBean().getActions().values())
{
if (!bulkEditAction.isAvailable(getBulkEditBean()))
{
addErrorMessage(getText("bulk.edit.perform.invalid.action",
String.valueOf(getBulkEditBean().getSelectedIssues().size())));
}
}
}
catch (Exception e)
{
log.error("Error occurred validating available update operations.", e);
addErrorMessage(getText("bulk.canperform.error"));
}
}
public String doDefault() throws Exception
{
if (getBulkEditBean() == null)
{
return redirectToStart();
}
// set BulkEditBean to use the issues that have now been selected rather than the issues from the search request
getBulkEditBean().setIssuesInUse(getBulkEditBean().getSelectedIssues());
return super.doDefault();
}
private void validateInput()
{
if (getActions() == null || getActions().length == 0)
{
addErrorMessage(getText(RADIO_ERROR_MSG));
return;
}
selectedActions = new LinkedHashMap();
for (int i = 0; i < getActions().length; i++)
{
String fieldId = getActions()[i];
BulkEditAction bulkEditAction = (BulkEditAction) getEditActions().get(fieldId);
selectedActions.put(bulkEditAction.getField().getId(), bulkEditAction);
// Validate the field for all issues
bulkEditAction.getField()
.populateFromParams(getBulkEditBean().getFieldValuesHolder(), ActionContext.getParameters());
for (Issue issue : getBulkEditBean().getSelectedIssues())
{
bulkEditAction.getField().validateParams(getBulkEditBean(), this, this, issue,
buildFieldScreenRenderLayoutItem(bulkEditAction.getField(), issue.getGenericValue()));
}
}
}
public boolean isHasAvailableActions() throws Exception
{
return getBulkEditOperation().canPerform(getBulkEditBean(), getLoggedInApplicationUser());
}
private void updateBean()
{
// set values in bean once form data has been validated
getBulkEditBean().setActions(selectedActions);
try
{
for (BulkEditAction bulkEditAction : getBulkEditBean().getActions().values())
{
OrderableField field = bulkEditAction.getField();
Object value = field.getValueFromParams(getBulkEditBean().getFieldValuesHolder());
getBulkEditBean().getFieldValues().put(field.getId(), value);
}
}
catch (FieldValidationException e)
{
log.error("Error getting field value.", e);
throw new NestedRuntimeException("Error getting field value.", e);
}
getBulkEditBean().clearAvailablePreviousSteps();
getBulkEditBean().addAvailablePreviousStep(1);
getBulkEditBean().addAvailablePreviousStep(2);
getBulkEditBean().addAvailablePreviousStep(3);
setCurrentStep(4);
}
/**
* Returns a list of bulk actions
* If search request was performed on "All Projects" (ie. multiple projects) certain actions such as fixfor will not
* be displayed, as fixfor versions obviously differ across projects.
* <p/>
* If no issues have been selected then no actions should be shown
*/
public Map getEditActions()
{
if (editActions == null)
{
editActions = getBulkEditOperation().getActions(getBulkEditBean(), getLoggedInApplicationUser());
}
return editActions;
}
/**
* Returns a list of bulk actions which are visible/available
*/
public Collection getVisibleActions()
{
if (visibleActions == null)
{
seperateVisibleAndHiddenActions();
}
return visibleActions;
}
/**
* Returns a list of bulk actions which are hidden/unavailable
*/
public Collection getHiddenActions()
{
if (hiddenActions == null)
{
seperateVisibleAndHiddenActions();
}
return hiddenActions;
}
/**
* Initialises the visibleActions and hiddenActions collection
*/
private void seperateVisibleAndHiddenActions()
{
visibleActions = new ArrayList();
hiddenActions = new ArrayList();
Iterator actions = getEditActions().values().iterator();
while (actions.hasNext())
{
BulkEditAction action = (BulkEditAction) actions.next();
if (action.isAvailable(getBulkEditBean()))
{
visibleActions.add(action);
}
else
{
hiddenActions.add(action);
}
}
}
public boolean isAvailable(String action) throws Exception
{
return getEditActions().containsKey(action);
}
public Collection getCustomFields()
{
if (customFields == null)
{
// customFields = getBulkEditOperation().getCustomFields(getBulkEditBean(), getLoggedInUser());
customFields = new LinkedList();
}
return customFields;
}
// Check if the array of the selected actions is null and if it contains any elements
// The user may select an action but not select an argument for the action.
// Also check if the argument is null.
public boolean isHasFirstElement(List actions)
{
if (actions != null && !actions.isEmpty() && (actions.get(0) != null))
{
// Action selected with a corresponding argument
return true;
}
return false;
}
public void setCurrentStep(int step)
{
getBulkEditBean().setCurrentStep(step);
}
public String[] getActions()
{
return actions;
}
public void setActions(String[] actions)
{
this.actions = actions;
}
private BulkEditOperation getBulkEditOperation()
{
return bulkEditOperation;
}
public String getOperationDetailsActionName()
{
return getBulkEditOperation().getOperationName() + "Details.jspa";
}
public boolean isChecked(String value)
{
if (getActions() == null || getActions().length == 0)
{
// If there were no actions submitted we are either being invoked with no check boxes checked
// (which should be OK, as there is nothing to validate), or we are coming from the later stage of
// the wizard. In this case we should look into BulkEditBean
if (getBulkEditBean().getActions() != null)
{
return getBulkEditBean().getActions().containsKey(value);
}
return false;
}
else
{
// If we have check boxes (actions) submitted use them
for (int i = 0; i < getActions().length; i++)
{
String action = getActions()[i];
if (action.equals(value))
return true;
}
return false;
}
}
}
| turgaycelik/mysource | jira-project/jira-components/jira-core/src/main/java/com/atlassian/jira/web/action/issue/bulkedit/BulkEdit.java | 4,282 | // customFields = getBulkEditOperation().getCustomFields(getBulkEditBean(), getLoggedInUser()); | line_comment | nl | /*
* Copyright (c) 2002-2004
* All rights reserved.
*/
package com.atlassian.jira.web.action.issue.bulkedit;
import com.atlassian.core.util.map.EasyMap;
import com.atlassian.jira.bc.issue.search.SearchService;
import com.atlassian.jira.bulkedit.BulkOperationManager;
import com.atlassian.jira.bulkedit.operation.BulkEditAction;
import com.atlassian.jira.bulkedit.operation.BulkEditOperation;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.IssueFactory;
import com.atlassian.jira.issue.customfields.impl.FieldValidationException;
import com.atlassian.jira.issue.fields.FieldManager;
import com.atlassian.jira.issue.fields.OrderableField;
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutItem;
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutManager;
import com.atlassian.jira.issue.fields.screen.FieldScreenRenderLayoutItem;
import com.atlassian.jira.issue.fields.screen.FieldScreenRenderLayoutItemImpl;
import com.atlassian.jira.security.PermissionManager;
import com.atlassian.jira.security.Permissions;
import com.atlassian.jira.security.xsrf.RequiresXsrfCheck;
import com.atlassian.jira.task.TaskManager;
import com.atlassian.jira.util.I18nHelper;
import com.atlassian.jira.util.collect.MapBuilder;
import com.atlassian.jira.web.bean.BulkEditBean;
import com.atlassian.jira.web.bean.BulkEditBeanSessionHelper;
import org.apache.commons.jelly.util.NestedRuntimeException;
import org.ofbiz.core.entity.GenericValue;
import webwork.action.ActionContext;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class BulkEdit extends AbstractBulkOperationDetailsAction
{
public static final String RADIO_ERROR_MSG = "buik.edit.must.select.one.action.to.perform";
public static final String SHOW_BULK_EDIT_WARNING = "showBulkEditWarning";
private BulkEditOperation bulkEditOperation;
// actions array is retrieved from the checkbox group in the JSP called "actions"
// this stores the fields that the user has indicated an intention to bulk edit (ie. my checking it)
private String[] actions;
private Map editActions;
private Map selectedActions;
ArrayList visibleActions;
ArrayList hiddenActions;
private List customFields;
private final FieldManager fieldManager;
private final FieldLayoutManager fieldLayoutManager;
private final IssueFactory issueFactory;
private final PermissionManager permissionManager;
public BulkEdit(SearchService searchService, BulkOperationManager bulkOperationManager, FieldManager fieldManager,
IssueFactory issueFactory, PermissionManager permissionManager,
final FieldLayoutManager fieldLayoutManager,
final BulkEditBeanSessionHelper bulkEditBeanSessionHelper, final TaskManager taskManager,
final I18nHelper i18nHelper)
{
super(searchService, bulkEditBeanSessionHelper, taskManager, i18nHelper);
this.fieldManager = fieldManager;
this.bulkEditOperation = (BulkEditOperation) bulkOperationManager.getProgressAwareOperation(
BulkEditOperation.NAME_KEY);
this.issueFactory = issueFactory;
this.permissionManager = permissionManager;
this.fieldLayoutManager = fieldLayoutManager;
}
public String getFieldHtml(String fieldId) throws Exception
{
OrderableField orderableField = fieldManager.getOrderableField(fieldId);
final Map displayParameters =
EasyMap.build(OrderableField.NO_HEADER_PARAM_KEY, Boolean.TRUE, SHOW_BULK_EDIT_WARNING, Boolean.TRUE);
return orderableField.getBulkEditHtml(getBulkEditBean(), this, getBulkEditBean(), displayParameters);
}
public String getFieldViewHtml(OrderableField orderableField)
{
// There is a validation that will not allow an edit to occur on a field that has different renderer types
// defined in the field layout item so if we get here then we know it is safe to grab the first layout
// item we can find for the field and that this will imply the correct renderer type.
FieldLayoutItem layoutItem = null;
if (!getBulkEditBean().getFieldLayouts().isEmpty())
{
layoutItem = getBulkEditBean().getFieldLayouts().iterator().next().getFieldLayoutItem(orderableField);
}
final Map<String, Object> displayParams = MapBuilder.<String, Object>newBuilder("readonly", Boolean.TRUE)
.add("nolink", Boolean.TRUE)
.add("bulkoperation", getBulkEditBean().getOperationName())
.add("prefix", "new_").toMutableMap();
return orderableField.getViewHtml(layoutItem, this, getBulkEditBean().getSelectedIssues().iterator().next(),
getBulkEditBean().getFieldValues().get(orderableField.getId()), displayParams);
}
protected Issue getIssueObject(GenericValue issueGV)
{
return issueFactory.getIssue(issueGV);
}
protected FieldScreenRenderLayoutItem buildFieldScreenRenderLayoutItem(final OrderableField field,
GenericValue issue)
{
return new FieldScreenRenderLayoutItemImpl(null,
fieldLayoutManager.getFieldLayout(issue).getFieldLayoutItem(field));
}
public String doDetails()
{
BulkEditBean bulkEditBean = getBulkEditBean();
// Check that we have a BulkEditBean - i.e. the user got here by following the wizard - not by
// clicking the "back" button of the browser (or something like that)
if (bulkEditBean == null)
{
// If we do not have BulkEditBean, send the user to the first step of the wizard
return redirectToStart();
}
setFieldDefaults();
bulkEditBean.clearAvailablePreviousSteps();
bulkEditBean.addAvailablePreviousStep(1);
bulkEditBean.addAvailablePreviousStep(2);
// Ensure that bulk notification can be disabled
if (isCanDisableMailNotifications())
bulkEditBean.setSendBulkNotification(false);
else
bulkEditBean.setSendBulkNotification(true);
setCurrentStep(3);
return INPUT;
}
private void setFieldDefaults()
{
for (final Object o : getEditActions().values())
{
BulkEditAction bulkEditAction = (BulkEditAction) o;
if (bulkEditAction.isAvailable(getBulkEditBean()))
{
// TODO Might have to create another method - populateForBulkEdit
bulkEditAction.getField()
.populateDefaults(getBulkEditBean().getFieldValuesHolder(), getIssueObject(null));
}
}
}
@RequiresXsrfCheck
public String doDetailsValidation() throws Exception
{
// Check that we have a BulkEditBean - i.e. the user got here by following the wizard - not by
// clicking the "back" button of the browser (or something like that)
if (getBulkEditBean() == null)
{
// If we do not have BulkEditBean, send the user to the first step of the wizard
return redirectToStart();
}
validateInput();
if (invalidInput())
return ERROR;
else
updateBean();
return getResult();
}
@RequiresXsrfCheck
public String doPerform() throws Exception
{
if (getBulkEditBean() == null)
{
return redirectToStart();
}
doValidationPerform();
if (invalidInput())
{
return ERROR;
}
final String taskName = getText("bulk.operation.progress.taskname.edit",
getRootBulkEditBean().getSelectedIssuesIncludingSubTasks().size());
return submitBulkOperationTask(getBulkEditBean(), getBulkEditOperation(), taskName);
}
private void doValidationPerform()
{
try
{
// Ensure the user has the global BULK CHANGE permission
if (!permissionManager.hasPermission(Permissions.BULK_CHANGE, getLoggedInUser()))
{
addErrorMessage(getText("bulk.change.no.permission",
String.valueOf(getBulkEditBean().getSelectedIssues().size())));
return;
}
// Ensure the user can perform the operation
if (!getBulkEditOperation().canPerform(getBulkEditBean(), getLoggedInApplicationUser()))
{
addErrorMessage(getText("bulk.edit.cannotperform.error",
String.valueOf(getBulkEditBean().getSelectedIssues().size())));
return;
}
}
catch (Exception e)
{
log.error("Error occurred while testing operation.", e);
addErrorMessage(getText("bulk.canperform.error"));
return;
}
try
{
for (BulkEditAction bulkEditAction : getBulkEditBean().getActions().values())
{
if (!bulkEditAction.isAvailable(getBulkEditBean()))
{
addErrorMessage(getText("bulk.edit.perform.invalid.action",
String.valueOf(getBulkEditBean().getSelectedIssues().size())));
}
}
}
catch (Exception e)
{
log.error("Error occurred validating available update operations.", e);
addErrorMessage(getText("bulk.canperform.error"));
}
}
public String doDefault() throws Exception
{
if (getBulkEditBean() == null)
{
return redirectToStart();
}
// set BulkEditBean to use the issues that have now been selected rather than the issues from the search request
getBulkEditBean().setIssuesInUse(getBulkEditBean().getSelectedIssues());
return super.doDefault();
}
private void validateInput()
{
if (getActions() == null || getActions().length == 0)
{
addErrorMessage(getText(RADIO_ERROR_MSG));
return;
}
selectedActions = new LinkedHashMap();
for (int i = 0; i < getActions().length; i++)
{
String fieldId = getActions()[i];
BulkEditAction bulkEditAction = (BulkEditAction) getEditActions().get(fieldId);
selectedActions.put(bulkEditAction.getField().getId(), bulkEditAction);
// Validate the field for all issues
bulkEditAction.getField()
.populateFromParams(getBulkEditBean().getFieldValuesHolder(), ActionContext.getParameters());
for (Issue issue : getBulkEditBean().getSelectedIssues())
{
bulkEditAction.getField().validateParams(getBulkEditBean(), this, this, issue,
buildFieldScreenRenderLayoutItem(bulkEditAction.getField(), issue.getGenericValue()));
}
}
}
public boolean isHasAvailableActions() throws Exception
{
return getBulkEditOperation().canPerform(getBulkEditBean(), getLoggedInApplicationUser());
}
private void updateBean()
{
// set values in bean once form data has been validated
getBulkEditBean().setActions(selectedActions);
try
{
for (BulkEditAction bulkEditAction : getBulkEditBean().getActions().values())
{
OrderableField field = bulkEditAction.getField();
Object value = field.getValueFromParams(getBulkEditBean().getFieldValuesHolder());
getBulkEditBean().getFieldValues().put(field.getId(), value);
}
}
catch (FieldValidationException e)
{
log.error("Error getting field value.", e);
throw new NestedRuntimeException("Error getting field value.", e);
}
getBulkEditBean().clearAvailablePreviousSteps();
getBulkEditBean().addAvailablePreviousStep(1);
getBulkEditBean().addAvailablePreviousStep(2);
getBulkEditBean().addAvailablePreviousStep(3);
setCurrentStep(4);
}
/**
* Returns a list of bulk actions
* If search request was performed on "All Projects" (ie. multiple projects) certain actions such as fixfor will not
* be displayed, as fixfor versions obviously differ across projects.
* <p/>
* If no issues have been selected then no actions should be shown
*/
public Map getEditActions()
{
if (editActions == null)
{
editActions = getBulkEditOperation().getActions(getBulkEditBean(), getLoggedInApplicationUser());
}
return editActions;
}
/**
* Returns a list of bulk actions which are visible/available
*/
public Collection getVisibleActions()
{
if (visibleActions == null)
{
seperateVisibleAndHiddenActions();
}
return visibleActions;
}
/**
* Returns a list of bulk actions which are hidden/unavailable
*/
public Collection getHiddenActions()
{
if (hiddenActions == null)
{
seperateVisibleAndHiddenActions();
}
return hiddenActions;
}
/**
* Initialises the visibleActions and hiddenActions collection
*/
private void seperateVisibleAndHiddenActions()
{
visibleActions = new ArrayList();
hiddenActions = new ArrayList();
Iterator actions = getEditActions().values().iterator();
while (actions.hasNext())
{
BulkEditAction action = (BulkEditAction) actions.next();
if (action.isAvailable(getBulkEditBean()))
{
visibleActions.add(action);
}
else
{
hiddenActions.add(action);
}
}
}
public boolean isAvailable(String action) throws Exception
{
return getEditActions().containsKey(action);
}
public Collection getCustomFields()
{
if (customFields == null)
{
// customFields =<SUF>
customFields = new LinkedList();
}
return customFields;
}
// Check if the array of the selected actions is null and if it contains any elements
// The user may select an action but not select an argument for the action.
// Also check if the argument is null.
public boolean isHasFirstElement(List actions)
{
if (actions != null && !actions.isEmpty() && (actions.get(0) != null))
{
// Action selected with a corresponding argument
return true;
}
return false;
}
public void setCurrentStep(int step)
{
getBulkEditBean().setCurrentStep(step);
}
public String[] getActions()
{
return actions;
}
public void setActions(String[] actions)
{
this.actions = actions;
}
private BulkEditOperation getBulkEditOperation()
{
return bulkEditOperation;
}
public String getOperationDetailsActionName()
{
return getBulkEditOperation().getOperationName() + "Details.jspa";
}
public boolean isChecked(String value)
{
if (getActions() == null || getActions().length == 0)
{
// If there were no actions submitted we are either being invoked with no check boxes checked
// (which should be OK, as there is nothing to validate), or we are coming from the later stage of
// the wizard. In this case we should look into BulkEditBean
if (getBulkEditBean().getActions() != null)
{
return getBulkEditBean().getActions().containsKey(value);
}
return false;
}
else
{
// If we have check boxes (actions) submitted use them
for (int i = 0; i < getActions().length; i++)
{
String action = getActions()[i];
if (action.equals(value))
return true;
}
return false;
}
}
}
|
24550_15 | package volvis;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.awt.AWTTextureIO;
import gui.MIPRendererPanel;
import gui.RaycastRendererPanel;
import gui.TransferFunctionEditor;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javafx.util.Pair;
import javax.media.opengl.GL2;
import util.TFChangeListener;
import util.VectorMath;
import volume.Volume;
/**
*
* @author Mart
*/
public class OpacityRenderer extends Renderer implements TFChangeListener {
private Volume volume = null;
MIPRendererPanel panel;
TransferFunction tFunc;
TransferFunctionEditor tfEditor;
int count = 0;
public OpacityRenderer(Visualization vis) {
panel = new MIPRendererPanel(this, vis);
panel.setSpeedLabel("0");
}
public void setVolume(Volume vol) {
volume = vol;
System.out.println(vol.getMaximum() + " " + vol.getMinimum());
// set up image for storing the resulting rendering
// the image width and height are equal to the length of the volume diagonal
int imageSize = (int) Math.floor(Math.sqrt(vol.getDimX() * vol.getDimX() + vol.getDimY() * vol.getDimY()
+ vol.getDimZ() * vol.getDimZ()));
if (imageSize % 2 != 0) {
imageSize = imageSize + 1;
}
image = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB);
tFunc = new TransferFunction(volume.getMinimum(), volume.getMaximum());
tFunc.addTFChangeListener(this);
tfEditor = new TransferFunctionEditor(tFunc, volume.getHistogram(), true);
panel.setTransferFunctionEditor(tfEditor);
}
@Override
public void changed() {
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).changed();
}
}
public MIPRendererPanel getPanel() {
return panel;
}
short[] getVoxels(double[] coord, double[] vector) {
double xZeroAt, yZeroAt, zZeroAt;
double xMaxAt, yMaxAt, zMaxAt;
if (vector[0] >= 0) {
xZeroAt = -coord[0] / vector[0];
xMaxAt = (volume.getDimX() - coord[0]) / vector[0];
} else {
xZeroAt = (volume.getDimX() - coord[0]) / vector[0];
xMaxAt = -coord[0] / vector[0];
}
if (vector[1] >= 0) {
yZeroAt = -coord[1] / vector[1];
yMaxAt = (volume.getDimY() - coord[1]) / vector[1];
} else {
yZeroAt = (volume.getDimY() - coord[1]) / vector[1];
yMaxAt = -coord[1] / vector[1];
}
if (vector[2] >= 0) {
zZeroAt = -coord[2] / vector[2];
zMaxAt = (volume.getDimZ() - coord[2]) / vector[2];
} else {
zZeroAt = (volume.getDimZ() - coord[2]) / vector[2];
zMaxAt = -coord[2] / vector[2];
}
xZeroAt = vector[0] == 0 ? -Double.MAX_VALUE : xZeroAt;
yZeroAt = vector[1] == 0 ? -Double.MAX_VALUE : yZeroAt;
zZeroAt = vector[2] == 0 ? -Double.MAX_VALUE : zZeroAt;
xMaxAt = vector[0] == 0 ? Double.MAX_VALUE : xMaxAt;
yMaxAt = vector[1] == 0 ? Double.MAX_VALUE : yMaxAt;
zMaxAt = vector[2] == 0 ? Double.MAX_VALUE : zMaxAt;
double start = Math.max(Math.max(xZeroAt, yZeroAt), zZeroAt);
double end = Math.min(Math.min(xMaxAt, yMaxAt), zMaxAt);
int slices = Integer.parseInt(panel.Samples.getValue().toString());
double length = end - start;
double diff = (length / (slices - 1));
short[] fuckDezeShit = new short[slices];
for (double i = 0; i < slices; i++) {
int x = (int) Math.round((double) coord[0] + (double) vector[0] * ((double) start + (double) diff * i));
int y = (int) Math.round((double) coord[1] + (double) vector[1] * ((double) start + (double) diff * i));
int z = (int) Math.round((double) coord[2] + (double) vector[2] * ((double) start + (double) diff * i));
fuckDezeShit[(int) i] = ((x >= 0) && (x < volume.getDimX()) && (y >= 0) && (y < volume.getDimY())
&& (z >= 0) && (z < volume.getDimZ())) ? volume.getVoxel(x, y, z) : 0;
}
return fuckDezeShit;
}
double[] getRayColor(double[] coord, double[] vector) {
double xZeroAt, yZeroAt, zZeroAt;
double xMaxAt, yMaxAt, zMaxAt;
if (vector[0] >= 0) {
xZeroAt = -coord[0] / vector[0];
xMaxAt = (volume.getDimX() - coord[0]) / vector[0];
} else {
xZeroAt = (volume.getDimX() - coord[0]) / vector[0];
xMaxAt = -coord[0] / vector[0];
}
if (vector[1] >= 0) {
yZeroAt = -coord[1] / vector[1];
yMaxAt = (volume.getDimY() - coord[1]) / vector[1];
} else {
yZeroAt = (volume.getDimY() - coord[1]) / vector[1];
yMaxAt = -coord[1] / vector[1];
}
if (vector[2] >= 0) {
zZeroAt = -coord[2] / vector[2];
zMaxAt = (volume.getDimZ() - coord[2]) / vector[2];
} else {
zZeroAt = (volume.getDimZ() - coord[2]) / vector[2];
zMaxAt = -coord[2] / vector[2];
}
xZeroAt = vector[0] == 0 ? -Double.MAX_VALUE : xZeroAt;
yZeroAt = vector[1] == 0 ? -Double.MAX_VALUE : yZeroAt;
zZeroAt = vector[2] == 0 ? -Double.MAX_VALUE : zZeroAt;
xMaxAt = vector[0] == 0 ? Double.MAX_VALUE : xMaxAt;
yMaxAt = vector[1] == 0 ? Double.MAX_VALUE : yMaxAt;
zMaxAt = vector[2] == 0 ? Double.MAX_VALUE : zMaxAt;
double start = Math.max(Math.max(xZeroAt, yZeroAt), zZeroAt);
double end = Math.min(Math.min(xMaxAt, yMaxAt), zMaxAt);
int slices = Integer.parseInt(panel.Samples.getValue().toString());
double length = end - start;
double diff = (length / (slices - 1));
double c_red, c_green, c_blue;
c_red = c_green = c_blue = 0;
ArrayList<TransferFunction.ControlPoint> controlPoints = tFunc.getControlPoints();
Region[] regions = new Region[(controlPoints.size() - 1) / 2];
// if(++count % 10000 == 0){
// System.out.println(controlPoints.size());
// count = 0;
//
// }
int at = 0;
if (regions.length > 1) {
for (int i = 1; i < controlPoints.size(); i += 2) {
regions[at++] = new Region(controlPoints.get(i).value, controlPoints.get(i).color.a);
}
}
// for (double i = slices - 1; i >= 0; i--) {
for (double i = 0; i < slices; i++) {
int x = (int) Math.round((double) coord[0] + (double) vector[0] * ((double) start + (double) diff * i));
// int xp = (int) Math.round((double) coord[0] + (double) vector[0] * ((double) start + (double) diff * (i-1)));
// int xn = (int) Math.round((double) coord[0] + (double) vector[0] * ((double) start + (double) diff * (i+1)));
int y = (int) Math.round((double) coord[1] + (double) vector[1] * ((double) start + (double) diff * i));
// int yp = (int) Math.round((double) coord[1] + (double) vector[1] * ((double) start + (double) diff * (i-1)));
// int yn = (int) Math.round((double) coord[1] + (double) vector[1] * ((double) start + (double) diff * (i+1)));
int z = (int) Math.round((double) coord[2] + (double) vector[2] * ((double) start + (double) diff * i));
// int zp = (int) Math.round((double) coord[2] + (double) vector[2] * ((double) start + (double) diff * (i-1)));
// int zn = (int) Math.round((double) coord[2] + (double) vector[2] * ((double) start + (double) diff * (i+1)));
short fxi = getVoxel(x, y, z);
TFColor voxelColor = tFunc.getColor(fxi);
double[] dfxi = new double[]{
0.5 * (getVoxel(x - 1, y, z) - getVoxel(x + 1, y, z)),
0.5 * (getVoxel(x, y - 1, z) - getVoxel(x, y + 1, z)),
0.5 * (getVoxel(x, y, z - 1) - getVoxel(x, y, z + 1))
};
double dfxil = VectorMath.length(dfxi);
double a = 0;
if (regions.length >= 2) {
for (int v = 0; v < regions.length - 1; v++) {
if (!(regions[v].v <= fxi && fxi <= regions[v + 1].v)) {
continue;
}
double an = regions[v].a;
double anp1 = regions[v + 1].a;
a += anp1 * (fxi - regions[v].v);
a += an * (regions[v + 1].v - fxi);
a /= (regions[v + 1].v - regions[v].v);
a *= dfxil / tFunc.num;
// a *= voxelColor.a;
break;
}
}
if (a == 0) {
continue;
}
double ai = 1 - a;
//c_alpha = ai * c_alpha + (voxelColor.a <= 1.0 ? voxelColor.a : 1) * a;
c_red = ai * c_red + (voxelColor.r <= 1.0 ? voxelColor.r : 1) * a;
c_green = ai * c_green + (voxelColor.g <= 1.0 ? voxelColor.g : 1) * a;
c_blue = ai * c_blue + (voxelColor.b <= 1.0 ? voxelColor.b : 1) * a;
}
return new double[]{c_red, c_green, c_blue};
}
short getVoxel(int x, int y, int z) {
if ((x >= 0) && (x < volume.getDimX()) && (y >= 0) && (y < volume.getDimY())
&& (z >= 0) && (z < volume.getDimZ())) {
return volume.getVoxel(x, y, z);
} else {
return 0;
}
}
// get a voxel from the volume data by nearest neighbor interpolation
short getVoxel(double[] coord) {
// Lijkt me dat hier iets moet gebeuren om alle voxels te selecteren ofzo
int x = (int) Math.round(coord[0]);
int y = (int) Math.round(coord[1]);
int z = (int) Math.round(coord[2]);
if ((x >= 0) && (x < volume.getDimX()) && (y >= 0) && (y < volume.getDimY())
&& (z >= 0) && (z < volume.getDimZ())) {
return volume.getVoxel(x, y, z);
} else {
return 0;
}
}
void slicer(double[] viewMatrix) {
// clear image
for (int j = 0; j < image.getHeight(); j++) {
for (int i = 0; i < image.getWidth(); i++) {
image.setRGB(i, j, 0);
}
}
// vector uVec and vVec define a plane through the origin,
// perpendicular to the view vector viewVec
double[] viewVec = new double[3];
double[] uVec = new double[3];
double[] vVec = new double[3];
VectorMath.setVector(viewVec, viewMatrix[2], viewMatrix[6], viewMatrix[10]);
VectorMath.setVector(uVec, viewMatrix[0], viewMatrix[4], viewMatrix[8]);
VectorMath.setVector(vVec, viewMatrix[1], viewMatrix[5], viewMatrix[9]);
// image is square
int imageCenter = image.getWidth() / 2;
double[] pixelCoord = new double[3];
double[] volumeCenter = new double[3];
VectorMath.setVector(volumeCenter, volume.getDimX() / 2, volume.getDimY() / 2, volume.getDimZ() / 2);
// sample on a plane through the origin of the volume data
// double max = volume.getMaximum();
for (int j = 0; j < image.getHeight(); j++) {
for (int i = 0; i < image.getWidth(); i++) {
pixelCoord[0] = uVec[0] * (i - imageCenter) + vVec[0] * (j - imageCenter)
+ volumeCenter[0];
pixelCoord[1] = uVec[1] * (i - imageCenter) + vVec[1] * (j - imageCenter)
+ volumeCenter[1];
pixelCoord[2] = uVec[2] * (i - imageCenter) + vVec[2] * (j - imageCenter)
+ volumeCenter[2];
// int val = getVoxel(pixelCoord);
double[] blub = getRayColor(pixelCoord, viewVec);
int red = (int) Math.round(blub[0] * 255);
int blue = (int) Math.round(blub[2] * 255);
int green = (int) Math.round(blub[1] * 255);
// (c_alpha << 24) |
int pixelColor = (254 << 24) | (red << 16) | (green << 8) | blue;
image.setRGB(i, j, pixelColor);
}
}
}
private void drawBoundingBox(GL2 gl) {
gl.glPushAttrib(GL2.GL_CURRENT_BIT);
gl.glDisable(GL2.GL_LIGHTING);
gl.glColor4d(1.0, 1.0, 1.0, 1.0);
gl.glLineWidth(1.5f);
gl.glEnable(GL2.GL_LINE_SMOOTH);
gl.glHint(GL2.GL_LINE_SMOOTH_HINT, GL2.GL_NICEST);
gl.glEnable(GL2.GL_BLEND);
gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA);
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glEnd();
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glEnd();
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glEnd();
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glEnd();
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glEnd();
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glEnd();
gl.glDisable(GL2.GL_LINE_SMOOTH);
gl.glDisable(GL2.GL_BLEND);
gl.glEnable(GL2.GL_LIGHTING);
gl.glPopAttrib();
}
@Override
public void visualize(GL2 gl) {
if (volume == null) {
return;
}
drawBoundingBox(gl);
gl.glGetDoublev(GL2.GL_MODELVIEW_MATRIX, viewMatrix, 0);
long startTime = System.currentTimeMillis();
slicer(viewMatrix);
long endTime = System.currentTimeMillis();
double runningTime = (endTime - startTime);
panel.setSpeedLabel(Double.toString(runningTime));
Texture texture = AWTTextureIO.newTexture(gl.getGLProfile(), image, false);
gl.glPushAttrib(GL2.GL_LIGHTING_BIT);
gl.glDisable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_BLEND);
gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA);
// draw rendered image as a billboard texture
texture.enable(gl);
texture.bind(gl);
double halfWidth = image.getWidth() / 2.0;
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glBegin(GL2.GL_QUADS);
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
gl.glTexCoord2d(0.0, 0.0);
gl.glVertex3d(-halfWidth, -halfWidth, 0.0);
gl.glTexCoord2d(0.0, 1.0);
gl.glVertex3d(-halfWidth, halfWidth, 0.0);
gl.glTexCoord2d(1.0, 1.0);
gl.glVertex3d(halfWidth, halfWidth, 0.0);
gl.glTexCoord2d(1.0, 0.0);
gl.glVertex3d(halfWidth, -halfWidth, 0.0);
gl.glEnd();
texture.disable(gl);
texture.destroy(gl);
gl.glPopMatrix();
gl.glPopAttrib();
if (gl.glGetError() > 0) {
System.out.println("some OpenGL error: " + gl.glGetError());
}
}
private BufferedImage image;
private double[] viewMatrix = new double[4 * 4];
private static class Region {
public double v;
public double a;
public Region(double v, double a) {
this.v = v;
this.a = a;
}
}
}
| tuupke/2IV35-VolVis | VolVis/src/volvis/OpacityRenderer.java | 6,431 | // Lijkt me dat hier iets moet gebeuren om alle voxels te selecteren ofzo | line_comment | nl | package volvis;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.awt.AWTTextureIO;
import gui.MIPRendererPanel;
import gui.RaycastRendererPanel;
import gui.TransferFunctionEditor;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javafx.util.Pair;
import javax.media.opengl.GL2;
import util.TFChangeListener;
import util.VectorMath;
import volume.Volume;
/**
*
* @author Mart
*/
public class OpacityRenderer extends Renderer implements TFChangeListener {
private Volume volume = null;
MIPRendererPanel panel;
TransferFunction tFunc;
TransferFunctionEditor tfEditor;
int count = 0;
public OpacityRenderer(Visualization vis) {
panel = new MIPRendererPanel(this, vis);
panel.setSpeedLabel("0");
}
public void setVolume(Volume vol) {
volume = vol;
System.out.println(vol.getMaximum() + " " + vol.getMinimum());
// set up image for storing the resulting rendering
// the image width and height are equal to the length of the volume diagonal
int imageSize = (int) Math.floor(Math.sqrt(vol.getDimX() * vol.getDimX() + vol.getDimY() * vol.getDimY()
+ vol.getDimZ() * vol.getDimZ()));
if (imageSize % 2 != 0) {
imageSize = imageSize + 1;
}
image = new BufferedImage(imageSize, imageSize, BufferedImage.TYPE_INT_ARGB);
tFunc = new TransferFunction(volume.getMinimum(), volume.getMaximum());
tFunc.addTFChangeListener(this);
tfEditor = new TransferFunctionEditor(tFunc, volume.getHistogram(), true);
panel.setTransferFunctionEditor(tfEditor);
}
@Override
public void changed() {
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).changed();
}
}
public MIPRendererPanel getPanel() {
return panel;
}
short[] getVoxels(double[] coord, double[] vector) {
double xZeroAt, yZeroAt, zZeroAt;
double xMaxAt, yMaxAt, zMaxAt;
if (vector[0] >= 0) {
xZeroAt = -coord[0] / vector[0];
xMaxAt = (volume.getDimX() - coord[0]) / vector[0];
} else {
xZeroAt = (volume.getDimX() - coord[0]) / vector[0];
xMaxAt = -coord[0] / vector[0];
}
if (vector[1] >= 0) {
yZeroAt = -coord[1] / vector[1];
yMaxAt = (volume.getDimY() - coord[1]) / vector[1];
} else {
yZeroAt = (volume.getDimY() - coord[1]) / vector[1];
yMaxAt = -coord[1] / vector[1];
}
if (vector[2] >= 0) {
zZeroAt = -coord[2] / vector[2];
zMaxAt = (volume.getDimZ() - coord[2]) / vector[2];
} else {
zZeroAt = (volume.getDimZ() - coord[2]) / vector[2];
zMaxAt = -coord[2] / vector[2];
}
xZeroAt = vector[0] == 0 ? -Double.MAX_VALUE : xZeroAt;
yZeroAt = vector[1] == 0 ? -Double.MAX_VALUE : yZeroAt;
zZeroAt = vector[2] == 0 ? -Double.MAX_VALUE : zZeroAt;
xMaxAt = vector[0] == 0 ? Double.MAX_VALUE : xMaxAt;
yMaxAt = vector[1] == 0 ? Double.MAX_VALUE : yMaxAt;
zMaxAt = vector[2] == 0 ? Double.MAX_VALUE : zMaxAt;
double start = Math.max(Math.max(xZeroAt, yZeroAt), zZeroAt);
double end = Math.min(Math.min(xMaxAt, yMaxAt), zMaxAt);
int slices = Integer.parseInt(panel.Samples.getValue().toString());
double length = end - start;
double diff = (length / (slices - 1));
short[] fuckDezeShit = new short[slices];
for (double i = 0; i < slices; i++) {
int x = (int) Math.round((double) coord[0] + (double) vector[0] * ((double) start + (double) diff * i));
int y = (int) Math.round((double) coord[1] + (double) vector[1] * ((double) start + (double) diff * i));
int z = (int) Math.round((double) coord[2] + (double) vector[2] * ((double) start + (double) diff * i));
fuckDezeShit[(int) i] = ((x >= 0) && (x < volume.getDimX()) && (y >= 0) && (y < volume.getDimY())
&& (z >= 0) && (z < volume.getDimZ())) ? volume.getVoxel(x, y, z) : 0;
}
return fuckDezeShit;
}
double[] getRayColor(double[] coord, double[] vector) {
double xZeroAt, yZeroAt, zZeroAt;
double xMaxAt, yMaxAt, zMaxAt;
if (vector[0] >= 0) {
xZeroAt = -coord[0] / vector[0];
xMaxAt = (volume.getDimX() - coord[0]) / vector[0];
} else {
xZeroAt = (volume.getDimX() - coord[0]) / vector[0];
xMaxAt = -coord[0] / vector[0];
}
if (vector[1] >= 0) {
yZeroAt = -coord[1] / vector[1];
yMaxAt = (volume.getDimY() - coord[1]) / vector[1];
} else {
yZeroAt = (volume.getDimY() - coord[1]) / vector[1];
yMaxAt = -coord[1] / vector[1];
}
if (vector[2] >= 0) {
zZeroAt = -coord[2] / vector[2];
zMaxAt = (volume.getDimZ() - coord[2]) / vector[2];
} else {
zZeroAt = (volume.getDimZ() - coord[2]) / vector[2];
zMaxAt = -coord[2] / vector[2];
}
xZeroAt = vector[0] == 0 ? -Double.MAX_VALUE : xZeroAt;
yZeroAt = vector[1] == 0 ? -Double.MAX_VALUE : yZeroAt;
zZeroAt = vector[2] == 0 ? -Double.MAX_VALUE : zZeroAt;
xMaxAt = vector[0] == 0 ? Double.MAX_VALUE : xMaxAt;
yMaxAt = vector[1] == 0 ? Double.MAX_VALUE : yMaxAt;
zMaxAt = vector[2] == 0 ? Double.MAX_VALUE : zMaxAt;
double start = Math.max(Math.max(xZeroAt, yZeroAt), zZeroAt);
double end = Math.min(Math.min(xMaxAt, yMaxAt), zMaxAt);
int slices = Integer.parseInt(panel.Samples.getValue().toString());
double length = end - start;
double diff = (length / (slices - 1));
double c_red, c_green, c_blue;
c_red = c_green = c_blue = 0;
ArrayList<TransferFunction.ControlPoint> controlPoints = tFunc.getControlPoints();
Region[] regions = new Region[(controlPoints.size() - 1) / 2];
// if(++count % 10000 == 0){
// System.out.println(controlPoints.size());
// count = 0;
//
// }
int at = 0;
if (regions.length > 1) {
for (int i = 1; i < controlPoints.size(); i += 2) {
regions[at++] = new Region(controlPoints.get(i).value, controlPoints.get(i).color.a);
}
}
// for (double i = slices - 1; i >= 0; i--) {
for (double i = 0; i < slices; i++) {
int x = (int) Math.round((double) coord[0] + (double) vector[0] * ((double) start + (double) diff * i));
// int xp = (int) Math.round((double) coord[0] + (double) vector[0] * ((double) start + (double) diff * (i-1)));
// int xn = (int) Math.round((double) coord[0] + (double) vector[0] * ((double) start + (double) diff * (i+1)));
int y = (int) Math.round((double) coord[1] + (double) vector[1] * ((double) start + (double) diff * i));
// int yp = (int) Math.round((double) coord[1] + (double) vector[1] * ((double) start + (double) diff * (i-1)));
// int yn = (int) Math.round((double) coord[1] + (double) vector[1] * ((double) start + (double) diff * (i+1)));
int z = (int) Math.round((double) coord[2] + (double) vector[2] * ((double) start + (double) diff * i));
// int zp = (int) Math.round((double) coord[2] + (double) vector[2] * ((double) start + (double) diff * (i-1)));
// int zn = (int) Math.round((double) coord[2] + (double) vector[2] * ((double) start + (double) diff * (i+1)));
short fxi = getVoxel(x, y, z);
TFColor voxelColor = tFunc.getColor(fxi);
double[] dfxi = new double[]{
0.5 * (getVoxel(x - 1, y, z) - getVoxel(x + 1, y, z)),
0.5 * (getVoxel(x, y - 1, z) - getVoxel(x, y + 1, z)),
0.5 * (getVoxel(x, y, z - 1) - getVoxel(x, y, z + 1))
};
double dfxil = VectorMath.length(dfxi);
double a = 0;
if (regions.length >= 2) {
for (int v = 0; v < regions.length - 1; v++) {
if (!(regions[v].v <= fxi && fxi <= regions[v + 1].v)) {
continue;
}
double an = regions[v].a;
double anp1 = regions[v + 1].a;
a += anp1 * (fxi - regions[v].v);
a += an * (regions[v + 1].v - fxi);
a /= (regions[v + 1].v - regions[v].v);
a *= dfxil / tFunc.num;
// a *= voxelColor.a;
break;
}
}
if (a == 0) {
continue;
}
double ai = 1 - a;
//c_alpha = ai * c_alpha + (voxelColor.a <= 1.0 ? voxelColor.a : 1) * a;
c_red = ai * c_red + (voxelColor.r <= 1.0 ? voxelColor.r : 1) * a;
c_green = ai * c_green + (voxelColor.g <= 1.0 ? voxelColor.g : 1) * a;
c_blue = ai * c_blue + (voxelColor.b <= 1.0 ? voxelColor.b : 1) * a;
}
return new double[]{c_red, c_green, c_blue};
}
short getVoxel(int x, int y, int z) {
if ((x >= 0) && (x < volume.getDimX()) && (y >= 0) && (y < volume.getDimY())
&& (z >= 0) && (z < volume.getDimZ())) {
return volume.getVoxel(x, y, z);
} else {
return 0;
}
}
// get a voxel from the volume data by nearest neighbor interpolation
short getVoxel(double[] coord) {
// Lijkt me<SUF>
int x = (int) Math.round(coord[0]);
int y = (int) Math.round(coord[1]);
int z = (int) Math.round(coord[2]);
if ((x >= 0) && (x < volume.getDimX()) && (y >= 0) && (y < volume.getDimY())
&& (z >= 0) && (z < volume.getDimZ())) {
return volume.getVoxel(x, y, z);
} else {
return 0;
}
}
void slicer(double[] viewMatrix) {
// clear image
for (int j = 0; j < image.getHeight(); j++) {
for (int i = 0; i < image.getWidth(); i++) {
image.setRGB(i, j, 0);
}
}
// vector uVec and vVec define a plane through the origin,
// perpendicular to the view vector viewVec
double[] viewVec = new double[3];
double[] uVec = new double[3];
double[] vVec = new double[3];
VectorMath.setVector(viewVec, viewMatrix[2], viewMatrix[6], viewMatrix[10]);
VectorMath.setVector(uVec, viewMatrix[0], viewMatrix[4], viewMatrix[8]);
VectorMath.setVector(vVec, viewMatrix[1], viewMatrix[5], viewMatrix[9]);
// image is square
int imageCenter = image.getWidth() / 2;
double[] pixelCoord = new double[3];
double[] volumeCenter = new double[3];
VectorMath.setVector(volumeCenter, volume.getDimX() / 2, volume.getDimY() / 2, volume.getDimZ() / 2);
// sample on a plane through the origin of the volume data
// double max = volume.getMaximum();
for (int j = 0; j < image.getHeight(); j++) {
for (int i = 0; i < image.getWidth(); i++) {
pixelCoord[0] = uVec[0] * (i - imageCenter) + vVec[0] * (j - imageCenter)
+ volumeCenter[0];
pixelCoord[1] = uVec[1] * (i - imageCenter) + vVec[1] * (j - imageCenter)
+ volumeCenter[1];
pixelCoord[2] = uVec[2] * (i - imageCenter) + vVec[2] * (j - imageCenter)
+ volumeCenter[2];
// int val = getVoxel(pixelCoord);
double[] blub = getRayColor(pixelCoord, viewVec);
int red = (int) Math.round(blub[0] * 255);
int blue = (int) Math.round(blub[2] * 255);
int green = (int) Math.round(blub[1] * 255);
// (c_alpha << 24) |
int pixelColor = (254 << 24) | (red << 16) | (green << 8) | blue;
image.setRGB(i, j, pixelColor);
}
}
}
private void drawBoundingBox(GL2 gl) {
gl.glPushAttrib(GL2.GL_CURRENT_BIT);
gl.glDisable(GL2.GL_LIGHTING);
gl.glColor4d(1.0, 1.0, 1.0, 1.0);
gl.glLineWidth(1.5f);
gl.glEnable(GL2.GL_LINE_SMOOTH);
gl.glHint(GL2.GL_LINE_SMOOTH_HINT, GL2.GL_NICEST);
gl.glEnable(GL2.GL_BLEND);
gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA);
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glEnd();
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glEnd();
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glEnd();
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glEnd();
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glEnd();
gl.glBegin(GL2.GL_LINE_LOOP);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glVertex3d(-volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, volume.getDimZ() / 2.0);
gl.glVertex3d(volume.getDimX() / 2.0, -volume.getDimY() / 2.0, -volume.getDimZ() / 2.0);
gl.glEnd();
gl.glDisable(GL2.GL_LINE_SMOOTH);
gl.glDisable(GL2.GL_BLEND);
gl.glEnable(GL2.GL_LIGHTING);
gl.glPopAttrib();
}
@Override
public void visualize(GL2 gl) {
if (volume == null) {
return;
}
drawBoundingBox(gl);
gl.glGetDoublev(GL2.GL_MODELVIEW_MATRIX, viewMatrix, 0);
long startTime = System.currentTimeMillis();
slicer(viewMatrix);
long endTime = System.currentTimeMillis();
double runningTime = (endTime - startTime);
panel.setSpeedLabel(Double.toString(runningTime));
Texture texture = AWTTextureIO.newTexture(gl.getGLProfile(), image, false);
gl.glPushAttrib(GL2.GL_LIGHTING_BIT);
gl.glDisable(GL2.GL_LIGHTING);
gl.glEnable(GL2.GL_BLEND);
gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA);
// draw rendered image as a billboard texture
texture.enable(gl);
texture.bind(gl);
double halfWidth = image.getWidth() / 2.0;
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glBegin(GL2.GL_QUADS);
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
gl.glTexCoord2d(0.0, 0.0);
gl.glVertex3d(-halfWidth, -halfWidth, 0.0);
gl.glTexCoord2d(0.0, 1.0);
gl.glVertex3d(-halfWidth, halfWidth, 0.0);
gl.glTexCoord2d(1.0, 1.0);
gl.glVertex3d(halfWidth, halfWidth, 0.0);
gl.glTexCoord2d(1.0, 0.0);
gl.glVertex3d(halfWidth, -halfWidth, 0.0);
gl.glEnd();
texture.disable(gl);
texture.destroy(gl);
gl.glPopMatrix();
gl.glPopAttrib();
if (gl.glGetError() > 0) {
System.out.println("some OpenGL error: " + gl.glGetError());
}
}
private BufferedImage image;
private double[] viewMatrix = new double[4 * 4];
private static class Region {
public double v;
public double a;
public Region(double v, double a) {
this.v = v;
this.a = a;
}
}
}
|
169859_1 | /**
*
* Copyright 2012-2017 TNO Geologische Dienst Nederland
*
* Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
* the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*
* This work was sponsored by the Dutch Rijksoverheid, Basisregistratie
* Ondergrond (BRO) Programme (https://bro.pleio.nl/)
*/
package nl.bro.cpt.gef.main;
import static org.fest.assertions.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import nl.bro.cpt.gef.main.util.TestHandler;
public class ConverGefTest {
@Before
public void init() {
TestHandler.LOG_RECORDS.clear();
}
@After
public void cleanup() {
TestHandler.LOG_RECORDS.clear();
}
private List<String> getMessages() {
List<String> messages = new ArrayList<>();
for ( LogRecord record : TestHandler.LOG_RECORDS ) {
messages.add( record.getMessage() );
}
return messages;
}
@Test
public void testNoArguments() {
// -- action
ConvertGef.main( new String[0] );
// -- verify
List<String> messages = getMessages();
assertThat( messages ).contains( "Missing t option", "Missing r option", "Missing q option" );
}
@Test
public void testNonExistingFile() {
ConvertGef.main( new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "TEST.GEF" } );
List<String> messages = getMessages();
assertThat( messages.toString() ).contains( "kan niet gevonden worden" );
}
/**
* Ignore tot dat filenaam probleem is opgelost
*/
@Test
@Ignore
public void testNormal() {
ConvertGef.main(
new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "-d", "target", "src/test/resources/CPT-F3b-i3-23913-completion-CPT.GEF",
"src/test/resources/CPT-F3b-i3-23913-completion-DISS.GEF" } );
}
}
| tvcstseng/CPT_GEF_CONVERTER | gef_standalone/src/test/java/nl/bro/cpt/gef/main/ConverGefTest.java | 795 | /**
* Ignore tot dat filenaam probleem is opgelost
*/ | block_comment | nl | /**
*
* Copyright 2012-2017 TNO Geologische Dienst Nederland
*
* Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
* the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* https://joinup.ec.europa.eu/software/page/eupl
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*
* This work was sponsored by the Dutch Rijksoverheid, Basisregistratie
* Ondergrond (BRO) Programme (https://bro.pleio.nl/)
*/
package nl.bro.cpt.gef.main;
import static org.fest.assertions.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.LogRecord;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import nl.bro.cpt.gef.main.util.TestHandler;
public class ConverGefTest {
@Before
public void init() {
TestHandler.LOG_RECORDS.clear();
}
@After
public void cleanup() {
TestHandler.LOG_RECORDS.clear();
}
private List<String> getMessages() {
List<String> messages = new ArrayList<>();
for ( LogRecord record : TestHandler.LOG_RECORDS ) {
messages.add( record.getMessage() );
}
return messages;
}
@Test
public void testNoArguments() {
// -- action
ConvertGef.main( new String[0] );
// -- verify
List<String> messages = getMessages();
assertThat( messages ).contains( "Missing t option", "Missing r option", "Missing q option" );
}
@Test
public void testNonExistingFile() {
ConvertGef.main( new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "TEST.GEF" } );
List<String> messages = getMessages();
assertThat( messages.toString() ).contains( "kan niet gevonden worden" );
}
/**
* Ignore tot dat<SUF>*/
@Test
@Ignore
public void testNormal() {
ConvertGef.main(
new String[] { "-r", "test", "-t", "R", "-q", "IMBRO", "-d", "target", "src/test/resources/CPT-F3b-i3-23913-completion-CPT.GEF",
"src/test/resources/CPT-F3b-i3-23913-completion-DISS.GEF" } );
}
}
|
7893_4 | package teun.demo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import teun.demo.domain.Exercise;
import teun.demo.domain.ExerciseFact;
import teun.demo.domain.User;
import teun.demo.repository.ExerciseFactRepository;
import teun.demo.repository.ExerciseRepository;
import teun.demo.repository.UserRepository;
import java.util.*;
@Slf4j
@SessionAttributes({"selectedUser", "selectedCategory", "selectedSubCategory", "selectedExercise"})
@Controller
@RequestMapping("/exercise")
public class ExerciseFactController {
private ExerciseFactRepository exerciseFactRepository;
private ExerciseRepository exerciseRepository;
private UserRepository userRepository;
@Autowired
public ExerciseFactController(ExerciseFactRepository exerciseFactRepo,
ExerciseRepository exerciseRepo,
UserRepository userRepo) {
this.exerciseFactRepository = exerciseFactRepo;
this.exerciseRepository = exerciseRepo;
this.userRepository = userRepo;
}
@GetMapping("/{id}/categories")
public String showCat(@PathVariable long id, Model model) {
log.info("/{id}/categories");
log.info("changed selectedUser to PathVariable");
model.addAttribute("selectedUser", this.userRepository.findById(id).get());
printModelContent(model.asMap());
return "showCategories";
}
@GetMapping("/{id}/{category}")
public String showSubcat(@PathVariable long id,
@PathVariable String category,
Model model) {
log.info("/{id}/{category}");
log.info(category);
Collection<String> subCategories = this.exerciseRepository.findSubCategoriesByCategory(category);
log.info(subCategories.toString());
model.addAttribute("subCategories", subCategories);
log.info("changed subCategories to PathVariable");
printModelContent(model.asMap());
return "showSubcategories";
}
@GetMapping("/{id}/{category}/{subCat}")
public String showExercise1(@PathVariable long id,
@PathVariable String category,
@PathVariable String subCat,
Model model) {
log.info("/{id}/{category}/{subCat}");
log.info("dit is je geselecteerde category: " + category);
log.info("dit is je geselecteerde subcat: " + subCat);
List<Exercise> exercises = this.exerciseRepository.findExercisesBySubCategory(subCat);
log.info("dit zijn je exercises: " + exercises.toString());
model.addAttribute("category", category);
model.addAttribute("exercises", exercises);
log.info("changed category to PathVariable");
log.info("changed exercises to PathVariable");
printModelContent(model.asMap());
System.out.println("hello");
return "showExercises";
}
@GetMapping("/{exerciseId}")
public String exerciseFormInput(@PathVariable long exerciseId, Model model) {
log.info("/{exerciseId}/{userId}");
//log.info("id of user " +userId);
//User selectedUser = this.userRepository.findById(userId).get();
Exercise exercise = this.exerciseRepository.findById(exerciseId).get();
log.info("gekozen exercise: " + exercise.toString() + " met id: " + exercise.getId());
//model.addAttribute("selectedUser",selectedUser);
model.addAttribute("selectedExercise", exercise);
printModelContent(model.asMap());
return "exerciseForm";
}
@PostMapping("/newFact")
public String ProcessNewFact(@ModelAttribute ExerciseFact exerciseFact, Model model) {
// deze user wordt niet goed geset. Kan blijkbaar niet op basis van transient dingen?
// waarom wordt date ook niet goed gebruikt?
// exercise gaat ook niet naar het goede
// en waarom is de id nog niet gegenerate?
log.info("/newFact");
log.info("class van exerciseFact is " + exerciseFact.getClass());
exerciseFact.setUser((User) model.getAttribute("selectedUser"));
exerciseFact.setExercise((Exercise) model.getAttribute("selectedExercise"));
exerciseFactRepository.insertNewExerciseFactUserIdExerciseIdScore(
exerciseFact.getUser().getId(),
exerciseFact.getExercise().getId(),
exerciseFact.getScore());
printModelContent(model.asMap());
log.info(exerciseFact.toString());
return "exerciseForm";
}
// ModelAttributes
@ModelAttribute(name = "exercise")
public Exercise findExercise() {
return new Exercise();
}
@ModelAttribute(name = "categories")
public Set<String> showCategories() {
log.info("Put categories in Model");
Set<String> categories = new HashSet<>();
this.exerciseRepository.findAll().forEach(x -> categories.add(x.getCategory().toLowerCase()));
return categories;
}
@ModelAttribute("selectedUser")
public User findSelectedUser() {
log.info("created new object selectedUser");
return new User();
}
@ModelAttribute("selectedExercise")
public Exercise findSelectedExercise() {
log.info("created new object selectedUser");
return new Exercise();
}
@ModelAttribute("exerciseFact")
public ExerciseFact newExerciseFact() {
return new ExerciseFact();
}
public void printModelContent(Map model) {
log.info("OBJECTS IN MODEL:");
for (Object modelObject : model.keySet()) {
log.info(modelObject + " " + model.get(modelObject));
}
log.info("EINDE");
}
}
| tvcstseng/FitnessApp3 | src/main/java/teun/demo/controller/ExerciseFactController.java | 1,590 | // exercise gaat ook niet naar het goede | line_comment | nl | package teun.demo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import teun.demo.domain.Exercise;
import teun.demo.domain.ExerciseFact;
import teun.demo.domain.User;
import teun.demo.repository.ExerciseFactRepository;
import teun.demo.repository.ExerciseRepository;
import teun.demo.repository.UserRepository;
import java.util.*;
@Slf4j
@SessionAttributes({"selectedUser", "selectedCategory", "selectedSubCategory", "selectedExercise"})
@Controller
@RequestMapping("/exercise")
public class ExerciseFactController {
private ExerciseFactRepository exerciseFactRepository;
private ExerciseRepository exerciseRepository;
private UserRepository userRepository;
@Autowired
public ExerciseFactController(ExerciseFactRepository exerciseFactRepo,
ExerciseRepository exerciseRepo,
UserRepository userRepo) {
this.exerciseFactRepository = exerciseFactRepo;
this.exerciseRepository = exerciseRepo;
this.userRepository = userRepo;
}
@GetMapping("/{id}/categories")
public String showCat(@PathVariable long id, Model model) {
log.info("/{id}/categories");
log.info("changed selectedUser to PathVariable");
model.addAttribute("selectedUser", this.userRepository.findById(id).get());
printModelContent(model.asMap());
return "showCategories";
}
@GetMapping("/{id}/{category}")
public String showSubcat(@PathVariable long id,
@PathVariable String category,
Model model) {
log.info("/{id}/{category}");
log.info(category);
Collection<String> subCategories = this.exerciseRepository.findSubCategoriesByCategory(category);
log.info(subCategories.toString());
model.addAttribute("subCategories", subCategories);
log.info("changed subCategories to PathVariable");
printModelContent(model.asMap());
return "showSubcategories";
}
@GetMapping("/{id}/{category}/{subCat}")
public String showExercise1(@PathVariable long id,
@PathVariable String category,
@PathVariable String subCat,
Model model) {
log.info("/{id}/{category}/{subCat}");
log.info("dit is je geselecteerde category: " + category);
log.info("dit is je geselecteerde subcat: " + subCat);
List<Exercise> exercises = this.exerciseRepository.findExercisesBySubCategory(subCat);
log.info("dit zijn je exercises: " + exercises.toString());
model.addAttribute("category", category);
model.addAttribute("exercises", exercises);
log.info("changed category to PathVariable");
log.info("changed exercises to PathVariable");
printModelContent(model.asMap());
System.out.println("hello");
return "showExercises";
}
@GetMapping("/{exerciseId}")
public String exerciseFormInput(@PathVariable long exerciseId, Model model) {
log.info("/{exerciseId}/{userId}");
//log.info("id of user " +userId);
//User selectedUser = this.userRepository.findById(userId).get();
Exercise exercise = this.exerciseRepository.findById(exerciseId).get();
log.info("gekozen exercise: " + exercise.toString() + " met id: " + exercise.getId());
//model.addAttribute("selectedUser",selectedUser);
model.addAttribute("selectedExercise", exercise);
printModelContent(model.asMap());
return "exerciseForm";
}
@PostMapping("/newFact")
public String ProcessNewFact(@ModelAttribute ExerciseFact exerciseFact, Model model) {
// deze user wordt niet goed geset. Kan blijkbaar niet op basis van transient dingen?
// waarom wordt date ook niet goed gebruikt?
// exercise gaat<SUF>
// en waarom is de id nog niet gegenerate?
log.info("/newFact");
log.info("class van exerciseFact is " + exerciseFact.getClass());
exerciseFact.setUser((User) model.getAttribute("selectedUser"));
exerciseFact.setExercise((Exercise) model.getAttribute("selectedExercise"));
exerciseFactRepository.insertNewExerciseFactUserIdExerciseIdScore(
exerciseFact.getUser().getId(),
exerciseFact.getExercise().getId(),
exerciseFact.getScore());
printModelContent(model.asMap());
log.info(exerciseFact.toString());
return "exerciseForm";
}
// ModelAttributes
@ModelAttribute(name = "exercise")
public Exercise findExercise() {
return new Exercise();
}
@ModelAttribute(name = "categories")
public Set<String> showCategories() {
log.info("Put categories in Model");
Set<String> categories = new HashSet<>();
this.exerciseRepository.findAll().forEach(x -> categories.add(x.getCategory().toLowerCase()));
return categories;
}
@ModelAttribute("selectedUser")
public User findSelectedUser() {
log.info("created new object selectedUser");
return new User();
}
@ModelAttribute("selectedExercise")
public Exercise findSelectedExercise() {
log.info("created new object selectedUser");
return new Exercise();
}
@ModelAttribute("exerciseFact")
public ExerciseFact newExerciseFact() {
return new ExerciseFact();
}
public void printModelContent(Map model) {
log.info("OBJECTS IN MODEL:");
for (Object modelObject : model.keySet()) {
log.info(modelObject + " " + model.get(modelObject));
}
log.info("EINDE");
}
}
|
115377_0 | /**
* Copyright 2012-2014 TNO Geologische Dienst Nederland
*
* Alle rechten voorbehouden.
* Niets uit deze software mag worden vermenigvuldigd en/of openbaar gemaakt door middel van druk, fotokopie,
* microfilm of op welke andere wijze dan ook, zonder voorafgaande toestemming van TNO.
*
* Indien deze software in opdracht werd uitgebracht, wordt voor de rechten en verplichtingen van opdrachtgever
* en opdrachtnemer verwezen naar de Algemene Voorwaarden voor opdrachten aan TNO, dan wel de betreffende
* terzake tussen de partijen gesloten overeenkomst.
*/
package com.ttstudios.pi.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
* @author T.V.C.S. Tseng
*/
public class FileReader {
private static final Logger LOG = LoggerFactory.getLogger( FileReader.class );
public FileReader() {
}
public static byte[] read(String fileName) throws IOException {
String path = FileReader.class.getClassLoader().getResource( fileName ).getFile();
File file = new File( path );
fileName = file.getName();
return FileReader.read( file );
}
private static byte[] read(File file) throws IOException {
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream( file );
int read = 0;
while ( ( read = ios.read( buffer ) ) != -1 ) {
ous.write( buffer, 0, read );
}
}
finally {
try {
if ( ous != null ) {
ous.close();
}
}
catch ( IOException e ) {
System.err.println( e.toString() );
}
try {
if ( ios != null ) {
ios.close();
}
}
catch ( IOException e ) {
LOG.error(e.toString(), e);
}
}
return ous.toByteArray();
}
public List<String> readLines(Path pathToFile) throws IOException {
Charset charset = Charset.forName( "ISO-8859-1" );
List<String> lines = null;
try {
lines = Files.readAllLines(pathToFile, charset);
}
catch(FileNotFoundException ex){
LOG.error("File not found: " + pathToFile);
}
return lines;
}
}
| tvcstseng/pi | util/src/main/java/com/ttstudios/pi/util/FileReader.java | 816 | /**
* Copyright 2012-2014 TNO Geologische Dienst Nederland
*
* Alle rechten voorbehouden.
* Niets uit deze software mag worden vermenigvuldigd en/of openbaar gemaakt door middel van druk, fotokopie,
* microfilm of op welke andere wijze dan ook, zonder voorafgaande toestemming van TNO.
*
* Indien deze software in opdracht werd uitgebracht, wordt voor de rechten en verplichtingen van opdrachtgever
* en opdrachtnemer verwezen naar de Algemene Voorwaarden voor opdrachten aan TNO, dan wel de betreffende
* terzake tussen de partijen gesloten overeenkomst.
*/ | block_comment | nl | /**
* Copyright 2012-2014 TNO<SUF>*/
package com.ttstudios.pi.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
/**
* @author T.V.C.S. Tseng
*/
public class FileReader {
private static final Logger LOG = LoggerFactory.getLogger( FileReader.class );
public FileReader() {
}
public static byte[] read(String fileName) throws IOException {
String path = FileReader.class.getClassLoader().getResource( fileName ).getFile();
File file = new File( path );
fileName = file.getName();
return FileReader.read( file );
}
private static byte[] read(File file) throws IOException {
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream( file );
int read = 0;
while ( ( read = ios.read( buffer ) ) != -1 ) {
ous.write( buffer, 0, read );
}
}
finally {
try {
if ( ous != null ) {
ous.close();
}
}
catch ( IOException e ) {
System.err.println( e.toString() );
}
try {
if ( ios != null ) {
ios.close();
}
}
catch ( IOException e ) {
LOG.error(e.toString(), e);
}
}
return ous.toByteArray();
}
public List<String> readLines(Path pathToFile) throws IOException {
Charset charset = Charset.forName( "ISO-8859-1" );
List<String> lines = null;
try {
lines = Files.readAllLines(pathToFile, charset);
}
catch(FileNotFoundException ex){
LOG.error("File not found: " + pathToFile);
}
return lines;
}
}
|
172935_2 | package language;
import java.util.ArrayList;
import java.util.List;
import language.parser.oberonLexer;
import org.antlr.runtime.tree.BaseTree;
import org.antlr.runtime.tree.Tree;
public class AstNodeCreater {
private AstNodeCreater() {}
public static AnModule createModule(BaseTree parentTree) throws Exception{
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.MODULE);
String moduleName = getIdentNameFromTree(tree);
AnContext decls = createDeclarations(tree);
List<IStatement> statementSeq = createAnStatementSequence(tree);
return new AnModule(moduleName, decls, statementSeq);
}
public static AnContext createDeclarations(BaseTree parentTree) throws Exception{
assert(parentTree != null);
BaseTree btDecls = getChildOfType(parentTree, oberonLexer.DECLARATIONS);
assert(btDecls != null);
List<AnIdentDecl> constDecls = createAnConstDelcs(btDecls, new AnEnvironment());
List<AnTypeDecl> typeDecls = createAnTypeDecls(btDecls);
List<AnIdentDecl> varDecls = createAnVarDecls(btDecls);
List<AnProcDecl> procDecls = createListOfAnProcDecl(btDecls);
AnContext ctxt = new AnContext();
ctxt.setIdents(constDecls);
ctxt.setIdents(varDecls);
ctxt.setTypes(typeDecls);
ctxt.setProcs(procDecls);
return ctxt;
}
//
public static AnProcDecl createProcDecl(BaseTree parentTree) throws Exception{
assert(parentTree != null);
BaseTree tree;
if (parentTree.getType() == oberonLexer.PROCDECL){
tree = parentTree;
} else {
tree = getChildOfType(parentTree, oberonLexer.PROCDECL);
}
//Procheader gerelateerd
BaseTree btProcHeader = getChildOfType(tree, oberonLexer.PROCHEAD);
assert(btProcHeader != null);
assert(btProcHeader.getChildCount() >= 1);
String name = getIdentNameFromTree(btProcHeader);
List<AnIdentDecl> formalParams = createAnFormalParams(btProcHeader);
//Procbody gerelateerd
BaseTree btProcBody = getChildOfType(tree, oberonLexer.PROCBODY);
assert(btProcBody != null);
AnContext ctxt = createDeclarations(btProcBody);
List<IStatement> statementSeq = createAnStatementSequence(btProcBody);
return new AnProcDecl(name, ctxt, formalParams, statementSeq);
}
//
public static List<AnProcDecl> createListOfAnProcDecl(BaseTree parentTree) throws Exception{
assert(parentTree != null);
List<BaseTree> children = getChildrenOfType(parentTree, oberonLexer.PROCDECL);
List<AnProcDecl> procDecls = new ArrayList<AnProcDecl>();
for (BaseTree child : children){
procDecls.add(createProcDecl(child));
}
return procDecls;
}
//
public static List<AnIdentDecl> createAnVarDecls(BaseTree parentTree){
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.VARS);
return createAnVarDeclsList(tree);
}
//
public static List<AnIdentDecl> createAnVarDeclsList(BaseTree parentTree){
List<AnIdentDecl> idents = new ArrayList<AnIdentDecl>();
List<BaseTree> vars = getChildrenOfType(parentTree, oberonLexer.VAR);
for (BaseTree var: vars){
idents.addAll(createIdentDeclList(var, getTypeFromTree(var)));
}
return idents;
}
public static List<AnIdentDecl> createIdentDeclList(BaseTree parentTree, ValueType type){
List<AnIdentDecl> idents = new ArrayList<AnIdentDecl>();
List<BaseTree> btIdents = getChildrenOfType(parentTree, oberonLexer.IDENTIFIER);
for (BaseTree btIdent : btIdents){
idents.add(new AnIdentDecl(getIdentNameFromTree(btIdent), type));
}
return idents;
}
//
public static List<AnTypeDecl> createAnTypeDecls(BaseTree parentTree){
List<AnTypeDecl> identList = new ArrayList<AnTypeDecl>();
if (parentTree == null) {return identList;}
// TODO >
//oberonLexer.TYPES
return null;
}
//
public static List<AnIdentDecl> createAnConstDelcs(BaseTree parentTree, AnEnvironment env) throws Exception{
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.CONSTS);
List<AnIdentDecl> constsList = new ArrayList<AnIdentDecl>();
List<BaseTree> children = getChildrenOfType(tree, oberonLexer.CONST);
for (BaseTree child : children){
constsList.add(createAnIdentConst(child, env));
}
return constsList;
}
//
public static AnIdentDecl createAnIdentConst(BaseTree parentTree, AnEnvironment env) throws Exception{
assert(parentTree != null);
AnExpression expr = createAnExpression(parentTree);
AnValue val = expr.eval(env);
AnIdentDecl ident = new AnIdentDecl(getIdentNameFromTree(parentTree), val.getType());
ident.assign(val);
ident.setConst(true);
return ident;
}
//
public static List<AnIdentDecl> createAnFormalParams(BaseTree parentTree){
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.FORMALPARAMS);
List<BaseTree> children = getChildrenOfType(tree, oberonLexer.FPSECTION);
List<AnIdentDecl> params = new ArrayList<AnIdentDecl>();
boolean isVar;
ValueType valType;
for (BaseTree child : children){
isVar = isVar(child);
valType = getTypeFromTree(child);
List<BaseTree> btIdents = getChildrenOfType(child, oberonLexer.IDENTIFIER);
for (BaseTree btIdent : btIdents){
params.add(createAnIdentParam(btIdent, valType, isVar));
}
}
return params;
}
//
public static List<IStatement> createAnStatementSequence(BaseTree parentTree) throws Exception{
assert(parentTree != null);
List<IStatement> statements = new ArrayList<IStatement>();
BaseTree tree = getChildOfType(parentTree, oberonLexer.STATEMENTSEQ);
if (tree == null) { return null; }
List<BaseTree> children = getChildrenOfType(tree, oberonLexer.STATEMENT);
for (BaseTree child : children){
statements.add(createIStatement(child));
}
return statements;
}
//!
public static IStatement createIStatement(BaseTree parentTree) throws Exception{
assert(parentTree != null);
assert (parentTree.getChildCount() == 1);
BaseTree btStatement = (BaseTree) parentTree.getChild(0);
int statType = btStatement.getType();
switch(statType){
case oberonLexer.ASSIGN: return createSmtAssignment(btStatement);
case oberonLexer.PROCCALL: return createSmtProcCall(btStatement);
case oberonLexer.IFSTATEMENT: return createSmtIf(btStatement);
case oberonLexer.WHILE: return createSmtWhile(btStatement);
case oberonLexer.ASSERT: return createSmtAssert(btStatement);
default: throw new UnsupportedOperationException();
}
}
public static AnSmtAssert createSmtAssert(BaseTree tree){
assert(tree != null);
assert(tree.getType()== oberonLexer.ASSERT);
AnExpression condition = createAnExpression(tree);
return new AnSmtAssert(condition, tree.toStringTree());
}
public static AnSmtWhile createSmtWhile(BaseTree tree) throws Exception{
assert(tree != null);
assert(tree.getType()== oberonLexer.WHILE);
AnExpression condition = createAnExpression(tree);
List<IStatement> statements = createAnStatementSequence(tree);
return new AnSmtWhile(condition, statements);
}
public static AnSmtIf createSmtIf(BaseTree tree) throws Exception{
assert(tree != null);
assert(tree.getType()== oberonLexer.IFSTATEMENT);
AnExpression condition = createAnExpression(tree);
List<IStatement> statements = createAnStatementSequence(tree);
return new AnSmtIf(condition, statements);
}
//-> ^(PROCCALL identSelector actualParameters?) ;
public static AnSmtProcCall createSmtProcCall(BaseTree parentTree) throws Exception{
assert(parentTree != null);
BaseTree tree;
if (parentTree.getType() == oberonLexer.PROCCALL){
tree = parentTree;
} else {
tree = getChildOfType(parentTree, oberonLexer.PROCCALL);
}
assert(tree != null);
List<AnExpression> actualParams = createActualParams(tree);
return new AnSmtProcCall(getIdentNameFromTree(tree), actualParams);
}
private static List<AnExpression> createActualParams(BaseTree parentTree) throws Exception{
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.ACTUALPARAMS);
List<AnExpression> actualParams = new ArrayList<AnExpression>();
List<BaseTree> children = getChildrenOfType(tree, oberonLexer.EXPRESSION);
AnExpression expr;
for (BaseTree child : children){
expr = createSubExpression(child);
actualParams.add(expr);
}
return actualParams;
}
private static AnSmtAssignment createSmtAssignment(BaseTree parentTree){
assert(parentTree != null);
assert(parentTree.getType() == oberonLexer.ASSIGN);
String lhsName = getIdentNameFromTree(parentTree);
AnExpression expr = createAnExpression(parentTree);
return new AnSmtAssignment(lhsName, expr);
}
private static AnExpression createAnExpression(Tree tree){
assert(tree != null);
return createAnExpression((BaseTree) tree);
}
private static AnExpression createSubExpression(Tree tree){
assert(tree != null);
return createSubExpression((BaseTree) tree);
}
public static AnExpression createAnExpression(BaseTree parentTree){
assert(parentTree != null);
BaseTree tree;
if (parentTree.getType() != oberonLexer.EXPRESSION) {
tree = getChildOfType(parentTree, oberonLexer.EXPRESSION);
} else {
tree = parentTree;
}
assert (tree.getChildCount() >= 1);
return createSubExpression(tree.getChild(0));
}
//
public static AnExpression createSubExpression(BaseTree tree){
assert(tree != null);
assert(tree.getChildCount() == 1 || tree.getChildCount() == 2);
String stringRepr = tree.toStringTree();
int exprType = tree.getType();
switch(exprType){
//Values
case oberonLexer.NUMBER:
AnValue val = createValue(tree);
return new AnExpression(val, stringRepr);
case oberonLexer.IDENTIFIER:
IType ident = createIdent(tree);
return new AnExpression(ident, stringRepr);
//Expressions that include an operator
case oberonLexer.EXPRESSION:
return createAnExpression(tree);
case oberonLexer.PLUS:
case oberonLexer.MIN:
case oberonLexer.TILDEFACTOR:
case oberonLexer.MULT:
case oberonLexer.DIV:
case oberonLexer.MOD:
case oberonLexer.AMP:
case oberonLexer.OR:
case oberonLexer.EQ:
case oberonLexer.HASH:
case oberonLexer.LT:
case oberonLexer.LTEQ:
case oberonLexer.GT:
case oberonLexer.GTEQ:
int numChildren = tree.getChildren().size();
assert (numChildren == 1 || numChildren == 2);
AnExpression lhs = createSubExpression(tree.getChild(0));
if (numChildren == 2){
AnExpression rhs = createSubExpression(tree.getChild(1));
return new AnExpression(exprType, lhs, rhs, stringRepr);
} else {
return new AnExpression(exprType, lhs, stringRepr);
}
default: throw new UnsupportedOperationException();
}
}
private static AnIdent createIdent(BaseTree parentTree){
assert(parentTree != null);
return new AnIdent(getIdentNameFromTree(parentTree));
}
private static AnIdentDecl createAnIdentParam(BaseTree parentTree, ValueType valType, boolean isVar){
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.IDENT);
AnIdentDecl param = new AnIdentDecl(tree.toString(), valType);
param.setVar(isVar);
return param;
}
private static AnValue createValue(BaseTree tree){
assert(tree != null);
assert (tree.getChildCount() == 1);
String strVal = tree.getChild(0).toString();
int valType = tree.getType();
switch(valType){
case oberonLexer.NUMBER:
return new AnValue(Integer.parseInt(strVal));
default:
new UnsupportedOperationException();
return null;
}
}
private static BaseTree getChildOfType(BaseTree tree, int type){
assert(tree != null);
@SuppressWarnings("unchecked")
List<BaseTree> children = tree.getChildren();
for (BaseTree child : children){
if (child.getType() == type) {return child;}
}
return null;
}
private static List<BaseTree> getChildrenOfType(BaseTree tree, int type){
List<BaseTree> goodChildren = new ArrayList<BaseTree>();
if (tree == null){ return goodChildren; }
@SuppressWarnings("unchecked")
List<BaseTree> children = tree.getChildren();
for (BaseTree child : children){
if (child.getType() == type) {
goodChildren.add(child);
}
}
return goodChildren;
}
private static ValueType tokenToValueType(int token){
switch(token){
case oberonLexer.NUMBER: return ValueType.NUMBER;
case oberonLexer.ARRAY: return ValueType.ARRAY;
case oberonLexer.CONST: return ValueType.CONST;
case oberonLexer.RECORD: return ValueType.RECORD;
default: throw new UnsupportedOperationException();
}
}
private static String getIdentNameFromTree(BaseTree tree){
assert(tree != null);
BaseTree ident;
if (tree.getType() == oberonLexer.IDENTIFIER) {
ident = tree;
} else {
ident = getChildOfType(tree, oberonLexer.IDENTIFIER);
}
if (ident != null){
return ident.getChild(0).toString();
} else {
return null;
}
}
private static ValueType getTypeFromTree(BaseTree parentTree){
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.TYPE);
assert (tree != null);
assert (tree.getChildCount() == 1);
String type = getIdentNameFromTree(tree);
if (type.equals("INTEGER")) {
return ValueType.NUMBER;
} else if (type.equals("NUMBER")) {
return ValueType.NUMBER;
}
BaseTree array = getChildOfType(parentTree, oberonLexer.ARRAY);
if (array != null){
//Dit zal niet met een valuetype op te lossen zijn. Ik kan niet grootte van array opgeven enz.
throw new UnsupportedOperationException();
}
BaseTree record = getChildOfType(parentTree, oberonLexer.RECORD);
if (record != null){
throw new UnsupportedOperationException();
}
return tokenToValueType(tree.getType());
}
private static boolean isVar(BaseTree parent){
return (getChildOfType(parent, oberonLexer.VAR) != null);
}
}
| tvdstorm/sea-of-oberon0 | 6005462/src/language/AstNodeCreater.java | 4,879 | //Dit zal niet met een valuetype op te lossen zijn. Ik kan niet grootte van array opgeven enz.
| line_comment | nl | package language;
import java.util.ArrayList;
import java.util.List;
import language.parser.oberonLexer;
import org.antlr.runtime.tree.BaseTree;
import org.antlr.runtime.tree.Tree;
public class AstNodeCreater {
private AstNodeCreater() {}
public static AnModule createModule(BaseTree parentTree) throws Exception{
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.MODULE);
String moduleName = getIdentNameFromTree(tree);
AnContext decls = createDeclarations(tree);
List<IStatement> statementSeq = createAnStatementSequence(tree);
return new AnModule(moduleName, decls, statementSeq);
}
public static AnContext createDeclarations(BaseTree parentTree) throws Exception{
assert(parentTree != null);
BaseTree btDecls = getChildOfType(parentTree, oberonLexer.DECLARATIONS);
assert(btDecls != null);
List<AnIdentDecl> constDecls = createAnConstDelcs(btDecls, new AnEnvironment());
List<AnTypeDecl> typeDecls = createAnTypeDecls(btDecls);
List<AnIdentDecl> varDecls = createAnVarDecls(btDecls);
List<AnProcDecl> procDecls = createListOfAnProcDecl(btDecls);
AnContext ctxt = new AnContext();
ctxt.setIdents(constDecls);
ctxt.setIdents(varDecls);
ctxt.setTypes(typeDecls);
ctxt.setProcs(procDecls);
return ctxt;
}
//
public static AnProcDecl createProcDecl(BaseTree parentTree) throws Exception{
assert(parentTree != null);
BaseTree tree;
if (parentTree.getType() == oberonLexer.PROCDECL){
tree = parentTree;
} else {
tree = getChildOfType(parentTree, oberonLexer.PROCDECL);
}
//Procheader gerelateerd
BaseTree btProcHeader = getChildOfType(tree, oberonLexer.PROCHEAD);
assert(btProcHeader != null);
assert(btProcHeader.getChildCount() >= 1);
String name = getIdentNameFromTree(btProcHeader);
List<AnIdentDecl> formalParams = createAnFormalParams(btProcHeader);
//Procbody gerelateerd
BaseTree btProcBody = getChildOfType(tree, oberonLexer.PROCBODY);
assert(btProcBody != null);
AnContext ctxt = createDeclarations(btProcBody);
List<IStatement> statementSeq = createAnStatementSequence(btProcBody);
return new AnProcDecl(name, ctxt, formalParams, statementSeq);
}
//
public static List<AnProcDecl> createListOfAnProcDecl(BaseTree parentTree) throws Exception{
assert(parentTree != null);
List<BaseTree> children = getChildrenOfType(parentTree, oberonLexer.PROCDECL);
List<AnProcDecl> procDecls = new ArrayList<AnProcDecl>();
for (BaseTree child : children){
procDecls.add(createProcDecl(child));
}
return procDecls;
}
//
public static List<AnIdentDecl> createAnVarDecls(BaseTree parentTree){
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.VARS);
return createAnVarDeclsList(tree);
}
//
public static List<AnIdentDecl> createAnVarDeclsList(BaseTree parentTree){
List<AnIdentDecl> idents = new ArrayList<AnIdentDecl>();
List<BaseTree> vars = getChildrenOfType(parentTree, oberonLexer.VAR);
for (BaseTree var: vars){
idents.addAll(createIdentDeclList(var, getTypeFromTree(var)));
}
return idents;
}
public static List<AnIdentDecl> createIdentDeclList(BaseTree parentTree, ValueType type){
List<AnIdentDecl> idents = new ArrayList<AnIdentDecl>();
List<BaseTree> btIdents = getChildrenOfType(parentTree, oberonLexer.IDENTIFIER);
for (BaseTree btIdent : btIdents){
idents.add(new AnIdentDecl(getIdentNameFromTree(btIdent), type));
}
return idents;
}
//
public static List<AnTypeDecl> createAnTypeDecls(BaseTree parentTree){
List<AnTypeDecl> identList = new ArrayList<AnTypeDecl>();
if (parentTree == null) {return identList;}
// TODO >
//oberonLexer.TYPES
return null;
}
//
public static List<AnIdentDecl> createAnConstDelcs(BaseTree parentTree, AnEnvironment env) throws Exception{
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.CONSTS);
List<AnIdentDecl> constsList = new ArrayList<AnIdentDecl>();
List<BaseTree> children = getChildrenOfType(tree, oberonLexer.CONST);
for (BaseTree child : children){
constsList.add(createAnIdentConst(child, env));
}
return constsList;
}
//
public static AnIdentDecl createAnIdentConst(BaseTree parentTree, AnEnvironment env) throws Exception{
assert(parentTree != null);
AnExpression expr = createAnExpression(parentTree);
AnValue val = expr.eval(env);
AnIdentDecl ident = new AnIdentDecl(getIdentNameFromTree(parentTree), val.getType());
ident.assign(val);
ident.setConst(true);
return ident;
}
//
public static List<AnIdentDecl> createAnFormalParams(BaseTree parentTree){
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.FORMALPARAMS);
List<BaseTree> children = getChildrenOfType(tree, oberonLexer.FPSECTION);
List<AnIdentDecl> params = new ArrayList<AnIdentDecl>();
boolean isVar;
ValueType valType;
for (BaseTree child : children){
isVar = isVar(child);
valType = getTypeFromTree(child);
List<BaseTree> btIdents = getChildrenOfType(child, oberonLexer.IDENTIFIER);
for (BaseTree btIdent : btIdents){
params.add(createAnIdentParam(btIdent, valType, isVar));
}
}
return params;
}
//
public static List<IStatement> createAnStatementSequence(BaseTree parentTree) throws Exception{
assert(parentTree != null);
List<IStatement> statements = new ArrayList<IStatement>();
BaseTree tree = getChildOfType(parentTree, oberonLexer.STATEMENTSEQ);
if (tree == null) { return null; }
List<BaseTree> children = getChildrenOfType(tree, oberonLexer.STATEMENT);
for (BaseTree child : children){
statements.add(createIStatement(child));
}
return statements;
}
//!
public static IStatement createIStatement(BaseTree parentTree) throws Exception{
assert(parentTree != null);
assert (parentTree.getChildCount() == 1);
BaseTree btStatement = (BaseTree) parentTree.getChild(0);
int statType = btStatement.getType();
switch(statType){
case oberonLexer.ASSIGN: return createSmtAssignment(btStatement);
case oberonLexer.PROCCALL: return createSmtProcCall(btStatement);
case oberonLexer.IFSTATEMENT: return createSmtIf(btStatement);
case oberonLexer.WHILE: return createSmtWhile(btStatement);
case oberonLexer.ASSERT: return createSmtAssert(btStatement);
default: throw new UnsupportedOperationException();
}
}
public static AnSmtAssert createSmtAssert(BaseTree tree){
assert(tree != null);
assert(tree.getType()== oberonLexer.ASSERT);
AnExpression condition = createAnExpression(tree);
return new AnSmtAssert(condition, tree.toStringTree());
}
public static AnSmtWhile createSmtWhile(BaseTree tree) throws Exception{
assert(tree != null);
assert(tree.getType()== oberonLexer.WHILE);
AnExpression condition = createAnExpression(tree);
List<IStatement> statements = createAnStatementSequence(tree);
return new AnSmtWhile(condition, statements);
}
public static AnSmtIf createSmtIf(BaseTree tree) throws Exception{
assert(tree != null);
assert(tree.getType()== oberonLexer.IFSTATEMENT);
AnExpression condition = createAnExpression(tree);
List<IStatement> statements = createAnStatementSequence(tree);
return new AnSmtIf(condition, statements);
}
//-> ^(PROCCALL identSelector actualParameters?) ;
public static AnSmtProcCall createSmtProcCall(BaseTree parentTree) throws Exception{
assert(parentTree != null);
BaseTree tree;
if (parentTree.getType() == oberonLexer.PROCCALL){
tree = parentTree;
} else {
tree = getChildOfType(parentTree, oberonLexer.PROCCALL);
}
assert(tree != null);
List<AnExpression> actualParams = createActualParams(tree);
return new AnSmtProcCall(getIdentNameFromTree(tree), actualParams);
}
private static List<AnExpression> createActualParams(BaseTree parentTree) throws Exception{
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.ACTUALPARAMS);
List<AnExpression> actualParams = new ArrayList<AnExpression>();
List<BaseTree> children = getChildrenOfType(tree, oberonLexer.EXPRESSION);
AnExpression expr;
for (BaseTree child : children){
expr = createSubExpression(child);
actualParams.add(expr);
}
return actualParams;
}
private static AnSmtAssignment createSmtAssignment(BaseTree parentTree){
assert(parentTree != null);
assert(parentTree.getType() == oberonLexer.ASSIGN);
String lhsName = getIdentNameFromTree(parentTree);
AnExpression expr = createAnExpression(parentTree);
return new AnSmtAssignment(lhsName, expr);
}
private static AnExpression createAnExpression(Tree tree){
assert(tree != null);
return createAnExpression((BaseTree) tree);
}
private static AnExpression createSubExpression(Tree tree){
assert(tree != null);
return createSubExpression((BaseTree) tree);
}
public static AnExpression createAnExpression(BaseTree parentTree){
assert(parentTree != null);
BaseTree tree;
if (parentTree.getType() != oberonLexer.EXPRESSION) {
tree = getChildOfType(parentTree, oberonLexer.EXPRESSION);
} else {
tree = parentTree;
}
assert (tree.getChildCount() >= 1);
return createSubExpression(tree.getChild(0));
}
//
public static AnExpression createSubExpression(BaseTree tree){
assert(tree != null);
assert(tree.getChildCount() == 1 || tree.getChildCount() == 2);
String stringRepr = tree.toStringTree();
int exprType = tree.getType();
switch(exprType){
//Values
case oberonLexer.NUMBER:
AnValue val = createValue(tree);
return new AnExpression(val, stringRepr);
case oberonLexer.IDENTIFIER:
IType ident = createIdent(tree);
return new AnExpression(ident, stringRepr);
//Expressions that include an operator
case oberonLexer.EXPRESSION:
return createAnExpression(tree);
case oberonLexer.PLUS:
case oberonLexer.MIN:
case oberonLexer.TILDEFACTOR:
case oberonLexer.MULT:
case oberonLexer.DIV:
case oberonLexer.MOD:
case oberonLexer.AMP:
case oberonLexer.OR:
case oberonLexer.EQ:
case oberonLexer.HASH:
case oberonLexer.LT:
case oberonLexer.LTEQ:
case oberonLexer.GT:
case oberonLexer.GTEQ:
int numChildren = tree.getChildren().size();
assert (numChildren == 1 || numChildren == 2);
AnExpression lhs = createSubExpression(tree.getChild(0));
if (numChildren == 2){
AnExpression rhs = createSubExpression(tree.getChild(1));
return new AnExpression(exprType, lhs, rhs, stringRepr);
} else {
return new AnExpression(exprType, lhs, stringRepr);
}
default: throw new UnsupportedOperationException();
}
}
private static AnIdent createIdent(BaseTree parentTree){
assert(parentTree != null);
return new AnIdent(getIdentNameFromTree(parentTree));
}
private static AnIdentDecl createAnIdentParam(BaseTree parentTree, ValueType valType, boolean isVar){
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.IDENT);
AnIdentDecl param = new AnIdentDecl(tree.toString(), valType);
param.setVar(isVar);
return param;
}
private static AnValue createValue(BaseTree tree){
assert(tree != null);
assert (tree.getChildCount() == 1);
String strVal = tree.getChild(0).toString();
int valType = tree.getType();
switch(valType){
case oberonLexer.NUMBER:
return new AnValue(Integer.parseInt(strVal));
default:
new UnsupportedOperationException();
return null;
}
}
private static BaseTree getChildOfType(BaseTree tree, int type){
assert(tree != null);
@SuppressWarnings("unchecked")
List<BaseTree> children = tree.getChildren();
for (BaseTree child : children){
if (child.getType() == type) {return child;}
}
return null;
}
private static List<BaseTree> getChildrenOfType(BaseTree tree, int type){
List<BaseTree> goodChildren = new ArrayList<BaseTree>();
if (tree == null){ return goodChildren; }
@SuppressWarnings("unchecked")
List<BaseTree> children = tree.getChildren();
for (BaseTree child : children){
if (child.getType() == type) {
goodChildren.add(child);
}
}
return goodChildren;
}
private static ValueType tokenToValueType(int token){
switch(token){
case oberonLexer.NUMBER: return ValueType.NUMBER;
case oberonLexer.ARRAY: return ValueType.ARRAY;
case oberonLexer.CONST: return ValueType.CONST;
case oberonLexer.RECORD: return ValueType.RECORD;
default: throw new UnsupportedOperationException();
}
}
private static String getIdentNameFromTree(BaseTree tree){
assert(tree != null);
BaseTree ident;
if (tree.getType() == oberonLexer.IDENTIFIER) {
ident = tree;
} else {
ident = getChildOfType(tree, oberonLexer.IDENTIFIER);
}
if (ident != null){
return ident.getChild(0).toString();
} else {
return null;
}
}
private static ValueType getTypeFromTree(BaseTree parentTree){
assert(parentTree != null);
BaseTree tree = getChildOfType(parentTree, oberonLexer.TYPE);
assert (tree != null);
assert (tree.getChildCount() == 1);
String type = getIdentNameFromTree(tree);
if (type.equals("INTEGER")) {
return ValueType.NUMBER;
} else if (type.equals("NUMBER")) {
return ValueType.NUMBER;
}
BaseTree array = getChildOfType(parentTree, oberonLexer.ARRAY);
if (array != null){
//Dit zal<SUF>
throw new UnsupportedOperationException();
}
BaseTree record = getChildOfType(parentTree, oberonLexer.RECORD);
if (record != null){
throw new UnsupportedOperationException();
}
return tokenToValueType(tree.getType());
}
private static boolean isVar(BaseTree parent){
return (getChildOfType(parent, oberonLexer.VAR) != null);
}
}
|
63167_4 | /*
* Copyright 2011 Vlaams Gewest
*
* This file is part of SESAM, the Service Endpoint Security And Monitoring framework.
*
* SESAM 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.
*
* SESAM 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 SESAM. If not, see <http://www.gnu.org/licenses/>.
*/
package be.vlaanderen.sesam.config;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
public class IPRange {
private BigInteger from;
private BigInteger to;
public BigInteger getFrom() {
return from;
}
public void setFrom(String from) {
try {
this.from = ipToBigInteger(InetAddress.getByName(from));
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Not a valid ip address");
}
}
public BigInteger getTo() {
return to;
}
public void setTo(String to) {
try {
this.to = ipToBigInteger(InetAddress.getByName(to));
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Not a valid ip address");
}
}
// ---------------------------------------------------------
// TODO
public boolean withinRange(InetSocketAddress address) {
BigInteger test = ipToBigInteger(address.getAddress());
// FIXME
return true;
}
public static BigInteger ipToBigInteger(InetAddress address) {
byte[] octets = address.getAddress();
return new BigInteger(1, octets);
}
// TODO make unittest
// public static void main(String[] params) {
// try {
// BigInteger a = ipToBigInteger(InetAddress.getByName("255.10.255.1"));
//
// if (!a.equals(b))
// System.out.println("Hoezo niet gelijk? a:" + a + " - b:" + b);
// else
// System.out.println("equal");
//
// } catch (UnknownHostException e) {}
//
// }
} | tvgulck/sesam | sesam-bundles/sesam-config/src/main/java/be/vlaanderen/sesam/config/IPRange.java | 697 | // System.out.println("Hoezo niet gelijk? a:" + a + " - b:" + b); | line_comment | nl | /*
* Copyright 2011 Vlaams Gewest
*
* This file is part of SESAM, the Service Endpoint Security And Monitoring framework.
*
* SESAM 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.
*
* SESAM 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 SESAM. If not, see <http://www.gnu.org/licenses/>.
*/
package be.vlaanderen.sesam.config;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
public class IPRange {
private BigInteger from;
private BigInteger to;
public BigInteger getFrom() {
return from;
}
public void setFrom(String from) {
try {
this.from = ipToBigInteger(InetAddress.getByName(from));
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Not a valid ip address");
}
}
public BigInteger getTo() {
return to;
}
public void setTo(String to) {
try {
this.to = ipToBigInteger(InetAddress.getByName(to));
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Not a valid ip address");
}
}
// ---------------------------------------------------------
// TODO
public boolean withinRange(InetSocketAddress address) {
BigInteger test = ipToBigInteger(address.getAddress());
// FIXME
return true;
}
public static BigInteger ipToBigInteger(InetAddress address) {
byte[] octets = address.getAddress();
return new BigInteger(1, octets);
}
// TODO make unittest
// public static void main(String[] params) {
// try {
// BigInteger a = ipToBigInteger(InetAddress.getByName("255.10.255.1"));
//
// if (!a.equals(b))
// System.out.println("Hoezo niet<SUF>
// else
// System.out.println("equal");
//
// } catch (UnknownHostException e) {}
//
// }
} |
70935_52 |
package org.twak.camp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.vecmath.Point3d;
import javax.vecmath.Tuple3d;
import javax.vecmath.Vector3d;
import org.twak.utils.Pair;
import org.twak.utils.Triple;
import org.twak.utils.collections.ConsecutivePairs;
import org.twak.utils.collections.ConsecutiveTriples;
import org.twak.utils.geom.Ray3d;
import org.twak.utils.geom.LinearForm3D;
/**
* A bunch of faces that collide at one point
* @author twak
*/
public class CoSitedCollision
{
public Set<EdgeCollision> edges = new LinkedHashSet();
public Point3d loc;
public boolean debugHoriz = false;
public List<Chain> chains = new ArrayList();
private HeightCollision parent;
public CoSitedCollision( Point3d loc, EdgeCollision ec, HeightCollision parent )
{
this.loc= loc;
this.parent = parent;
add( ec );
}
public void add(EdgeCollision ec)
{
edges.add( ec );
}
/**
* New routine
* @return true if valid chains found at this site
*/
public boolean findChains ( Skeleton skel )
{
chains = new ArrayList();
// remove duplicate edges
Set<Edge> allEdges = new LinkedHashSet();
for (EdgeCollision ec : edges)
{
allEdges.add( ec.a );
allEdges.add( ec.b );
allEdges.add( ec.c );
}
Iterator<Edge> eit = allEdges.iterator();
while ( eit.hasNext() )
if ( !skel.liveEdges.contains( eit.next() ) )
eit.remove();
if (allEdges.size() < 3)
return false;
Set<Corner> edgeStarts = new LinkedHashSet<>();
for ( Edge e : allEdges )
for ( Corner c : e.currentCorners )
if ( c.nextL == e )
if ( !skel.preserveParallel || EdgeCollision.bisectorsBound( c, loc, skel ) )
edgeStarts.add( c );
while (!edgeStarts.isEmpty())
{
Corner start = edgeStarts.iterator().next();
Chain chain = buildChain2( start, edgeStarts );
if (chain != null)
chains.add( chain );
}
edgeStarts.clear();
for (Chain c : chains)
if (c.chain.size() > 1)
edgeStarts.addAll( c.chain );
Iterator<Chain> chit = chains.iterator();
while (chit.hasNext())
{
Chain chain = chit.next();
if (chain.chain.size() == 1)
{
// first corner of edge is not necessarily the corner of the edge segment bounding the collision
Corner s = chain.chain.get( 0 );
Corner found = EdgeCollision.findCorner( s.nextL, loc, skel );
// if (found != null && !edgeStarts.contains( found ))
// fixme: because we (strangely) add all the chain starts above, we can just check if it's unchanged...
if (found == s && !edgeStarts.contains( found ))
{
// chain.chain.clear();
// chain.chain.add( found );
}
else
chit.remove();
}
}
// while still no-horizontals in chains (there may be when dealing with multiple
// sites at one height), process chains to a counter clockwise order
if (chains.size() > 1) // size == 1 may have parallels in it (run away!)
Collections.sort( chains, new ChainComparator( loc.z ) );
return true;
}
/**
* If another collision has been evaluated at teh same height, this method
* checks for any changes in the Corners involved in a skeleton. This is a problem
* when several collisions at the same height occur against one smash edge.
*
* If the chain has length > 1, then the lost corner can be recorvered using
* the following corner (the corners central to the collision, every one after
* the first will all remain valid at one height).
*
* If the chain has length 1, we're in for a bit of a trek.
*
* We can skip the finding edges part if the current height only has one
* collision?
*
* @param skel
*/
public void validateChains (Skeleton skel)
{
// in case an edge has been removed by a previous event at this height
for ( Chain c : chains )
{
if (c.loop)
continue; // nothing to do here
if (c.chain.size() > 1) // previous
{
c.chain.remove( 0 );
c.chain.add( 0, c.chain.get( 0 ).prevC );
}
else // smash edge, search for correct corner (edges not in liveEdges removed next)
{
/**
* This covers the "corner situation" where a concave angle creates creates
* another loop with it's point closer to the target, than the original loop.
*
* It may well break down with lots of adjacent sides.
*/
Corner s = c.chain.get( 0 );
Edge e = s.nextL;
Ray3d projectionLine = new Ray3d (loc, e.direction() );
LinearForm3D ceiling = new LinearForm3D( 0, 0, 1, -loc.z );
// project start onto line of collisions above smash edge
try
{
Tuple3d start;
if (e.uphill.equals( s.prevL.uphill ))
start = ceiling.collide(e.start, e.uphill);
else
start = e.linearForm.collide( s.prevL.linearForm, ceiling );
// line defined using collision point, so we're finding the line before 0
double targetParam = 0;
// we should only end with start if it hasn't been elevated yet
Corner bestPrev = s;
// ignore points before start (but allow the first point to override start!)
double bestParam = projectionLine.projectParam( start ) - 0.001;
// parameterize each corner in e's currentCorners by the line
for ( Corner r : e.currentCorners )
if ( r.nextL == e )
{
// parameterize
Tuple3d rOnHigh = Math.abs( r.z - loc.z ) < 0.001 ? r : ceiling.collide( r.prevL.linearForm, r.nextL.linearForm );
double param = projectionLine.projectParam( rOnHigh );
// if this was the previous (todo: does this want a tolerance on < targetParam? why not?)
if ( param > bestParam && param <= targetParam )
{
bestPrev = r;
bestParam = param;
}
}
c.chain.remove( 0 );
c.chain.add( 0, bestPrev );
// might have formed a loop
c.loop = c.chain.get( c.chain.size() - 1 ).nextC == c.chain.get( 0 );
}
catch ( Throwable t )
{
t.printStackTrace();
// System.err.println( "didn't like colliding " + e + "and " + s.prevL );
continue;
}
}
}
Map<Edge, Corner> edgeToCorner = new LinkedHashMap<>();
for (Chain cc : chains)
for (Corner c : cc.chain)
edgeToCorner.put( c.nextL, c);
// Find valid triples ~ now topology is as it will be before evaluation, we
// can check that the input edge triplets still have two consecutive edges.
Set<Edge> validEdges = new LinkedHashSet<>();
for (EdgeCollision ec : edges)
{
// todo: adjacent pairs may not be parallel!
if (hasAdjacent(
edgeToCorner.get( ec.a ),
edgeToCorner.get( ec.b ),
edgeToCorner.get( ec.c ) ))
{
if ( skel.liveEdges.contains( ec. a ) &&
skel.liveEdges.contains( ec. b ) &&
skel.liveEdges.contains( ec. c ) )
{
validEdges.add( ec.a );
validEdges.add( ec.b );
validEdges.add( ec.c );
}
}
}
List<Chain> chainOrder = new ArrayList<>( chains );
// remove parts of chains that aren't a valid triple.
for (Chain cc : chainOrder)
{
// remove and split
chains.addAll( chains.indexOf( cc ), cc.removeCornersWithoutEdges ( validEdges ) );
}
// kill 0-length chains
Iterator<Chain> ccit = chains.iterator();
while (ccit.hasNext())
{
if (ccit.next().chain.size() == 0)
ccit.remove();
}
}
private boolean hasAdjacent (Corner a, Corner b, Corner c)
{
if (a== null || b == null || c == null)
return false;
if ( (a.nextC == b || a.nextC == c) ) // todo: speedup by puting consec in a,b always?
return true;
if ( (b.nextC == c || b.nextC == a) )
return true;
if ( (c.nextC == a || c.nextC == b) )
return true;
return false;
}
public boolean processChains(Skeleton skel)
{
if (moreOneSmashEdge()) // no test example case showing this is required?
return false;
Set<Corner> allCorners = new LinkedHashSet();
for (Chain cc : chains)
{
allCorners.addAll( cc.chain ); //cc.chain.get(0).nextL.currentCorners
}
// after all the checks, if there are less than three faces involved, it's not a collision any more
if (allCorners.size() < 3)
return false;
skel.debugCollisionOrder.add( this );
Iterator<Chain> cit = chains.iterator();
while (cit.hasNext())
{
Chain chain = cit.next(); // chain.chain.get(2).nextL
for ( Pair<Corner, Corner> p : new ConsecutivePairs<Corner>( chain.chain, chain.loop ) )
{
// System.out.println( "proc consec " + p.first() + " and " + p.second() );
EdgeCollision.processConsecutive( loc, p.first(), p.second(), skel );
}
// remove the middle faces in the loop from the list of live corners, liveEdges if
// there are no more live corners, and the liveCorners list
if ( chain.chain.size() >= 3 )
{
Iterator<Triple<Corner, Corner, Corner>> tit = new ConsecutiveTriples<Corner>( chain.chain, chain.loop );
while ( tit.hasNext() )
{
Edge middle = tit.next().second().nextL;
// face no longer referenced, remove from list of live edges
if ( middle.currentCorners.isEmpty() )
skel.liveEdges.remove( middle );
}
}
if ( chain.loop )
cit.remove();
}
// was entirely closed loops
if ( chains.isEmpty() )
return true;
// connect end of previous chain, to start of next
// in case we are colliding against a smash (no-corner/split event)-edge, we cache the next-corner before
// any alterations
Map<Corner, Corner> aNext = new LinkedHashMap();
for ( Chain chain : chains )
{
Corner c = chain.chain.get( chain.chain.size() -1 );
aNext.put( c, c.nextC );
}
// process intra-chain collisions (non-consecutive edges)
for ( Pair<Chain, Chain> adjacentChains : new ConsecutivePairs<Chain>( chains, true ) )
{
List<Corner> first = adjacentChains.first().chain;
Corner a = first.get( first.size() -1 );
Corner b = adjacentChains.second().chain.get( 0 );
EdgeCollision.processJump( loc, a, aNext.get( a ), b, skel, parent );
}
return true;
}
/**
* Is this actually needed in any of the examples?
*/
private boolean moreOneSmashEdge()
{
// if two chains have length one, this is not a valid collision point
int oneCount = 0;
for (Chain ch : chains)
if (ch.chain.size() == 1)
oneCount++;
if (oneCount > 1)
return false;
return oneCount > 1;
}
public static Chain buildChain2( Corner start, Set<Corner> input ) // start.nextL start.prevL
{
List<Corner> chain = new ArrayList();
// check backwards
Corner a = start;
while ( input.contains( a ) )
{
chain.add( 0, a );
input.remove( a );
a = a.prevC;
}
// check forwards
a = start.nextC;
while ( input.contains( a ) )
{
chain.add( a );
input.remove( a );
a = a.nextC;
}
return new Chain (chain);
}
/**
* Defines order by the angle the first corner in a chain makes with the second
* against a fixed axis at a specified height.
*/
static Vector3d Y_UP = new Vector3d( 0, 1, 0 );
public class ChainComparator implements Comparator<Chain>
{
double height;
// LinearForm3D ceiling;
public ChainComparator (double height)
{
this.height = height;
// this.ceiling = new LinearForm3D( 0, 0, 1, -height );
}
public int compare( Chain o1, Chain o2 )
{
Corner c1 = o1.chain.get( 0 );
Corner c2 = o2.chain.get( 0 );
// except for the first and and last point
// chain's non-start/end points are always at the position of the collision - so to
// find the angle of the first edge at the specified height, we project the edge before start
// coordinate the desired height and take the angle relative to the collision
// !could speed up with a chain-class that caches this info!
// try
// {
Tuple3d p1 = Edge.collide(c1, height);//ceiling.collide( c1.prevL.linearForm, c1.nextL.linearForm );
Tuple3d p2 = Edge.collide(c2, height );//ceiling.collide( c2.prevL.linearForm, c2.nextL.linearForm );
p1.sub( loc );
p2.sub( loc );
// start/end line is (+-)Pi
return Double.compare(
Math.atan2( p1.y, p1.x ),
Math.atan2( p2.y, p2.x ) );
// }
// catch (RuntimeException e)
// {
// // we can probably fix these up (by assuming that they're horizontal?)
// // todo: can we prove they are safe to ignore? eg: no parallel edges inbound, none outbound etc..
// System.err.println( "didn't like colliding 1" + c1.prevL + " and " + c1.nextL );
// System.err.println( " 2" + c2.prevL + " and " + c2.nextL );
// return 0;
// }
}
}
public double getHeight()
{
return loc.z;
}
@Override
public String toString()
{
StringBuilder sb= new StringBuilder("{");
for (EdgeCollision e :edges)
sb.append( e +",");
sb.append( "}");
return sb.toString();
}
}
| twak/campskeleton | src/org/twak/camp/CoSitedCollision.java | 4,791 | // start/end line is (+-)Pi
| line_comment | nl |
package org.twak.camp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.vecmath.Point3d;
import javax.vecmath.Tuple3d;
import javax.vecmath.Vector3d;
import org.twak.utils.Pair;
import org.twak.utils.Triple;
import org.twak.utils.collections.ConsecutivePairs;
import org.twak.utils.collections.ConsecutiveTriples;
import org.twak.utils.geom.Ray3d;
import org.twak.utils.geom.LinearForm3D;
/**
* A bunch of faces that collide at one point
* @author twak
*/
public class CoSitedCollision
{
public Set<EdgeCollision> edges = new LinkedHashSet();
public Point3d loc;
public boolean debugHoriz = false;
public List<Chain> chains = new ArrayList();
private HeightCollision parent;
public CoSitedCollision( Point3d loc, EdgeCollision ec, HeightCollision parent )
{
this.loc= loc;
this.parent = parent;
add( ec );
}
public void add(EdgeCollision ec)
{
edges.add( ec );
}
/**
* New routine
* @return true if valid chains found at this site
*/
public boolean findChains ( Skeleton skel )
{
chains = new ArrayList();
// remove duplicate edges
Set<Edge> allEdges = new LinkedHashSet();
for (EdgeCollision ec : edges)
{
allEdges.add( ec.a );
allEdges.add( ec.b );
allEdges.add( ec.c );
}
Iterator<Edge> eit = allEdges.iterator();
while ( eit.hasNext() )
if ( !skel.liveEdges.contains( eit.next() ) )
eit.remove();
if (allEdges.size() < 3)
return false;
Set<Corner> edgeStarts = new LinkedHashSet<>();
for ( Edge e : allEdges )
for ( Corner c : e.currentCorners )
if ( c.nextL == e )
if ( !skel.preserveParallel || EdgeCollision.bisectorsBound( c, loc, skel ) )
edgeStarts.add( c );
while (!edgeStarts.isEmpty())
{
Corner start = edgeStarts.iterator().next();
Chain chain = buildChain2( start, edgeStarts );
if (chain != null)
chains.add( chain );
}
edgeStarts.clear();
for (Chain c : chains)
if (c.chain.size() > 1)
edgeStarts.addAll( c.chain );
Iterator<Chain> chit = chains.iterator();
while (chit.hasNext())
{
Chain chain = chit.next();
if (chain.chain.size() == 1)
{
// first corner of edge is not necessarily the corner of the edge segment bounding the collision
Corner s = chain.chain.get( 0 );
Corner found = EdgeCollision.findCorner( s.nextL, loc, skel );
// if (found != null && !edgeStarts.contains( found ))
// fixme: because we (strangely) add all the chain starts above, we can just check if it's unchanged...
if (found == s && !edgeStarts.contains( found ))
{
// chain.chain.clear();
// chain.chain.add( found );
}
else
chit.remove();
}
}
// while still no-horizontals in chains (there may be when dealing with multiple
// sites at one height), process chains to a counter clockwise order
if (chains.size() > 1) // size == 1 may have parallels in it (run away!)
Collections.sort( chains, new ChainComparator( loc.z ) );
return true;
}
/**
* If another collision has been evaluated at teh same height, this method
* checks for any changes in the Corners involved in a skeleton. This is a problem
* when several collisions at the same height occur against one smash edge.
*
* If the chain has length > 1, then the lost corner can be recorvered using
* the following corner (the corners central to the collision, every one after
* the first will all remain valid at one height).
*
* If the chain has length 1, we're in for a bit of a trek.
*
* We can skip the finding edges part if the current height only has one
* collision?
*
* @param skel
*/
public void validateChains (Skeleton skel)
{
// in case an edge has been removed by a previous event at this height
for ( Chain c : chains )
{
if (c.loop)
continue; // nothing to do here
if (c.chain.size() > 1) // previous
{
c.chain.remove( 0 );
c.chain.add( 0, c.chain.get( 0 ).prevC );
}
else // smash edge, search for correct corner (edges not in liveEdges removed next)
{
/**
* This covers the "corner situation" where a concave angle creates creates
* another loop with it's point closer to the target, than the original loop.
*
* It may well break down with lots of adjacent sides.
*/
Corner s = c.chain.get( 0 );
Edge e = s.nextL;
Ray3d projectionLine = new Ray3d (loc, e.direction() );
LinearForm3D ceiling = new LinearForm3D( 0, 0, 1, -loc.z );
// project start onto line of collisions above smash edge
try
{
Tuple3d start;
if (e.uphill.equals( s.prevL.uphill ))
start = ceiling.collide(e.start, e.uphill);
else
start = e.linearForm.collide( s.prevL.linearForm, ceiling );
// line defined using collision point, so we're finding the line before 0
double targetParam = 0;
// we should only end with start if it hasn't been elevated yet
Corner bestPrev = s;
// ignore points before start (but allow the first point to override start!)
double bestParam = projectionLine.projectParam( start ) - 0.001;
// parameterize each corner in e's currentCorners by the line
for ( Corner r : e.currentCorners )
if ( r.nextL == e )
{
// parameterize
Tuple3d rOnHigh = Math.abs( r.z - loc.z ) < 0.001 ? r : ceiling.collide( r.prevL.linearForm, r.nextL.linearForm );
double param = projectionLine.projectParam( rOnHigh );
// if this was the previous (todo: does this want a tolerance on < targetParam? why not?)
if ( param > bestParam && param <= targetParam )
{
bestPrev = r;
bestParam = param;
}
}
c.chain.remove( 0 );
c.chain.add( 0, bestPrev );
// might have formed a loop
c.loop = c.chain.get( c.chain.size() - 1 ).nextC == c.chain.get( 0 );
}
catch ( Throwable t )
{
t.printStackTrace();
// System.err.println( "didn't like colliding " + e + "and " + s.prevL );
continue;
}
}
}
Map<Edge, Corner> edgeToCorner = new LinkedHashMap<>();
for (Chain cc : chains)
for (Corner c : cc.chain)
edgeToCorner.put( c.nextL, c);
// Find valid triples ~ now topology is as it will be before evaluation, we
// can check that the input edge triplets still have two consecutive edges.
Set<Edge> validEdges = new LinkedHashSet<>();
for (EdgeCollision ec : edges)
{
// todo: adjacent pairs may not be parallel!
if (hasAdjacent(
edgeToCorner.get( ec.a ),
edgeToCorner.get( ec.b ),
edgeToCorner.get( ec.c ) ))
{
if ( skel.liveEdges.contains( ec. a ) &&
skel.liveEdges.contains( ec. b ) &&
skel.liveEdges.contains( ec. c ) )
{
validEdges.add( ec.a );
validEdges.add( ec.b );
validEdges.add( ec.c );
}
}
}
List<Chain> chainOrder = new ArrayList<>( chains );
// remove parts of chains that aren't a valid triple.
for (Chain cc : chainOrder)
{
// remove and split
chains.addAll( chains.indexOf( cc ), cc.removeCornersWithoutEdges ( validEdges ) );
}
// kill 0-length chains
Iterator<Chain> ccit = chains.iterator();
while (ccit.hasNext())
{
if (ccit.next().chain.size() == 0)
ccit.remove();
}
}
private boolean hasAdjacent (Corner a, Corner b, Corner c)
{
if (a== null || b == null || c == null)
return false;
if ( (a.nextC == b || a.nextC == c) ) // todo: speedup by puting consec in a,b always?
return true;
if ( (b.nextC == c || b.nextC == a) )
return true;
if ( (c.nextC == a || c.nextC == b) )
return true;
return false;
}
public boolean processChains(Skeleton skel)
{
if (moreOneSmashEdge()) // no test example case showing this is required?
return false;
Set<Corner> allCorners = new LinkedHashSet();
for (Chain cc : chains)
{
allCorners.addAll( cc.chain ); //cc.chain.get(0).nextL.currentCorners
}
// after all the checks, if there are less than three faces involved, it's not a collision any more
if (allCorners.size() < 3)
return false;
skel.debugCollisionOrder.add( this );
Iterator<Chain> cit = chains.iterator();
while (cit.hasNext())
{
Chain chain = cit.next(); // chain.chain.get(2).nextL
for ( Pair<Corner, Corner> p : new ConsecutivePairs<Corner>( chain.chain, chain.loop ) )
{
// System.out.println( "proc consec " + p.first() + " and " + p.second() );
EdgeCollision.processConsecutive( loc, p.first(), p.second(), skel );
}
// remove the middle faces in the loop from the list of live corners, liveEdges if
// there are no more live corners, and the liveCorners list
if ( chain.chain.size() >= 3 )
{
Iterator<Triple<Corner, Corner, Corner>> tit = new ConsecutiveTriples<Corner>( chain.chain, chain.loop );
while ( tit.hasNext() )
{
Edge middle = tit.next().second().nextL;
// face no longer referenced, remove from list of live edges
if ( middle.currentCorners.isEmpty() )
skel.liveEdges.remove( middle );
}
}
if ( chain.loop )
cit.remove();
}
// was entirely closed loops
if ( chains.isEmpty() )
return true;
// connect end of previous chain, to start of next
// in case we are colliding against a smash (no-corner/split event)-edge, we cache the next-corner before
// any alterations
Map<Corner, Corner> aNext = new LinkedHashMap();
for ( Chain chain : chains )
{
Corner c = chain.chain.get( chain.chain.size() -1 );
aNext.put( c, c.nextC );
}
// process intra-chain collisions (non-consecutive edges)
for ( Pair<Chain, Chain> adjacentChains : new ConsecutivePairs<Chain>( chains, true ) )
{
List<Corner> first = adjacentChains.first().chain;
Corner a = first.get( first.size() -1 );
Corner b = adjacentChains.second().chain.get( 0 );
EdgeCollision.processJump( loc, a, aNext.get( a ), b, skel, parent );
}
return true;
}
/**
* Is this actually needed in any of the examples?
*/
private boolean moreOneSmashEdge()
{
// if two chains have length one, this is not a valid collision point
int oneCount = 0;
for (Chain ch : chains)
if (ch.chain.size() == 1)
oneCount++;
if (oneCount > 1)
return false;
return oneCount > 1;
}
public static Chain buildChain2( Corner start, Set<Corner> input ) // start.nextL start.prevL
{
List<Corner> chain = new ArrayList();
// check backwards
Corner a = start;
while ( input.contains( a ) )
{
chain.add( 0, a );
input.remove( a );
a = a.prevC;
}
// check forwards
a = start.nextC;
while ( input.contains( a ) )
{
chain.add( a );
input.remove( a );
a = a.nextC;
}
return new Chain (chain);
}
/**
* Defines order by the angle the first corner in a chain makes with the second
* against a fixed axis at a specified height.
*/
static Vector3d Y_UP = new Vector3d( 0, 1, 0 );
public class ChainComparator implements Comparator<Chain>
{
double height;
// LinearForm3D ceiling;
public ChainComparator (double height)
{
this.height = height;
// this.ceiling = new LinearForm3D( 0, 0, 1, -height );
}
public int compare( Chain o1, Chain o2 )
{
Corner c1 = o1.chain.get( 0 );
Corner c2 = o2.chain.get( 0 );
// except for the first and and last point
// chain's non-start/end points are always at the position of the collision - so to
// find the angle of the first edge at the specified height, we project the edge before start
// coordinate the desired height and take the angle relative to the collision
// !could speed up with a chain-class that caches this info!
// try
// {
Tuple3d p1 = Edge.collide(c1, height);//ceiling.collide( c1.prevL.linearForm, c1.nextL.linearForm );
Tuple3d p2 = Edge.collide(c2, height );//ceiling.collide( c2.prevL.linearForm, c2.nextL.linearForm );
p1.sub( loc );
p2.sub( loc );
// start/end line<SUF>
return Double.compare(
Math.atan2( p1.y, p1.x ),
Math.atan2( p2.y, p2.x ) );
// }
// catch (RuntimeException e)
// {
// // we can probably fix these up (by assuming that they're horizontal?)
// // todo: can we prove they are safe to ignore? eg: no parallel edges inbound, none outbound etc..
// System.err.println( "didn't like colliding 1" + c1.prevL + " and " + c1.nextL );
// System.err.println( " 2" + c2.prevL + " and " + c2.nextL );
// return 0;
// }
}
}
public double getHeight()
{
return loc.z;
}
@Override
public String toString()
{
StringBuilder sb= new StringBuilder("{");
for (EdgeCollision e :edges)
sb.append( e +",");
sb.append( "}");
return sb.toString();
}
}
|
7319_3 | package be.thomaswinters.similarreplacer;
import be.thomaswinters.LambdaExceptionUtil;
import be.thomaswinters.markov.model.data.bags.Bag;
import be.thomaswinters.markov.model.data.bags.WriteableBag;
import be.thomaswinters.markov.model.data.bags.impl.ExclusionBag;
import be.thomaswinters.markov.model.data.bags.impl.MutableBag;
import be.thomaswinters.random.Picker;
import be.thomaswinters.replacement.Replacer;
import be.thomaswinters.replacement.Replacers;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.JLanguageTool;
import org.languagetool.language.Dutch;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
public class SimilarWordReplacer {
/*-********************************************-*
* STATIC TOOLS
*-********************************************-*/
private static final JLanguageTool langTool = new JLanguageTool(new Dutch());
protected static final Random RANDOM = new Random();
/*-********************************************-*/
/*-********************************************-*
* INSTANCE VARIABLES
*-********************************************-*/
private Map<Set<String>, WriteableBag<String>> mappings = new HashMap<>();
/*-********************************************-*/
/*-********************************************-*
* TAGS & TOKEN FILTERING
*-********************************************-*/
protected Set<String> getTags(AnalyzedTokenReadings token) {
return token.getReadings().stream().filter(e -> !e.hasNoTag()).map(e -> e.getPOSTag())
.filter(e -> e != null && !e.equals("SENT_END") && !e.equals("PARA_END")).collect(Collectors.toSet());
}
private static final Set<String> REPLACEMENT_TOKEN_BLACKLIST = new HashSet<>(Arrays.asList(
// Lidwoorden
"de", "het", "een",
// Algemene onderwerpen
"ik", "jij", "je", "u", "wij", "we", "jullie", "hij", "zij", "ze",
// Algemene persoonlijke voornaamwoorden
"hen", "hem", "haar", "mijn", "uw", "jouw", "onze", "ons",
// Algemene werkwoorden
"ben", "bent", "is", "was", "waren", "geweest", "heb", "hebt", "heeft", "hebben", "gehad", "word", "wordt",
"worden", "geworden", "werd", "werden", "laat", "laten", "liet", "lieten", "gelaten", "ga", "gaat", "gaan",
"gegaan", "ging", "gingen", "moet", "moeten", "moest", "moesten", "gemoeten", "mag", "mogen", "mocht",
"mochten", "gemogen", "zal", "zullen", "zult", "zou", "zouden", "kan", "kunnen", "gekunt", "gekunnen",
"hoef", "hoeft", "hoeven", "hoefde", "hoefden", "gehoeven",
// Veelgebruikte woorden
"niet", "iets", "dan", "voort", "erna", "welke", "maar", "van", "voor", "met", "binnenkort", "in", "en",
"teveel", "om", "alles", "elke", "al", "echt", "waar", "waarom", "hoe", "o.a.", "beetje", "enkel", "goed",
"best", "werkende", "meer", "voor", "zit", "echt", "uit", "even", "wel"));
private static final Set<String> REPLACEMENT_TAG_BLACKLIST = new HashSet<>(
Arrays.asList("AVwaar", "AVwr", "DTh", "DTd", "DTe", "DTp", "PRte", "PRnaar", "PRvan", "PN2", "PRVoor",
"PRmet", "PRop", "PRin", "PRom", "PRaan", "AVdr", "CJo"));
private List<AnalyzedTokenReadings> filterTokens(List<AnalyzedTokenReadings> tokens) {
return tokens.stream().filter(e -> e.getToken().trim().length() > 0).filter(e -> !e.getReadings().isEmpty())
.filter(token -> !getTags(token).isEmpty())
.filter(token -> getTags(token).stream().allMatch(tag -> !REPLACEMENT_TAG_BLACKLIST.contains(tag)))
.filter(token -> !REPLACEMENT_TOKEN_BLACKLIST.contains(token.getToken().toLowerCase()))
.collect(Collectors.toList());
}
/*-********************************************-*/
/*-********************************************-*
* PROCESSING KNOWLEDGE INPUT
*-********************************************-*/
public void process(String line) throws IOException {
List<AnalyzedSentence> answers = langTool.analyzeText(line);
for (AnalyzedSentence analyzedSentence : answers) {
List<AnalyzedTokenReadings> tokens = filterTokens(Arrays.asList(analyzedSentence.getTokens()));
for (AnalyzedTokenReadings token : tokens) {
if (token.getToken().trim().length() > 0) {
Set<String> tags = getTags(token);
// Add if valid
if (tags != null && tags.size() > 0) {
if (!mappings.containsKey(tags)) {
mappings.put(tags, new MutableBag<String>());
}
mappings.get(tags).add(token.getToken());
}
}
}
}
}
public void process(List<String> lines) {
lines.forEach(LambdaExceptionUtil.rethrowConsumer(this::process));
}
/*-********************************************-*/
/*-********************************************-*
* REPLACEABLE CALCULATION
*-********************************************-*/
public int getReplaceableSize(Set<String> tags) {
if (!mappings.containsKey(tags)) {
return 0;
}
return mappings.get(tags).size();
}
public List<AnalyzedTokenReadings> getReplaceableTokens(String line) {
List<AnalyzedSentence> answers;
try {
answers = langTool.analyzeText(line);
} catch (IOException e1) {
throw new RuntimeException(e1);
}
List<AnalyzedTokenReadings> tokens = new ArrayList<>();
for (AnalyzedSentence analyzedSentence : answers) {
tokens.addAll(Arrays.asList(analyzedSentence.getTokens()));
}
tokens = filterTokens(tokens).stream().filter(e -> getReplaceableSize(getTags(e)) > 1)
.collect(Collectors.toList());
return tokens;
}
public Optional<Replacer> createReplacer(AnalyzedTokenReadings token, Bag<String> replacePossibilities) {
// Check if there is another possibility than to replace with itself
if (replacePossibilities.isEmpty() || (replacePossibilities.getAmountOfUniqueElements() == 1
&& replacePossibilities.get(0).toLowerCase().equals(token.getToken().toLowerCase()))) {
return Optional.empty();
}
Bag<String> bag = new ExclusionBag<String>(replacePossibilities, Arrays.asList(token.getToken()));
String replacement = pickReplacement(token.getToken(), bag);
Replacer replacer = new Replacer(token.getToken(), replacement, false, true);
return Optional.of(replacer);
}
public String pickReplacement(String replacement, Bag<String> bag) {
return bag.get(RANDOM.nextInt(bag.getAmountOfElements()));
}
public List<Replacer> calculatePossibleReplacements(String line) {
Set<AnalyzedTokenReadings> tokens = new LinkedHashSet<>(getReplaceableTokens(line));
List<Replacer> replacers = new ArrayList<>();
for (AnalyzedTokenReadings token : tokens) {
Bag<String> replacePossibilities = mappings.get(getTags(token));
createReplacer(token, replacePossibilities).ifPresent(replacer -> replacers.add(replacer));
// System.out.println((createReplacer(token, replacePossibilities).isPresent()) + " mapping of " + token
// + "\n=>" + replacePossibilities);
}
return replacers;
}
/*-********************************************-*/
public String replaceSomething(String line, int amountOfReplacements) {
List<Replacer> replacers = calculatePossibleReplacements(line);
Set<Replacer> chosenReplacers = new LinkedHashSet<>(
Picker.pickRandomUniqueIndices(Math.min(replacers.size(), amountOfReplacements), replacers.size())
.stream().map(idx -> replacers.get(idx)).collect(Collectors.toList()));
return (new Replacers(chosenReplacers)).replace(line);
}
}
| twinters/torfs-bot | src/main/java/be/thomaswinters/similarreplacer/SimilarWordReplacer.java | 2,514 | // Algemene persoonlijke voornaamwoorden | line_comment | nl | package be.thomaswinters.similarreplacer;
import be.thomaswinters.LambdaExceptionUtil;
import be.thomaswinters.markov.model.data.bags.Bag;
import be.thomaswinters.markov.model.data.bags.WriteableBag;
import be.thomaswinters.markov.model.data.bags.impl.ExclusionBag;
import be.thomaswinters.markov.model.data.bags.impl.MutableBag;
import be.thomaswinters.random.Picker;
import be.thomaswinters.replacement.Replacer;
import be.thomaswinters.replacement.Replacers;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.JLanguageTool;
import org.languagetool.language.Dutch;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
public class SimilarWordReplacer {
/*-********************************************-*
* STATIC TOOLS
*-********************************************-*/
private static final JLanguageTool langTool = new JLanguageTool(new Dutch());
protected static final Random RANDOM = new Random();
/*-********************************************-*/
/*-********************************************-*
* INSTANCE VARIABLES
*-********************************************-*/
private Map<Set<String>, WriteableBag<String>> mappings = new HashMap<>();
/*-********************************************-*/
/*-********************************************-*
* TAGS & TOKEN FILTERING
*-********************************************-*/
protected Set<String> getTags(AnalyzedTokenReadings token) {
return token.getReadings().stream().filter(e -> !e.hasNoTag()).map(e -> e.getPOSTag())
.filter(e -> e != null && !e.equals("SENT_END") && !e.equals("PARA_END")).collect(Collectors.toSet());
}
private static final Set<String> REPLACEMENT_TOKEN_BLACKLIST = new HashSet<>(Arrays.asList(
// Lidwoorden
"de", "het", "een",
// Algemene onderwerpen
"ik", "jij", "je", "u", "wij", "we", "jullie", "hij", "zij", "ze",
// Algemene persoonlijke<SUF>
"hen", "hem", "haar", "mijn", "uw", "jouw", "onze", "ons",
// Algemene werkwoorden
"ben", "bent", "is", "was", "waren", "geweest", "heb", "hebt", "heeft", "hebben", "gehad", "word", "wordt",
"worden", "geworden", "werd", "werden", "laat", "laten", "liet", "lieten", "gelaten", "ga", "gaat", "gaan",
"gegaan", "ging", "gingen", "moet", "moeten", "moest", "moesten", "gemoeten", "mag", "mogen", "mocht",
"mochten", "gemogen", "zal", "zullen", "zult", "zou", "zouden", "kan", "kunnen", "gekunt", "gekunnen",
"hoef", "hoeft", "hoeven", "hoefde", "hoefden", "gehoeven",
// Veelgebruikte woorden
"niet", "iets", "dan", "voort", "erna", "welke", "maar", "van", "voor", "met", "binnenkort", "in", "en",
"teveel", "om", "alles", "elke", "al", "echt", "waar", "waarom", "hoe", "o.a.", "beetje", "enkel", "goed",
"best", "werkende", "meer", "voor", "zit", "echt", "uit", "even", "wel"));
private static final Set<String> REPLACEMENT_TAG_BLACKLIST = new HashSet<>(
Arrays.asList("AVwaar", "AVwr", "DTh", "DTd", "DTe", "DTp", "PRte", "PRnaar", "PRvan", "PN2", "PRVoor",
"PRmet", "PRop", "PRin", "PRom", "PRaan", "AVdr", "CJo"));
private List<AnalyzedTokenReadings> filterTokens(List<AnalyzedTokenReadings> tokens) {
return tokens.stream().filter(e -> e.getToken().trim().length() > 0).filter(e -> !e.getReadings().isEmpty())
.filter(token -> !getTags(token).isEmpty())
.filter(token -> getTags(token).stream().allMatch(tag -> !REPLACEMENT_TAG_BLACKLIST.contains(tag)))
.filter(token -> !REPLACEMENT_TOKEN_BLACKLIST.contains(token.getToken().toLowerCase()))
.collect(Collectors.toList());
}
/*-********************************************-*/
/*-********************************************-*
* PROCESSING KNOWLEDGE INPUT
*-********************************************-*/
public void process(String line) throws IOException {
List<AnalyzedSentence> answers = langTool.analyzeText(line);
for (AnalyzedSentence analyzedSentence : answers) {
List<AnalyzedTokenReadings> tokens = filterTokens(Arrays.asList(analyzedSentence.getTokens()));
for (AnalyzedTokenReadings token : tokens) {
if (token.getToken().trim().length() > 0) {
Set<String> tags = getTags(token);
// Add if valid
if (tags != null && tags.size() > 0) {
if (!mappings.containsKey(tags)) {
mappings.put(tags, new MutableBag<String>());
}
mappings.get(tags).add(token.getToken());
}
}
}
}
}
public void process(List<String> lines) {
lines.forEach(LambdaExceptionUtil.rethrowConsumer(this::process));
}
/*-********************************************-*/
/*-********************************************-*
* REPLACEABLE CALCULATION
*-********************************************-*/
public int getReplaceableSize(Set<String> tags) {
if (!mappings.containsKey(tags)) {
return 0;
}
return mappings.get(tags).size();
}
public List<AnalyzedTokenReadings> getReplaceableTokens(String line) {
List<AnalyzedSentence> answers;
try {
answers = langTool.analyzeText(line);
} catch (IOException e1) {
throw new RuntimeException(e1);
}
List<AnalyzedTokenReadings> tokens = new ArrayList<>();
for (AnalyzedSentence analyzedSentence : answers) {
tokens.addAll(Arrays.asList(analyzedSentence.getTokens()));
}
tokens = filterTokens(tokens).stream().filter(e -> getReplaceableSize(getTags(e)) > 1)
.collect(Collectors.toList());
return tokens;
}
public Optional<Replacer> createReplacer(AnalyzedTokenReadings token, Bag<String> replacePossibilities) {
// Check if there is another possibility than to replace with itself
if (replacePossibilities.isEmpty() || (replacePossibilities.getAmountOfUniqueElements() == 1
&& replacePossibilities.get(0).toLowerCase().equals(token.getToken().toLowerCase()))) {
return Optional.empty();
}
Bag<String> bag = new ExclusionBag<String>(replacePossibilities, Arrays.asList(token.getToken()));
String replacement = pickReplacement(token.getToken(), bag);
Replacer replacer = new Replacer(token.getToken(), replacement, false, true);
return Optional.of(replacer);
}
public String pickReplacement(String replacement, Bag<String> bag) {
return bag.get(RANDOM.nextInt(bag.getAmountOfElements()));
}
public List<Replacer> calculatePossibleReplacements(String line) {
Set<AnalyzedTokenReadings> tokens = new LinkedHashSet<>(getReplaceableTokens(line));
List<Replacer> replacers = new ArrayList<>();
for (AnalyzedTokenReadings token : tokens) {
Bag<String> replacePossibilities = mappings.get(getTags(token));
createReplacer(token, replacePossibilities).ifPresent(replacer -> replacers.add(replacer));
// System.out.println((createReplacer(token, replacePossibilities).isPresent()) + " mapping of " + token
// + "\n=>" + replacePossibilities);
}
return replacers;
}
/*-********************************************-*/
public String replaceSomething(String line, int amountOfReplacements) {
List<Replacer> replacers = calculatePossibleReplacements(line);
Set<Replacer> chosenReplacers = new LinkedHashSet<>(
Picker.pickRandomUniqueIndices(Math.min(replacers.size(), amountOfReplacements), replacers.size())
.stream().map(idx -> replacers.get(idx)).collect(Collectors.toList()));
return (new Replacers(chosenReplacers)).replace(line);
}
}
|
69460_41 | package com.twitter.search.earlybird.partition;
import java.io.IOException;
import java.util.Iterator;
import scala.runtime.BoxedUnit;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.base.Verify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.twitter.search.common.config.Config;
import com.twitter.search.common.indexing.thriftjava.ThriftVersionedEvents;
import com.twitter.search.common.metrics.SearchCounter;
import com.twitter.search.common.metrics.SearchLongGauge;
import com.twitter.search.common.metrics.SearchRateCounter;
import com.twitter.search.common.metrics.SearchTimer;
import com.twitter.search.common.partitioning.snowflakeparser.SnowflakeIdParser;
import com.twitter.search.common.util.GCUtil;
import com.twitter.search.earlybird.EarlybirdStatus;
import com.twitter.search.earlybird.common.CaughtUpMonitor;
import com.twitter.search.earlybird.exception.CriticalExceptionHandler;
import com.twitter.search.earlybird.index.OutOfOrderRealtimeTweetIDMapper;
import com.twitter.search.earlybird.querycache.QueryCacheManager;
import com.twitter.search.earlybird.util.CoordinatedEarlybirdActionInterface;
import com.twitter.util.Await;
import com.twitter.util.Duration;
import com.twitter.util.Future;
import com.twitter.util.TimeoutException;
/**
* This class handles incoming new Tweets. It is responsible for creating segments for the incoming
* Tweets when necessary, triggering optimization on those segments, and writing Tweets to the
* correct segment.
*/
public class TweetCreateHandler {
private static final Logger LOG = LoggerFactory.getLogger(TweetCreateHandler.class);
public static final long LATE_TWEET_TIME_BUFFER_MS = Duration.fromMinutes(1).inMilliseconds();
private static final String STATS_PREFIX = "tweet_create_handler_";
// To get a better idea of which of these succeeded and so on, see stats in SegmentManager.
private IndexingResultCounts indexingResultCounts;
private static final SearchRateCounter TWEETS_IN_WRONG_SEGMENT =
SearchRateCounter.export(STATS_PREFIX + "tweets_in_wrong_segment");
private static final SearchRateCounter SEGMENTS_CLOSED_EARLY =
SearchRateCounter.export(STATS_PREFIX + "segments_closed_early");
private static final SearchRateCounter INSERTED_IN_CURRENT_SEGMENT =
SearchRateCounter.export(STATS_PREFIX + "inserted_in_current_segment");
private static final SearchRateCounter INSERTED_IN_PREVIOUS_SEGMENT =
SearchRateCounter.export(STATS_PREFIX + "inserted_in_previous_segment");
private static final NewSegmentStats NEW_SEGMENT_STATS = new NewSegmentStats();
private static final SearchCounter CREATED_SEGMENTS =
SearchCounter.export(STATS_PREFIX + "created_segments");
private static final SearchRateCounter INCOMING_TWEETS =
SearchRateCounter.export(STATS_PREFIX + "incoming_tweets");
private static final SearchRateCounter INDEXING_SUCCESS =
SearchRateCounter.export(STATS_PREFIX + "indexing_success");
private static final SearchRateCounter INDEXING_FAILURE =
SearchRateCounter.export(STATS_PREFIX + "indexing_failure");
// Various stats and logging around creation of new segments, put in this
// class so that the code is not watered down too much by this.
private static class NewSegmentStats {
private static final String NEW_SEGMENT_STATS_PREFIX =
STATS_PREFIX + "new_segment_";
private static final SearchCounter START_NEW_AFTER_REACHING_LIMIT =
SearchCounter.export(NEW_SEGMENT_STATS_PREFIX + "start_after_reaching_limit");
private static final SearchCounter START_NEW_AFTER_EXCEEDING_MAX_ID =
SearchCounter.export(NEW_SEGMENT_STATS_PREFIX + "start_after_exceeding_max_id");
private static final SearchCounter TIMESLICE_SET_TO_CURRENT_ID =
SearchCounter.export(NEW_SEGMENT_STATS_PREFIX + "timeslice_set_to_current_id");
private static final SearchCounter TIMESLICE_SET_TO_MAX_ID =
SearchCounter.export(NEW_SEGMENT_STATS_PREFIX + "timeslice_set_to_max_id");
private static final SearchLongGauge TIMESPAN_BETWEEN_MAX_AND_CURRENT =
SearchLongGauge.export(NEW_SEGMENT_STATS_PREFIX + "timespan_between_id_and_max");
void recordCreateNewSegment() {
CREATED_SEGMENTS.increment();
}
void recordStartAfterReachingTweetsLimit(int numDocs, int numDocsCutoff,
int maxSegmentSize, int lateTweetBuffer) {
START_NEW_AFTER_REACHING_LIMIT.increment();
LOG.info(String.format(
"Will create new segment: numDocs=%,d, numDocsCutoff=%,d"
+ " | maxSegmentSize=%,d, lateTweetBuffer=%,d",
numDocs, numDocsCutoff, maxSegmentSize, lateTweetBuffer));
}
void recordStartAfterExceedingLargestValidTweetId(long tweetId, long largestValidTweetId) {
START_NEW_AFTER_EXCEEDING_MAX_ID.increment();
LOG.info(String.format(
"Will create new segment: tweetDd=%,d, largestValidTweetID for segment=%,d",
tweetId, largestValidTweetId));
}
void recordSettingTimesliceToCurrentTweet(long tweetID) {
TIMESLICE_SET_TO_CURRENT_ID.increment();
LOG.info("Creating new segment: tweet that triggered it has the largest id we've seen. "
+ " id={}", tweetID);
}
void recordSettingTimesliceToMaxTweetId(long tweetID, long maxTweetID) {
TIMESLICE_SET_TO_MAX_ID.increment();
LOG.info("Creating new segment: tweet that triggered it doesn't have the largest id"
+ " we've seen. tweetId={}, maxTweetId={}",
tweetID, maxTweetID);
long timeDifference =
SnowflakeIdParser.getTimeDifferenceBetweenTweetIDs(maxTweetID, tweetID);
LOG.info("Time difference between max seen and last seen: {} ms", timeDifference);
TIMESPAN_BETWEEN_MAX_AND_CURRENT.set(timeDifference);
}
void wrapNewSegmentCreation(long tweetID, long maxTweetID,
long currentSegmentTimesliceBoundary,
long largestValidTweetIDForCurrentSegment) {
long timeDifferenceStartToMax = SnowflakeIdParser.getTimeDifferenceBetweenTweetIDs(
largestValidTweetIDForCurrentSegment,
currentSegmentTimesliceBoundary);
LOG.info("Time between timeslice boundary and largest valid tweet id: {} ms",
timeDifferenceStartToMax);
LOG.info("Created new segment: (tweetId={}, maxTweetId={}, maxTweetId-tweetId={} "
+ " | currentSegmentTimesliceBoundary={}, largestValidTweetIDForSegment={})",
tweetID, maxTweetID, maxTweetID - tweetID, currentSegmentTimesliceBoundary,
largestValidTweetIDForCurrentSegment);
}
}
private final SegmentManager segmentManager;
private final MultiSegmentTermDictionaryManager multiSegmentTermDictionaryManager;
private final int maxSegmentSize;
private final int lateTweetBuffer;
private long maxTweetID = Long.MIN_VALUE;
private long largestValidTweetIDForCurrentSegment;
private long currentSegmentTimesliceBoundary;
private OptimizingSegmentWriter currentSegment;
private OptimizingSegmentWriter previousSegment;
private final QueryCacheManager queryCacheManager;
private final CriticalExceptionHandler criticalExceptionHandler;
private final SearchIndexingMetricSet searchIndexingMetricSet;
private final CoordinatedEarlybirdActionInterface postOptimizationRebuildsAction;
private final CoordinatedEarlybirdActionInterface gcAction;
private final CaughtUpMonitor indexCaughtUpMonitor;
private final OptimizationAndFlushingCoordinationLock optimizationAndFlushingCoordinationLock;
public TweetCreateHandler(
SegmentManager segmentManager,
SearchIndexingMetricSet searchIndexingMetricSet,
CriticalExceptionHandler criticalExceptionHandler,
MultiSegmentTermDictionaryManager multiSegmentTermDictionaryManager,
QueryCacheManager queryCacheManager,
CoordinatedEarlybirdActionInterface postOptimizationRebuildsAction,
CoordinatedEarlybirdActionInterface gcAction,
int lateTweetBuffer,
int maxSegmentSize,
CaughtUpMonitor indexCaughtUpMonitor,
OptimizationAndFlushingCoordinationLock optimizationAndFlushingCoordinationLock
) {
this.segmentManager = segmentManager;
this.criticalExceptionHandler = criticalExceptionHandler;
this.multiSegmentTermDictionaryManager = multiSegmentTermDictionaryManager;
this.queryCacheManager = queryCacheManager;
this.indexingResultCounts = new IndexingResultCounts();
this.searchIndexingMetricSet = searchIndexingMetricSet;
this.postOptimizationRebuildsAction = postOptimizationRebuildsAction;
this.gcAction = gcAction;
this.indexCaughtUpMonitor = indexCaughtUpMonitor;
Preconditions.checkState(lateTweetBuffer < maxSegmentSize);
this.lateTweetBuffer = lateTweetBuffer;
this.maxSegmentSize = maxSegmentSize;
this.optimizationAndFlushingCoordinationLock = optimizationAndFlushingCoordinationLock;
}
void prepareAfterStartingWithIndex(long maxIndexedTweetId) {
LOG.info("Preparing after starting with an index.");
Iterator<SegmentInfo> segmentInfosIterator =
segmentManager
.getSegmentInfos(SegmentManager.Filter.All, SegmentManager.Order.NEW_TO_OLD)
.iterator();
// Setup the last segment.
Verify.verify(segmentInfosIterator.hasNext(), "at least one segment expected");
ISegmentWriter lastWriter = segmentManager.getSegmentWriterForID(
segmentInfosIterator.next().getTimeSliceID());
Verify.verify(lastWriter != null);
LOG.info("TweetCreateHandler found last writer: {}", lastWriter.getSegmentInfo().toString());
this.currentSegmentTimesliceBoundary = lastWriter.getSegmentInfo().getTimeSliceID();
this.largestValidTweetIDForCurrentSegment =
OutOfOrderRealtimeTweetIDMapper.calculateMaxTweetID(currentSegmentTimesliceBoundary);
this.currentSegment = (OptimizingSegmentWriter) lastWriter;
if (maxIndexedTweetId == -1) {
maxTweetID = lastWriter.getSegmentInfo().getIndexSegment().getMaxTweetId();
LOG.info("Max tweet id = {}", maxTweetID);
} else {
// See SEARCH-31032
maxTweetID = maxIndexedTweetId;
}
// If we have a previous segment that's not optimized, set it up too, we still need to pick
// it up for optimization and we might still be able to add tweets to it.
if (segmentInfosIterator.hasNext()) {
SegmentInfo previousSegmentInfo = segmentInfosIterator.next();
if (!previousSegmentInfo.isOptimized()) {
ISegmentWriter previousSegmentWriter = segmentManager.getSegmentWriterForID(
previousSegmentInfo.getTimeSliceID());
if (previousSegmentWriter != null) {
LOG.info("Picked previous segment");
this.previousSegment = (OptimizingSegmentWriter) previousSegmentWriter;
} else {
// Should not happen.
LOG.error("Not found previous segment writer");
}
} else {
LOG.info("Previous segment info is optimized");
}
} else {
LOG.info("Previous segment info not found, we only have one segment");
}
}
private void updateIndexFreshness() {
searchIndexingMetricSet.highestStatusId.set(maxTweetID);
long tweetTimestamp = SnowflakeIdParser.getTimestampFromTweetId(
searchIndexingMetricSet.highestStatusId.get());
searchIndexingMetricSet.freshestTweetTimeMillis.set(tweetTimestamp);
}
/**
* Index a new TVE representing a Tweet create event.
*/
public void handleTweetCreate(ThriftVersionedEvents tve) throws IOException {
INCOMING_TWEETS.increment();
long id = tve.getId();
maxTweetID = Math.max(id, maxTweetID);
updateIndexFreshness();
boolean shouldCreateNewSegment = false;
if (currentSegment == null) {
shouldCreateNewSegment = true;
LOG.info("Will create new segment: current segment is null");
} else {
int numDocs = currentSegment.getSegmentInfo().getIndexSegment().getNumDocs();
int numDocsCutoff = maxSegmentSize - lateTweetBuffer;
if (numDocs >= numDocsCutoff) {
NEW_SEGMENT_STATS.recordStartAfterReachingTweetsLimit(numDocs, numDocsCutoff,
maxSegmentSize, lateTweetBuffer);
shouldCreateNewSegment = true;
} else if (id > largestValidTweetIDForCurrentSegment) {
NEW_SEGMENT_STATS.recordStartAfterExceedingLargestValidTweetId(id,
largestValidTweetIDForCurrentSegment);
shouldCreateNewSegment = true;
}
}
if (shouldCreateNewSegment) {
createNewSegment(id);
}
if (previousSegment != null) {
// Inserts and some updates can't be applied to an optimized segment, so we want to wait at
// least LATE_TWEET_TIME_BUFFER between when we created the new segment and when we optimize
// the previous segment, in case there are late tweets.
// We leave a large (150k, typically) buffer in the segment so that we don't have to close
// the previousSegment before LATE_TWEET_TIME_BUFFER has passed, but if we index
// lateTweetBuffer Tweets before optimizing, then we must optimize,
// so that we don't insert more than max segment size tweets into the previous segment.
long relativeTweetAgeMs =
SnowflakeIdParser.getTimeDifferenceBetweenTweetIDs(id, currentSegmentTimesliceBoundary);
boolean needToOptimize = false;
int numDocs = previousSegment.getSegmentInfo().getIndexSegment().getNumDocs();
String previousSegmentName = previousSegment.getSegmentInfo().getSegmentName();
if (numDocs >= maxSegmentSize) {
LOG.info(String.format("Previous segment (%s) reached maxSegmentSize, need to optimize it."
+ " numDocs=%,d, maxSegmentSize=%,d", previousSegmentName, numDocs, maxSegmentSize));
needToOptimize = true;
} else if (relativeTweetAgeMs > LATE_TWEET_TIME_BUFFER_MS) {
LOG.info(String.format("Previous segment (%s) is old enough, we can optimize it."
+ " Got tweet past time buffer of %,d ms by: %,d ms", previousSegmentName,
LATE_TWEET_TIME_BUFFER_MS, relativeTweetAgeMs - LATE_TWEET_TIME_BUFFER_MS));
needToOptimize = true;
}
if (needToOptimize) {
optimizePreviousSegment();
}
}
ISegmentWriter segmentWriter;
if (id >= currentSegmentTimesliceBoundary) {
INSERTED_IN_CURRENT_SEGMENT.increment();
segmentWriter = currentSegment;
} else if (previousSegment != null) {
INSERTED_IN_PREVIOUS_SEGMENT.increment();
segmentWriter = previousSegment;
} else {
TWEETS_IN_WRONG_SEGMENT.increment();
LOG.info("Inserting TVE ({}) into the current segment ({}) even though it should have gone "
+ "in a previous segment.", id, currentSegmentTimesliceBoundary);
segmentWriter = currentSegment;
}
SearchTimer timer = searchIndexingMetricSet.statusStats.startNewTimer();
ISegmentWriter.Result result = segmentWriter.indexThriftVersionedEvents(tve);
searchIndexingMetricSet.statusStats.stopTimerAndIncrement(timer);
if (result == ISegmentWriter.Result.SUCCESS) {
INDEXING_SUCCESS.increment();
} else {
INDEXING_FAILURE.increment();
}
indexingResultCounts.countResult(result);
}
/**
* Many tests need to verify behavior with segments optimized & unoptimized, so we need to expose
* this.
*/
@VisibleForTesting
public Future<SegmentInfo> optimizePreviousSegment() {
String segmentName = previousSegment.getSegmentInfo().getSegmentName();
previousSegment.getSegmentInfo().setIndexing(false);
LOG.info("Optimizing previous segment: {}", segmentName);
segmentManager.logState("Starting optimization for segment: " + segmentName);
Future<SegmentInfo> future = previousSegment
.startOptimization(gcAction, optimizationAndFlushingCoordinationLock)
.map(this::postOptimizationSteps)
.onFailure(t -> {
criticalExceptionHandler.handle(this, t);
return BoxedUnit.UNIT;
});
waitForOptimizationIfInTest(future);
previousSegment = null;
return future;
}
/**
* In tests, it's easier if when a segment starts optimizing, we know that it will finish
* optimizing. This way we have no race condition where we're surprised that something that
* started optimizing is not ready.
*
* In prod we don't have this problem. Segments run for 10 hours and optimization is 20 minutes
* so there's no need for extra synchronization.
*/
private void waitForOptimizationIfInTest(Future<SegmentInfo> future) {
if (Config.environmentIsTest()) {
try {
Await.ready(future);
LOG.info("Optimizing is done");
} catch (InterruptedException | TimeoutException ex) {
LOG.info("Exception while optimizing", ex);
}
}
}
private SegmentInfo postOptimizationSteps(SegmentInfo optimizedSegmentInfo) {
segmentManager.updateStats();
// See SEARCH-32175
optimizedSegmentInfo.setComplete(true);
String segmentName = optimizedSegmentInfo.getSegmentName();
LOG.info("Finished optimization for segment: " + segmentName);
segmentManager.logState(
"Finished optimization for segment: " + segmentName);
/*
* Building the multi segment term dictionary causes GC pauses. The reason for this is because
* it's pretty big (possible ~15GB). When it's allocated, we have to copy a lot of data from
* survivor space to old gen. That causes several GC pauses. See SEARCH-33544
*
* GC pauses are in general not fatal, but since all instances finish a segment at roughly the
* same time, they might happen at the same time and then it's a problem.
*
* Some possible solutions to this problem would be to build this dictionary in some data
* structures that are pre-allocated or to build only the part for the last segment, as
* everything else doesn't change. These solutions are a bit difficult to implement and this
* here is an easy workaround.
*
* Note that we might finish optimizing a segment and then it might take ~60+ minutes until it's
* a particular Earlybird's turn to run this code. The effect of this is going to be that we
* are not going to use the multi segment dictionary for the last two segments, one of which is
* still pretty small. That's not terrible, since right before optimization we're not using
* the dictionary for the last segment anyways, since it's still not optimized.
*/
try {
LOG.info("Acquire coordination lock before beginning post_optimization_rebuilds action.");
optimizationAndFlushingCoordinationLock.lock();
LOG.info("Successfully acquired coordination lock for post_optimization_rebuilds action.");
postOptimizationRebuildsAction.retryActionUntilRan(
"post optimization rebuilds", () -> {
Stopwatch stopwatch = Stopwatch.createStarted();
LOG.info("Starting to build multi term dictionary for {}", segmentName);
boolean result = multiSegmentTermDictionaryManager.buildDictionary();
LOG.info("Done building multi term dictionary for {} in {}, result: {}",
segmentName, stopwatch, result);
queryCacheManager.rebuildQueryCachesAfterSegmentOptimization(
optimizedSegmentInfo);
// This is a serial full GC and it defragments the memory so things can run smoothly
// until the next segment rolls. What we have observed is that if we don't do that
// later on some earlybirds can have promotion failures on an old gen that hasn't
// reached the initiating occupancy limit and these promotions failures can trigger a
// long (1.5 min) full GC. That usually happens because of fragmentation issues.
GCUtil.runGC();
// Wait for indexing to catch up before rejoining the serverset. We only need to do
// this if the host has already finished startup.
if (EarlybirdStatus.hasStarted()) {
indexCaughtUpMonitor.resetAndWaitUntilCaughtUp();
}
});
} finally {
LOG.info("Finished post_optimization_rebuilds action. Releasing coordination lock.");
optimizationAndFlushingCoordinationLock.unlock();
}
return optimizedSegmentInfo;
}
/**
* Many tests rely on precise segment boundaries, so we expose this to allow them to create a
* particular segment.
*/
@VisibleForTesting
public void createNewSegment(long tweetID) throws IOException {
NEW_SEGMENT_STATS.recordCreateNewSegment();
if (previousSegment != null) {
// We shouldn't have more than one unoptimized segment, so if we get to this point and the
// previousSegment has not been optimized and set to null, start optimizing it before
// creating the next one. Note that this is a weird case and would only happen if we get
// Tweets with drastically different IDs than we expect, or there is a large amount of time
// where no Tweets are created in this partition.
LOG.error("Creating new segment for Tweet {} when the previous segment {} was not sealed. "
+ "Current segment: {}. Documents: {}. largestValidTweetIDForSegment: {}.",
tweetID,
previousSegment.getSegmentInfo().getTimeSliceID(),
currentSegment.getSegmentInfo().getTimeSliceID(),
currentSegment.getSegmentInfo().getIndexSegment().getNumDocs(),
largestValidTweetIDForCurrentSegment);
optimizePreviousSegment();
SEGMENTS_CLOSED_EARLY.increment();
}
previousSegment = currentSegment;
// We have two cases:
//
// Case 1:
// If the greatest Tweet ID we have seen is tweetID, then when we want to create a new segment
// with that ID, so the Tweet being processed goes into the new segment.
//
// Case 2:
// If the tweetID is bigger than the max tweetID, then this method is being called directly from
// tests, so we didn't update the maxTweetID, so we can create a new segment with the new
// Tweet ID.
//
// Case 3:
// If it's not the greatest Tweet ID we have seen, then we don't want to create a
// segment boundary that is lower than any Tweet IDs in the current segment, because then
// some tweets from the previous segment would be in the wrong segment, so create a segment
// that has a greater ID than any Tweets that we have seen.
//
// Example:
// - We have seen tweets 3, 10, 5, 6.
// - We now see tweet 7 and we decide it's time to create a new segment.
// - The new segment will start at tweet 11. It can't start at tweet 7, because
// tweet 10 will be in the wrong segment.
// - Tweet 7 that we just saw will end up in the previous segment.
if (maxTweetID <= tweetID) {
currentSegmentTimesliceBoundary = tweetID;
NEW_SEGMENT_STATS.recordSettingTimesliceToCurrentTweet(tweetID);
} else {
currentSegmentTimesliceBoundary = maxTweetID + 1;
NEW_SEGMENT_STATS.recordSettingTimesliceToMaxTweetId(tweetID, maxTweetID);
}
currentSegment = segmentManager.createAndPutOptimizingSegmentWriter(
currentSegmentTimesliceBoundary);
currentSegment.getSegmentInfo().setIndexing(true);
largestValidTweetIDForCurrentSegment =
OutOfOrderRealtimeTweetIDMapper.calculateMaxTweetID(currentSegmentTimesliceBoundary);
NEW_SEGMENT_STATS.wrapNewSegmentCreation(tweetID, maxTweetID,
currentSegmentTimesliceBoundary, largestValidTweetIDForCurrentSegment);
segmentManager.removeExcessSegments();
}
void logState() {
LOG.info("TweetCreateHandler:");
LOG.info(String.format(" tweets sent for indexing: %,d",
indexingResultCounts.getIndexingCalls()));
LOG.info(String.format(" non-retriable failure: %,d",
indexingResultCounts.getFailureNotRetriable()));
LOG.info(String.format(" retriable failure: %,d",
indexingResultCounts.getFailureRetriable()));
LOG.info(String.format(" successfully indexed: %,d",
indexingResultCounts.getIndexingSuccess()));
LOG.info(String.format(" tweets in wrong segment: %,d", TWEETS_IN_WRONG_SEGMENT.getCount()));
LOG.info(String.format(" segments closed early: %,d", SEGMENTS_CLOSED_EARLY.getCount()));
}
}
| twitter/the-algorithm | src/java/com/twitter/search/earlybird/partition/TweetCreateHandler.java | 7,136 | // - We have seen tweets 3, 10, 5, 6. | line_comment | nl | package com.twitter.search.earlybird.partition;
import java.io.IOException;
import java.util.Iterator;
import scala.runtime.BoxedUnit;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.base.Verify;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.twitter.search.common.config.Config;
import com.twitter.search.common.indexing.thriftjava.ThriftVersionedEvents;
import com.twitter.search.common.metrics.SearchCounter;
import com.twitter.search.common.metrics.SearchLongGauge;
import com.twitter.search.common.metrics.SearchRateCounter;
import com.twitter.search.common.metrics.SearchTimer;
import com.twitter.search.common.partitioning.snowflakeparser.SnowflakeIdParser;
import com.twitter.search.common.util.GCUtil;
import com.twitter.search.earlybird.EarlybirdStatus;
import com.twitter.search.earlybird.common.CaughtUpMonitor;
import com.twitter.search.earlybird.exception.CriticalExceptionHandler;
import com.twitter.search.earlybird.index.OutOfOrderRealtimeTweetIDMapper;
import com.twitter.search.earlybird.querycache.QueryCacheManager;
import com.twitter.search.earlybird.util.CoordinatedEarlybirdActionInterface;
import com.twitter.util.Await;
import com.twitter.util.Duration;
import com.twitter.util.Future;
import com.twitter.util.TimeoutException;
/**
* This class handles incoming new Tweets. It is responsible for creating segments for the incoming
* Tweets when necessary, triggering optimization on those segments, and writing Tweets to the
* correct segment.
*/
public class TweetCreateHandler {
private static final Logger LOG = LoggerFactory.getLogger(TweetCreateHandler.class);
public static final long LATE_TWEET_TIME_BUFFER_MS = Duration.fromMinutes(1).inMilliseconds();
private static final String STATS_PREFIX = "tweet_create_handler_";
// To get a better idea of which of these succeeded and so on, see stats in SegmentManager.
private IndexingResultCounts indexingResultCounts;
private static final SearchRateCounter TWEETS_IN_WRONG_SEGMENT =
SearchRateCounter.export(STATS_PREFIX + "tweets_in_wrong_segment");
private static final SearchRateCounter SEGMENTS_CLOSED_EARLY =
SearchRateCounter.export(STATS_PREFIX + "segments_closed_early");
private static final SearchRateCounter INSERTED_IN_CURRENT_SEGMENT =
SearchRateCounter.export(STATS_PREFIX + "inserted_in_current_segment");
private static final SearchRateCounter INSERTED_IN_PREVIOUS_SEGMENT =
SearchRateCounter.export(STATS_PREFIX + "inserted_in_previous_segment");
private static final NewSegmentStats NEW_SEGMENT_STATS = new NewSegmentStats();
private static final SearchCounter CREATED_SEGMENTS =
SearchCounter.export(STATS_PREFIX + "created_segments");
private static final SearchRateCounter INCOMING_TWEETS =
SearchRateCounter.export(STATS_PREFIX + "incoming_tweets");
private static final SearchRateCounter INDEXING_SUCCESS =
SearchRateCounter.export(STATS_PREFIX + "indexing_success");
private static final SearchRateCounter INDEXING_FAILURE =
SearchRateCounter.export(STATS_PREFIX + "indexing_failure");
// Various stats and logging around creation of new segments, put in this
// class so that the code is not watered down too much by this.
private static class NewSegmentStats {
private static final String NEW_SEGMENT_STATS_PREFIX =
STATS_PREFIX + "new_segment_";
private static final SearchCounter START_NEW_AFTER_REACHING_LIMIT =
SearchCounter.export(NEW_SEGMENT_STATS_PREFIX + "start_after_reaching_limit");
private static final SearchCounter START_NEW_AFTER_EXCEEDING_MAX_ID =
SearchCounter.export(NEW_SEGMENT_STATS_PREFIX + "start_after_exceeding_max_id");
private static final SearchCounter TIMESLICE_SET_TO_CURRENT_ID =
SearchCounter.export(NEW_SEGMENT_STATS_PREFIX + "timeslice_set_to_current_id");
private static final SearchCounter TIMESLICE_SET_TO_MAX_ID =
SearchCounter.export(NEW_SEGMENT_STATS_PREFIX + "timeslice_set_to_max_id");
private static final SearchLongGauge TIMESPAN_BETWEEN_MAX_AND_CURRENT =
SearchLongGauge.export(NEW_SEGMENT_STATS_PREFIX + "timespan_between_id_and_max");
void recordCreateNewSegment() {
CREATED_SEGMENTS.increment();
}
void recordStartAfterReachingTweetsLimit(int numDocs, int numDocsCutoff,
int maxSegmentSize, int lateTweetBuffer) {
START_NEW_AFTER_REACHING_LIMIT.increment();
LOG.info(String.format(
"Will create new segment: numDocs=%,d, numDocsCutoff=%,d"
+ " | maxSegmentSize=%,d, lateTweetBuffer=%,d",
numDocs, numDocsCutoff, maxSegmentSize, lateTweetBuffer));
}
void recordStartAfterExceedingLargestValidTweetId(long tweetId, long largestValidTweetId) {
START_NEW_AFTER_EXCEEDING_MAX_ID.increment();
LOG.info(String.format(
"Will create new segment: tweetDd=%,d, largestValidTweetID for segment=%,d",
tweetId, largestValidTweetId));
}
void recordSettingTimesliceToCurrentTweet(long tweetID) {
TIMESLICE_SET_TO_CURRENT_ID.increment();
LOG.info("Creating new segment: tweet that triggered it has the largest id we've seen. "
+ " id={}", tweetID);
}
void recordSettingTimesliceToMaxTweetId(long tweetID, long maxTweetID) {
TIMESLICE_SET_TO_MAX_ID.increment();
LOG.info("Creating new segment: tweet that triggered it doesn't have the largest id"
+ " we've seen. tweetId={}, maxTweetId={}",
tweetID, maxTweetID);
long timeDifference =
SnowflakeIdParser.getTimeDifferenceBetweenTweetIDs(maxTweetID, tweetID);
LOG.info("Time difference between max seen and last seen: {} ms", timeDifference);
TIMESPAN_BETWEEN_MAX_AND_CURRENT.set(timeDifference);
}
void wrapNewSegmentCreation(long tweetID, long maxTweetID,
long currentSegmentTimesliceBoundary,
long largestValidTweetIDForCurrentSegment) {
long timeDifferenceStartToMax = SnowflakeIdParser.getTimeDifferenceBetweenTweetIDs(
largestValidTweetIDForCurrentSegment,
currentSegmentTimesliceBoundary);
LOG.info("Time between timeslice boundary and largest valid tweet id: {} ms",
timeDifferenceStartToMax);
LOG.info("Created new segment: (tweetId={}, maxTweetId={}, maxTweetId-tweetId={} "
+ " | currentSegmentTimesliceBoundary={}, largestValidTweetIDForSegment={})",
tweetID, maxTweetID, maxTweetID - tweetID, currentSegmentTimesliceBoundary,
largestValidTweetIDForCurrentSegment);
}
}
private final SegmentManager segmentManager;
private final MultiSegmentTermDictionaryManager multiSegmentTermDictionaryManager;
private final int maxSegmentSize;
private final int lateTweetBuffer;
private long maxTweetID = Long.MIN_VALUE;
private long largestValidTweetIDForCurrentSegment;
private long currentSegmentTimesliceBoundary;
private OptimizingSegmentWriter currentSegment;
private OptimizingSegmentWriter previousSegment;
private final QueryCacheManager queryCacheManager;
private final CriticalExceptionHandler criticalExceptionHandler;
private final SearchIndexingMetricSet searchIndexingMetricSet;
private final CoordinatedEarlybirdActionInterface postOptimizationRebuildsAction;
private final CoordinatedEarlybirdActionInterface gcAction;
private final CaughtUpMonitor indexCaughtUpMonitor;
private final OptimizationAndFlushingCoordinationLock optimizationAndFlushingCoordinationLock;
public TweetCreateHandler(
SegmentManager segmentManager,
SearchIndexingMetricSet searchIndexingMetricSet,
CriticalExceptionHandler criticalExceptionHandler,
MultiSegmentTermDictionaryManager multiSegmentTermDictionaryManager,
QueryCacheManager queryCacheManager,
CoordinatedEarlybirdActionInterface postOptimizationRebuildsAction,
CoordinatedEarlybirdActionInterface gcAction,
int lateTweetBuffer,
int maxSegmentSize,
CaughtUpMonitor indexCaughtUpMonitor,
OptimizationAndFlushingCoordinationLock optimizationAndFlushingCoordinationLock
) {
this.segmentManager = segmentManager;
this.criticalExceptionHandler = criticalExceptionHandler;
this.multiSegmentTermDictionaryManager = multiSegmentTermDictionaryManager;
this.queryCacheManager = queryCacheManager;
this.indexingResultCounts = new IndexingResultCounts();
this.searchIndexingMetricSet = searchIndexingMetricSet;
this.postOptimizationRebuildsAction = postOptimizationRebuildsAction;
this.gcAction = gcAction;
this.indexCaughtUpMonitor = indexCaughtUpMonitor;
Preconditions.checkState(lateTweetBuffer < maxSegmentSize);
this.lateTweetBuffer = lateTweetBuffer;
this.maxSegmentSize = maxSegmentSize;
this.optimizationAndFlushingCoordinationLock = optimizationAndFlushingCoordinationLock;
}
void prepareAfterStartingWithIndex(long maxIndexedTweetId) {
LOG.info("Preparing after starting with an index.");
Iterator<SegmentInfo> segmentInfosIterator =
segmentManager
.getSegmentInfos(SegmentManager.Filter.All, SegmentManager.Order.NEW_TO_OLD)
.iterator();
// Setup the last segment.
Verify.verify(segmentInfosIterator.hasNext(), "at least one segment expected");
ISegmentWriter lastWriter = segmentManager.getSegmentWriterForID(
segmentInfosIterator.next().getTimeSliceID());
Verify.verify(lastWriter != null);
LOG.info("TweetCreateHandler found last writer: {}", lastWriter.getSegmentInfo().toString());
this.currentSegmentTimesliceBoundary = lastWriter.getSegmentInfo().getTimeSliceID();
this.largestValidTweetIDForCurrentSegment =
OutOfOrderRealtimeTweetIDMapper.calculateMaxTweetID(currentSegmentTimesliceBoundary);
this.currentSegment = (OptimizingSegmentWriter) lastWriter;
if (maxIndexedTweetId == -1) {
maxTweetID = lastWriter.getSegmentInfo().getIndexSegment().getMaxTweetId();
LOG.info("Max tweet id = {}", maxTweetID);
} else {
// See SEARCH-31032
maxTweetID = maxIndexedTweetId;
}
// If we have a previous segment that's not optimized, set it up too, we still need to pick
// it up for optimization and we might still be able to add tweets to it.
if (segmentInfosIterator.hasNext()) {
SegmentInfo previousSegmentInfo = segmentInfosIterator.next();
if (!previousSegmentInfo.isOptimized()) {
ISegmentWriter previousSegmentWriter = segmentManager.getSegmentWriterForID(
previousSegmentInfo.getTimeSliceID());
if (previousSegmentWriter != null) {
LOG.info("Picked previous segment");
this.previousSegment = (OptimizingSegmentWriter) previousSegmentWriter;
} else {
// Should not happen.
LOG.error("Not found previous segment writer");
}
} else {
LOG.info("Previous segment info is optimized");
}
} else {
LOG.info("Previous segment info not found, we only have one segment");
}
}
private void updateIndexFreshness() {
searchIndexingMetricSet.highestStatusId.set(maxTweetID);
long tweetTimestamp = SnowflakeIdParser.getTimestampFromTweetId(
searchIndexingMetricSet.highestStatusId.get());
searchIndexingMetricSet.freshestTweetTimeMillis.set(tweetTimestamp);
}
/**
* Index a new TVE representing a Tweet create event.
*/
public void handleTweetCreate(ThriftVersionedEvents tve) throws IOException {
INCOMING_TWEETS.increment();
long id = tve.getId();
maxTweetID = Math.max(id, maxTweetID);
updateIndexFreshness();
boolean shouldCreateNewSegment = false;
if (currentSegment == null) {
shouldCreateNewSegment = true;
LOG.info("Will create new segment: current segment is null");
} else {
int numDocs = currentSegment.getSegmentInfo().getIndexSegment().getNumDocs();
int numDocsCutoff = maxSegmentSize - lateTweetBuffer;
if (numDocs >= numDocsCutoff) {
NEW_SEGMENT_STATS.recordStartAfterReachingTweetsLimit(numDocs, numDocsCutoff,
maxSegmentSize, lateTweetBuffer);
shouldCreateNewSegment = true;
} else if (id > largestValidTweetIDForCurrentSegment) {
NEW_SEGMENT_STATS.recordStartAfterExceedingLargestValidTweetId(id,
largestValidTweetIDForCurrentSegment);
shouldCreateNewSegment = true;
}
}
if (shouldCreateNewSegment) {
createNewSegment(id);
}
if (previousSegment != null) {
// Inserts and some updates can't be applied to an optimized segment, so we want to wait at
// least LATE_TWEET_TIME_BUFFER between when we created the new segment and when we optimize
// the previous segment, in case there are late tweets.
// We leave a large (150k, typically) buffer in the segment so that we don't have to close
// the previousSegment before LATE_TWEET_TIME_BUFFER has passed, but if we index
// lateTweetBuffer Tweets before optimizing, then we must optimize,
// so that we don't insert more than max segment size tweets into the previous segment.
long relativeTweetAgeMs =
SnowflakeIdParser.getTimeDifferenceBetweenTweetIDs(id, currentSegmentTimesliceBoundary);
boolean needToOptimize = false;
int numDocs = previousSegment.getSegmentInfo().getIndexSegment().getNumDocs();
String previousSegmentName = previousSegment.getSegmentInfo().getSegmentName();
if (numDocs >= maxSegmentSize) {
LOG.info(String.format("Previous segment (%s) reached maxSegmentSize, need to optimize it."
+ " numDocs=%,d, maxSegmentSize=%,d", previousSegmentName, numDocs, maxSegmentSize));
needToOptimize = true;
} else if (relativeTweetAgeMs > LATE_TWEET_TIME_BUFFER_MS) {
LOG.info(String.format("Previous segment (%s) is old enough, we can optimize it."
+ " Got tweet past time buffer of %,d ms by: %,d ms", previousSegmentName,
LATE_TWEET_TIME_BUFFER_MS, relativeTweetAgeMs - LATE_TWEET_TIME_BUFFER_MS));
needToOptimize = true;
}
if (needToOptimize) {
optimizePreviousSegment();
}
}
ISegmentWriter segmentWriter;
if (id >= currentSegmentTimesliceBoundary) {
INSERTED_IN_CURRENT_SEGMENT.increment();
segmentWriter = currentSegment;
} else if (previousSegment != null) {
INSERTED_IN_PREVIOUS_SEGMENT.increment();
segmentWriter = previousSegment;
} else {
TWEETS_IN_WRONG_SEGMENT.increment();
LOG.info("Inserting TVE ({}) into the current segment ({}) even though it should have gone "
+ "in a previous segment.", id, currentSegmentTimesliceBoundary);
segmentWriter = currentSegment;
}
SearchTimer timer = searchIndexingMetricSet.statusStats.startNewTimer();
ISegmentWriter.Result result = segmentWriter.indexThriftVersionedEvents(tve);
searchIndexingMetricSet.statusStats.stopTimerAndIncrement(timer);
if (result == ISegmentWriter.Result.SUCCESS) {
INDEXING_SUCCESS.increment();
} else {
INDEXING_FAILURE.increment();
}
indexingResultCounts.countResult(result);
}
/**
* Many tests need to verify behavior with segments optimized & unoptimized, so we need to expose
* this.
*/
@VisibleForTesting
public Future<SegmentInfo> optimizePreviousSegment() {
String segmentName = previousSegment.getSegmentInfo().getSegmentName();
previousSegment.getSegmentInfo().setIndexing(false);
LOG.info("Optimizing previous segment: {}", segmentName);
segmentManager.logState("Starting optimization for segment: " + segmentName);
Future<SegmentInfo> future = previousSegment
.startOptimization(gcAction, optimizationAndFlushingCoordinationLock)
.map(this::postOptimizationSteps)
.onFailure(t -> {
criticalExceptionHandler.handle(this, t);
return BoxedUnit.UNIT;
});
waitForOptimizationIfInTest(future);
previousSegment = null;
return future;
}
/**
* In tests, it's easier if when a segment starts optimizing, we know that it will finish
* optimizing. This way we have no race condition where we're surprised that something that
* started optimizing is not ready.
*
* In prod we don't have this problem. Segments run for 10 hours and optimization is 20 minutes
* so there's no need for extra synchronization.
*/
private void waitForOptimizationIfInTest(Future<SegmentInfo> future) {
if (Config.environmentIsTest()) {
try {
Await.ready(future);
LOG.info("Optimizing is done");
} catch (InterruptedException | TimeoutException ex) {
LOG.info("Exception while optimizing", ex);
}
}
}
private SegmentInfo postOptimizationSteps(SegmentInfo optimizedSegmentInfo) {
segmentManager.updateStats();
// See SEARCH-32175
optimizedSegmentInfo.setComplete(true);
String segmentName = optimizedSegmentInfo.getSegmentName();
LOG.info("Finished optimization for segment: " + segmentName);
segmentManager.logState(
"Finished optimization for segment: " + segmentName);
/*
* Building the multi segment term dictionary causes GC pauses. The reason for this is because
* it's pretty big (possible ~15GB). When it's allocated, we have to copy a lot of data from
* survivor space to old gen. That causes several GC pauses. See SEARCH-33544
*
* GC pauses are in general not fatal, but since all instances finish a segment at roughly the
* same time, they might happen at the same time and then it's a problem.
*
* Some possible solutions to this problem would be to build this dictionary in some data
* structures that are pre-allocated or to build only the part for the last segment, as
* everything else doesn't change. These solutions are a bit difficult to implement and this
* here is an easy workaround.
*
* Note that we might finish optimizing a segment and then it might take ~60+ minutes until it's
* a particular Earlybird's turn to run this code. The effect of this is going to be that we
* are not going to use the multi segment dictionary for the last two segments, one of which is
* still pretty small. That's not terrible, since right before optimization we're not using
* the dictionary for the last segment anyways, since it's still not optimized.
*/
try {
LOG.info("Acquire coordination lock before beginning post_optimization_rebuilds action.");
optimizationAndFlushingCoordinationLock.lock();
LOG.info("Successfully acquired coordination lock for post_optimization_rebuilds action.");
postOptimizationRebuildsAction.retryActionUntilRan(
"post optimization rebuilds", () -> {
Stopwatch stopwatch = Stopwatch.createStarted();
LOG.info("Starting to build multi term dictionary for {}", segmentName);
boolean result = multiSegmentTermDictionaryManager.buildDictionary();
LOG.info("Done building multi term dictionary for {} in {}, result: {}",
segmentName, stopwatch, result);
queryCacheManager.rebuildQueryCachesAfterSegmentOptimization(
optimizedSegmentInfo);
// This is a serial full GC and it defragments the memory so things can run smoothly
// until the next segment rolls. What we have observed is that if we don't do that
// later on some earlybirds can have promotion failures on an old gen that hasn't
// reached the initiating occupancy limit and these promotions failures can trigger a
// long (1.5 min) full GC. That usually happens because of fragmentation issues.
GCUtil.runGC();
// Wait for indexing to catch up before rejoining the serverset. We only need to do
// this if the host has already finished startup.
if (EarlybirdStatus.hasStarted()) {
indexCaughtUpMonitor.resetAndWaitUntilCaughtUp();
}
});
} finally {
LOG.info("Finished post_optimization_rebuilds action. Releasing coordination lock.");
optimizationAndFlushingCoordinationLock.unlock();
}
return optimizedSegmentInfo;
}
/**
* Many tests rely on precise segment boundaries, so we expose this to allow them to create a
* particular segment.
*/
@VisibleForTesting
public void createNewSegment(long tweetID) throws IOException {
NEW_SEGMENT_STATS.recordCreateNewSegment();
if (previousSegment != null) {
// We shouldn't have more than one unoptimized segment, so if we get to this point and the
// previousSegment has not been optimized and set to null, start optimizing it before
// creating the next one. Note that this is a weird case and would only happen if we get
// Tweets with drastically different IDs than we expect, or there is a large amount of time
// where no Tweets are created in this partition.
LOG.error("Creating new segment for Tweet {} when the previous segment {} was not sealed. "
+ "Current segment: {}. Documents: {}. largestValidTweetIDForSegment: {}.",
tweetID,
previousSegment.getSegmentInfo().getTimeSliceID(),
currentSegment.getSegmentInfo().getTimeSliceID(),
currentSegment.getSegmentInfo().getIndexSegment().getNumDocs(),
largestValidTweetIDForCurrentSegment);
optimizePreviousSegment();
SEGMENTS_CLOSED_EARLY.increment();
}
previousSegment = currentSegment;
// We have two cases:
//
// Case 1:
// If the greatest Tweet ID we have seen is tweetID, then when we want to create a new segment
// with that ID, so the Tweet being processed goes into the new segment.
//
// Case 2:
// If the tweetID is bigger than the max tweetID, then this method is being called directly from
// tests, so we didn't update the maxTweetID, so we can create a new segment with the new
// Tweet ID.
//
// Case 3:
// If it's not the greatest Tweet ID we have seen, then we don't want to create a
// segment boundary that is lower than any Tweet IDs in the current segment, because then
// some tweets from the previous segment would be in the wrong segment, so create a segment
// that has a greater ID than any Tweets that we have seen.
//
// Example:
// - We<SUF>
// - We now see tweet 7 and we decide it's time to create a new segment.
// - The new segment will start at tweet 11. It can't start at tweet 7, because
// tweet 10 will be in the wrong segment.
// - Tweet 7 that we just saw will end up in the previous segment.
if (maxTweetID <= tweetID) {
currentSegmentTimesliceBoundary = tweetID;
NEW_SEGMENT_STATS.recordSettingTimesliceToCurrentTweet(tweetID);
} else {
currentSegmentTimesliceBoundary = maxTweetID + 1;
NEW_SEGMENT_STATS.recordSettingTimesliceToMaxTweetId(tweetID, maxTweetID);
}
currentSegment = segmentManager.createAndPutOptimizingSegmentWriter(
currentSegmentTimesliceBoundary);
currentSegment.getSegmentInfo().setIndexing(true);
largestValidTweetIDForCurrentSegment =
OutOfOrderRealtimeTweetIDMapper.calculateMaxTweetID(currentSegmentTimesliceBoundary);
NEW_SEGMENT_STATS.wrapNewSegmentCreation(tweetID, maxTweetID,
currentSegmentTimesliceBoundary, largestValidTweetIDForCurrentSegment);
segmentManager.removeExcessSegments();
}
void logState() {
LOG.info("TweetCreateHandler:");
LOG.info(String.format(" tweets sent for indexing: %,d",
indexingResultCounts.getIndexingCalls()));
LOG.info(String.format(" non-retriable failure: %,d",
indexingResultCounts.getFailureNotRetriable()));
LOG.info(String.format(" retriable failure: %,d",
indexingResultCounts.getFailureRetriable()));
LOG.info(String.format(" successfully indexed: %,d",
indexingResultCounts.getIndexingSuccess()));
LOG.info(String.format(" tweets in wrong segment: %,d", TWEETS_IN_WRONG_SEGMENT.getCount()));
LOG.info(String.format(" segments closed early: %,d", SEGMENTS_CLOSED_EARLY.getCount()));
}
}
|
156168_9 | package Ponomar;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.util.*;
import java.io.*;
/***************************************************************
Matins.java :: MODULE THAT TAKES THE GIVEN MATINS READINGS FOR THE DAY,
THAT IS, PENTECOSTARION, MENELOGION, AND FLOATERS AND RETURNS
THE APPROPRIATE SET OF READINGS FOR THE DAY AND THEIR ORDER.
Further work will convert this into the programme that will allow the creation of the text for Matins.
Matins.java is part of the Ponomar project.
Copyright 2012 Yuri Shardt
version 1.0: July 2012
yuri.shardt (at) gmail.com
PERMISSION IS HEREBY GRANTED TO USE, MODIFY, AND/OR REDISTRIBUTE THIS SOURCE CODE
PROVIDED THAT THIS NOTICE REMAINS IN ALL VERSION AND / OR DERIVATIVES THEREOF.
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 AUTHOR 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.
**************************************************************/
public class Matins implements DocHandler {
private final static String configFileName = "ponomar.config"; // CONFIGURATIONS FILE
//private final static String generalFileName="Ponomar/xml/";
private final static String triodionFileName = "xml/triodion/"; // TRIODION FILE
private final static String pentecostarionFileName = "xml/pentecostarion/"; // PENTECOSTARION FILE
private static OrderedHashtable readings; // CONTAINS TODAY'S SCRIPTURE READING
private static OrderedHashtable PentecostarionS; //CONTAINS THE PENTECOSTARION READINGS (SEQUENTIAL (rjadovoje) READINGS!)
private static OrderedHashtable MenalogionS; //CONTAINS THE MENALOGION READINGS, EXCLUDING ANY FLOATERS
private static OrderedHashtable FloaterS;
private static OrderedHashtable Information; //CONTAINS COMMANDS ABOUT HOW TO CARRY OUT THE ORDERING OF THE READINGS
private static String Glocation;
private static LanguagePack Phrases ;//= new LanguagePack();
private static String[] TransferredDays;// = Phrases.obtainValues((String) Phrases.Phrases.get("DayReading"));
private static String[] Error;// = Phrases.obtainValues((String) Phrases.Phrases.get("Errors"));
private static Helpers findLanguage;// = new Helpers();
private static Vector dailyV = new Vector();
private static Vector dailyR = new Vector();
private static Vector dailyT = new Vector();
private static Vector menaion2V = new Vector();
private static Vector menaion2R = new Vector();
private static Vector menaion2T = new Vector();
private static Vector menaionV = new Vector();
private static Vector menaionR = new Vector();
private static Vector menaionT = new Vector();
private static Vector suppressedV = new Vector();
private static Vector suppressedR = new Vector();
private static Vector suppressedT = new Vector();
private static OrderedHashtable tomorrowRead = new OrderedHashtable();
private static OrderedHashtable yesterdayRead = new OrderedHashtable();
private static StringOp Information3 = new StringOp();
public Matins(OrderedHashtable dayInfo) {
Information3.dayInfo=dayInfo;
Phrases = new LanguagePack(dayInfo);
TransferredDays = Phrases.obtainValues((String) Phrases.Phrases.get("DayReading"));
Error = Phrases.obtainValues((String) Phrases.Phrases.get("Errors"));
findLanguage=new Helpers(Information3.dayInfo);
}
//THESE ARE THE SAME FUNCTION AS IN MAIN, BUT TRIMMED FOR THE CURRENT NEEDS
public void startDocument() {
}
public void endDocument() {
}
public void startElement(String elem, Hashtable table) {
// THE TAG COULD CONTAIN A COMMAND Cmd
// THE COMMAND TELLS US WHETHER OR NOT TO PROCESS THIS TAG GIVEN
// TODAY'S INFORMATION IN dayInfo.
if (table.get("Cmd") != null) {
// EXECUTE THE COMMAND, AND STOP IF IT IS FALSE
if (Information3.evalbool(table.get("Cmd").toString()) == false) {
return;
}
}
if (elem.equals("COMMAND")) {
//THIS WILL STORE ALL THE POSSIBLE COMMANDS FOR A GIVEN SITUATION AND ALLOW THE RESULTS TO BE DETEMINED.
String name = (String) table.get("Name");
String value = (String) table.get("Value");
//IF THE GIVEN name OCCURS IN THE information HASHTABLE THAN AUGMENT ITS VALUES.
if (Information.containsKey(name)) {
Vector previous = (Vector) Information.get(name);
previous.add(value);
Information.put(name, previous);
} else {
Vector vect = new Vector();
vect.add(value);
Information.put(name, vect);
}
}
//ALL WE CARE ABOUT ARE THE SCRIPTURE READINGS
}
public void endElement(String elem) {
}
public void text(String text) {
}
public String Readings(OrderedHashtable readingsIn, JDate today) {
/********************************************************
SINCE I HAVE CORRECTED THE SCRIPTURE READINGS IN THE MAIN FILE, I CAN NOW PRECEDE WITH A BETTER VERSION OF THIS PROGRAMME!
********************************************************/
//PROCESS THE READINGS INTO THE DESIRED FORMS:
classifyReadings orderedReadings = new classifyReadings(readingsIn);
/* Information3.dayInfo.put("doy","12");
Information3.dayInfo.put("dow","1");
Information3.dayInfo.put("nday","2");
System.out.println("Testing the new StringOp formulation is " + Information3.evalbool("doy == 12"));*/
Information = new OrderedHashtable();
int doy = Integer.parseInt(Information3.dayInfo.get("doy").toString());
int dow = Integer.parseInt(Information3.dayInfo.get("dow").toString());
int nday = Integer.parseInt(Information3.dayInfo.get("nday").toString());
int dRank=Integer.parseInt(Information3.dayInfo.get("dRank").toString());
//DETERMINE THE GOVERNING PARAMETERS FOR COMPILING THE READINGS
/*try {
FileReader frf = new FileReader(findLanguage.langFileFind(StringOp.dayInfo.get("LS").toString(), "xml/Commands/Matins.xml"));
Matins a1 = new Matins();
QDParser.parse(a1, frf);
} catch (Exception e) {
e.printStackTrace();
}*/
//For the time being I will hard code the rules, as it is simple one. Suppress Sequential readings on Sunday if dRank > 6; otherwise suppress the menaion readings.
Vector dailyVf = new Vector();
Vector dailyRf = new Vector();
Vector dailyTf = new Vector();
for (int i=0;i<orderedReadings.dailyV.size();i++){
dailyVf.add(orderedReadings.dailyV.get(i));
dailyRf.add(orderedReadings.dailyR.get(i));
dailyTf.add(dow);
}
for (int i=0;i<orderedReadings.menaionV.size();i++){
dailyVf.add(orderedReadings.menaionV.get(i));
dailyRf.add(orderedReadings.menaionR.get(i));
dailyTf.add(orderedReadings.menaionT.get(i));
}
return format(dailyVf, dailyRf, dailyTf);
}
private OrderedHashtable getReadings(JDate today, String readingType) {
String filename = "";
int lineNumber = 0;
int nday = (int) JDate.difference(today, Paschalion.getPascha(today.getYear()));
//I COPIED THIS FROM THE Main.java FILE BY ALEKS WITH MY MODIFICATIONS (Y.S.)
//FROM HERE UNTIL
if (nday >= -70 && nday < 0) {
filename = triodionFileName;
lineNumber = Math.abs(nday);
} else if (nday < -70) {
// WE HAVE NOT YET REACHED THE LENTEN TRIODION
filename = pentecostarionFileName;
JDate lastPascha = Paschalion.getPascha(today.getYear() - 1);
lineNumber = (int) JDate.difference(today, lastPascha) + 1;
} else {
// WE ARE AFTER PASCHA AND BEFORE THE END OF THE YEAR
filename = pentecostarionFileName;
lineNumber = nday + 1;
}
filename += lineNumber >= 10 ? lineNumber + "" : "0" + lineNumber + ""; // CLEANED UP
// READ THE PENTECOSTARION / TRIODION INFORMATION
Day checkingP = new Day(filename,Information3.dayInfo);
//ADDED 2008/05/19 n.s. Y.S.
//COPYING SOME READINGS FILES
// GET THE MENAION DATA
int m = today.getMonth();
int d = today.getDay();
filename = "";
filename += m < 10 ? "xml/0" + m : "xml/" + m; // CLEANED UP
filename += d < 10 ? "/0" + d : "/" + d; // CLEANED UP
filename += "";
Day checkingM = new Day(filename,Information3.dayInfo);
Information3.dayInfo.put("dRank",Math.max(checkingP.getDayRank(), checkingM.getDayRank()));
OrderedHashtable[] PaschalReadings = checkingP.getReadings();
OrderedHashtable[] MenaionReadings = checkingM.getReadings();
OrderedHashtable CombinedReadings = new OrderedHashtable();
for (int k = 0; k < MenaionReadings.length; k++) {
OrderedHashtable Reading = (OrderedHashtable) MenaionReadings[k].get("Readings");
OrderedHashtable Readings = (OrderedHashtable) Reading.get("Readings");
for (Enumeration e = Readings.enumerateKeys(); e.hasMoreElements();) {
String element1 = e.nextElement().toString();
if (CombinedReadings.get(element1) != null) {
//Type of Reading already exists combine them
OrderedHashtable temp = (OrderedHashtable) CombinedReadings.get(element1);
Vector Readings2 = (Vector) temp.get("Readings");
Vector Rank = (Vector) temp.get("Rank");
Vector Tag = (Vector) temp.get("Tag");
Readings2.add(Readings.get(element1));
Rank.add(Reading.get("Rank"));
Tag.add(Reading.get("Name"));
temp.put("Readings", Readings2);
temp.put("Rank", Rank);
temp.put("Tag", Tag);
CombinedReadings.put(element1, temp);
} else {
//Reading does not exist
Vector Readings2 = new Vector();
Vector Rank = new Vector();
Vector Tag = new Vector();
Readings2.add(Readings.get(element1));
Rank.add(Reading.get("Rank"));
Tag.add(Reading.get("Name"));
OrderedHashtable temp = new OrderedHashtable();
temp.put("Readings", Readings2);
temp.put("Rank", Rank);
temp.put("Tag", Tag);
CombinedReadings.put(element1, temp);
}
}
}
for (int k = 0; k < PaschalReadings.length; k++) {
OrderedHashtable Reading = (OrderedHashtable) PaschalReadings[k].get("Readings");
OrderedHashtable Readings = (OrderedHashtable) Reading.get("Readings");
for (Enumeration e = Readings.enumerateKeys(); e.hasMoreElements();) {
String element1 = e.nextElement().toString();
if (CombinedReadings.get(element1) != null) {
//Type of Reading already exists combine them
OrderedHashtable temp = (OrderedHashtable) CombinedReadings.get(element1);
Vector Readings2 = (Vector) temp.get("Readings");
Vector Rank = (Vector) temp.get("Rank");
Vector Tag = (Vector) temp.get("Tag");
Readings2.add(Readings.get(element1));
Rank.add(Reading.get("Rank"));
Tag.add(Reading.get("Name"));
temp.put("Readings", Readings2);
temp.put("Rank", Rank);
temp.put("Tag", Tag);
CombinedReadings.put(element1, temp);
} else {
//Reading does not exist
Vector Readings2 = new Vector();
Vector Rank = new Vector();
Vector Tag = new Vector();
Readings2.add(Readings.get(element1));
Rank.add(Reading.get("Rank"));
Tag.add(Reading.get("Name"));
OrderedHashtable temp = new OrderedHashtable();
temp.put("Readings", Readings2);
temp.put("Rank", Rank);
temp.put("Tag", Tag);
CombinedReadings.put(element1, temp);
}
}
}
OrderedHashtable temp = (OrderedHashtable) CombinedReadings.get("LITURGY");
//System.out.println("temp values (423)" + temp);
Vector Readings = (Vector) temp.get("Readings");
Vector Rank = (Vector) temp.get("Rank");
Vector Tag = (Vector) temp.get("Tag");
//Special case and consider it differently
Vector type = new Vector();
for (int j = 0; j < Readings.size(); j++) {
OrderedHashtable liturgy = (OrderedHashtable) Readings.get(j);
OrderedHashtable stepE = (OrderedHashtable) liturgy.get(readingType);
if (stepE != null)
{
type.add(stepE.get("Reading").toString());
}
else
{
//type.add("");
}
}
//output += RSep;
OrderedHashtable Final2 = new OrderedHashtable();
Final2.put("Readings", type);
Final2.put("Rank", Rank);
Final2.put("Tag", Tag);
return Final2;
}
protected String Display(String a, String b, String c) {
//THIS FUNCTION TAKES THE POSSIBLE 3 READINGS AND COMBINES THEM AS APPROPRIATE, SO THAT NO SPACES OR OTHER UNDESIRED STUFF IS DISPLAYED!
String output = "";
if (a.length() > 0) {
output += a;
}
if (b.length() > 0) {
if (output.length() > 0) {
output += Information3.dayInfo.get("ReadSep") + " ";
}
output += b;
}
if (c.length() > 0) {
if (output.length() > 0) {
output += Information3.dayInfo.get("ReadSep") + " ";
}
output += c;
}
//TECHNICALLY, IF THERE ARE 3 OR MORE READINGS, THEN SOME SHOULD BE TAKEN "FROM THE BEGINNING" (nod zachalo).
return output;
}
public String format(Vector vectV, Vector vectR, Vector vectT) {
String output = "";
Bible ShortForm = new Bible(Information3.dayInfo);
try {
Enumeration e3 = vectV.elements();
for (int k = 0; k < vectV.size(); k++) {
String reading = (String) vectV.get(k);
output += ShortForm.getHyperlink(reading);
if ((Integer) vectR.get(k) == -2 ) {
if (vectV.size()>1){
int tag = (Integer) vectT.get(k);
output += " (" + Week(vectT.get(k).toString()) + ")";
}
} else {
output += vectT.get(k);
}
if (k < vectV.size() - 1) {
output += Information3.dayInfo.get("ReadSep"); //IF THERE ARE MORE READINGS OF THE SAME TYPE APPEND A SEMICOLON!
}
}
} catch (Exception a) {
System.out.println(a.toString());
StackTraceElement[] trial=a.getStackTrace();
System.out.println(trial[0].toString());
}
return output;
}
private String Week(String dow) {
//CONVERTS THE DOW STRING INTO A NAME. THIS SHOULD BE IN THE ACCUSATIVE CASE
try {
return TransferredDays[Integer.parseInt(dow)];
} catch (Exception a) {
return dow; //A DAY OF THE WEEK WAS NOT SENT
}
}
public static void main(String[] argz) {
}
class classifyReadings implements DocHandler {
private final String configFileName = "ponomar.config"; // CONFIGURATIONS FILE
//private final static String generalFileName="Ponomar/xml/";
private final String triodionFileName = "xml/triodion/"; // TRIODION FILE
private final String pentecostarionFileName = "xml/pentecostarion/"; // PENTECOSTARION FILE
private OrderedHashtable Information2; //CONTAINS COMMANDS ABOUT HOW TO CARRY OUT THE ORDERING OF THE READINGS
public Vector dailyV = new Vector();
public Vector dailyR = new Vector();
public Vector dailyT = new Vector();
public Vector menaionV = new Vector();
public Vector menaionR = new Vector();
public Vector menaionT = new Vector();
public Vector suppressedV = new Vector();
public Vector suppressedR = new Vector();
public Vector suppressedT = new Vector();
private StringOp ParameterValues=new StringOp();
public classifyReadings() {
}
public classifyReadings(OrderedHashtable readingsInA) {
StringOp Testing = new StringOp();
ParameterValues.dayInfo=Information3.dayInfo;
classify(readingsInA);
}
public classifyReadings(OrderedHashtable readingsInA, StringOp ParameterValues) {
classify(readingsInA);
}
private void classify(OrderedHashtable readingsIn)
{
//Initialise Information.
Information2=new OrderedHashtable();
/*try {
FileReader frf = new FileReader(findLanguage.langFileFind(ParameterValues.dayInfo.get("LS").toString(), "xml/Commands/Matins.xml"));
//System.out.println(findLanguage.langFileFind(ParameterValues.dayInfo.get("LS").toString(), "xml/Commands/DivineLiturgy.xml"));
//DivineLiturgy a1 = new classifyReadin();
QDParser.parse(this, frf);
} catch (Exception e) {
e.printStackTrace();
}*/
Vector paschalV = (Vector) readingsIn.get("Readings");
Vector paschalR = (Vector) readingsIn.get("Rank");
Vector paschalT = (Vector) readingsIn.get("Tag");
dailyV = new Vector();
dailyR = new Vector();
dailyT = new Vector();
if (paschalV == null){
return;
}
for (int k = 0; k < paschalV.size(); k++) {
if ((Integer) paschalR.get(k) == -2) {
//THIS IS A DAILY READING THAT CAN BE SKIPPED, EXCEPT MAYBE ON SUNDAYS.
dailyV.add(paschalV.get(k));
dailyR.add(paschalR.get(k));
dailyT.add(paschalT.get(k));
} else {
menaionV.add(paschalV.get(k));
menaionR.add(paschalR.get(k));
menaionT.add(paschalT.get(k));
}
}
Suppress();
//LeapReadings();
}
public void startDocument() {
}
public void endDocument() {
}
public void startElement(String elem, Hashtable table) {
// THE TAG COULD CONTAIN A COMMAND Cmd
// THE COMMAND TELLS US WHETHER OR NOT TO PROCESS THIS TAG GIVEN
// TODAY'S INFORMATION IN dayInfo.
if (table.get("Cmd") != null) {
// EXECUTE THE COMMAND, AND STOP IF IT IS FALSE
if (ParameterValues.evalbool(table.get("Cmd").toString()) == false) {
return;
}
}
if (elem.equals("COMMAND")) {
//THIS WILL STORE ALL THE POSSIBLE COMMANDS FOR A GIVEN SITUATION AND ALLOW THE RESULTS TO BE DETEMINED.
String name = (String) table.get("Name");
String value = (String) table.get("Value");
//IF THE GIVEN name OCCURS IN THE information HASHTABLE THAN AUGMENT ITS VALUES.
//System.out.println("==============================\nTesting Information\n++++++++++++++++++++");
if (Information2.containsKey(name)) {
Vector previous = (Vector) Information2.get(name);
previous.add(value);
Information2.put(name, previous);
} else {
Vector vect = new Vector();
vect.add(value);
Information2.put(name, vect);
}
}
//ALL WE CARE ABOUT ARE THE SCRIPTURE READINGS
}
public void endElement(String elem) {
}
public void text(String text) {
}
private void Suppress() {
//THIS FUNCTION CONSIDERS WHAT HOLIDAYS ARE CURRENTLY OCCURING AND RETURNS THE READINGS FOR THE DAY, WHERE SUPPRESSED CONTAINS THE READINGS THAT WERE SUPPRESSED.
int doy = Integer.parseInt(ParameterValues.dayInfo.get("doy").toString());
int dow = Integer.parseInt(ParameterValues.dayInfo.get("dow").toString());
int nday = Integer.parseInt(ParameterValues.dayInfo.get("nday").toString());
int ndayF = Integer.parseInt(ParameterValues.dayInfo.get("ndayF").toString());
int ndayP = Integer.parseInt(ParameterValues.dayInfo.get("ndayP").toString());
int dRank = Integer.parseInt(ParameterValues.dayInfo.get("dRank").toString());
//LeapReadings(); //THIS ALLOWS APPROPRIATE SKIPPING OF READINGS OVER THE NATIVITY SEASON!
if (dow == 0 && dRank > 6 && (nday < -49 || nday > 0)) {
for (int k = 0; k < dailyV.size(); k++) {
suppressedV.add(dailyV.get(k));
suppressedR.add(dailyR.get(k));
suppressedT.add(dailyT.get(k));
}
dailyV.clear();
dailyR.clear();
dailyT.clear();
return; //There is no need for any other readings to be considered!
}
if (dow == 0 && dRank <= 6){
for (int k = 0; k < menaionV.size(); k++) {
suppressedV.add(menaionV.get(k));
suppressedR.add(menaionV.get(k));
suppressedT.add(menaionV.get(k));
}
menaionV.clear();
menaionV.clear();
menaionV.clear();
return;
}
return;
}
protected void LeapReadings() {
//SKIPS THE READINGS IF THERE ARE ANY BREAKS!
int doy = Integer.parseInt(ParameterValues.dayInfo.get("doy").toString());
int dow = Integer.parseInt(ParameterValues.dayInfo.get("dow").toString());
int nday = Integer.parseInt(ParameterValues.dayInfo.get("nday").toString());
int ndayF = Integer.parseInt(ParameterValues.dayInfo.get("ndayF").toString());
int ndayP = Integer.parseInt(ParameterValues.dayInfo.get("ndayP").toString());
//IN ALL CASES ONLY THE PENTECOSTARION READINGS ARE EFFECTED!
Vector empty = new Vector();
//USING THE NEWER VERSION OF STORED VALUES
//EACH OF THE STORED COMMANDS ARE EVALUATED IF ANY ARE TRUE THEN THE READINGS ARE SKIPPED IF THERE ARE ANY FURTHER READINGS ON THAT DAY.
int available = menaionV.size();
if (available > 0) {
Vector vect = (Vector) Information2.get("Suppress");
if (vect != null) {
for (Enumeration e2 = vect.elements(); e2.hasMoreElements();) {
String Command = (String) e2.nextElement();
if (ParameterValues.evalbool(Command)) {
//THE CURRENT COMMAND WAS TRUE AND THE SEQUENTITIAL READING IS TO BE SKIPPED
dailyV.clear();
dailyR.clear();
dailyT.clear();
suppressedV.clear();
suppressedR.clear();
suppressedT.clear();
return;
}
}
}
}
return;
}
}
}
| typiconman/ponomar | Ponomar/Matins.java | 7,474 | // = new Helpers();
| line_comment | nl | package Ponomar;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.util.*;
import java.io.*;
/***************************************************************
Matins.java :: MODULE THAT TAKES THE GIVEN MATINS READINGS FOR THE DAY,
THAT IS, PENTECOSTARION, MENELOGION, AND FLOATERS AND RETURNS
THE APPROPRIATE SET OF READINGS FOR THE DAY AND THEIR ORDER.
Further work will convert this into the programme that will allow the creation of the text for Matins.
Matins.java is part of the Ponomar project.
Copyright 2012 Yuri Shardt
version 1.0: July 2012
yuri.shardt (at) gmail.com
PERMISSION IS HEREBY GRANTED TO USE, MODIFY, AND/OR REDISTRIBUTE THIS SOURCE CODE
PROVIDED THAT THIS NOTICE REMAINS IN ALL VERSION AND / OR DERIVATIVES THEREOF.
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 AUTHOR 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.
**************************************************************/
public class Matins implements DocHandler {
private final static String configFileName = "ponomar.config"; // CONFIGURATIONS FILE
//private final static String generalFileName="Ponomar/xml/";
private final static String triodionFileName = "xml/triodion/"; // TRIODION FILE
private final static String pentecostarionFileName = "xml/pentecostarion/"; // PENTECOSTARION FILE
private static OrderedHashtable readings; // CONTAINS TODAY'S SCRIPTURE READING
private static OrderedHashtable PentecostarionS; //CONTAINS THE PENTECOSTARION READINGS (SEQUENTIAL (rjadovoje) READINGS!)
private static OrderedHashtable MenalogionS; //CONTAINS THE MENALOGION READINGS, EXCLUDING ANY FLOATERS
private static OrderedHashtable FloaterS;
private static OrderedHashtable Information; //CONTAINS COMMANDS ABOUT HOW TO CARRY OUT THE ORDERING OF THE READINGS
private static String Glocation;
private static LanguagePack Phrases ;//= new LanguagePack();
private static String[] TransferredDays;// = Phrases.obtainValues((String) Phrases.Phrases.get("DayReading"));
private static String[] Error;// = Phrases.obtainValues((String) Phrases.Phrases.get("Errors"));
private static Helpers findLanguage;// = new<SUF>
private static Vector dailyV = new Vector();
private static Vector dailyR = new Vector();
private static Vector dailyT = new Vector();
private static Vector menaion2V = new Vector();
private static Vector menaion2R = new Vector();
private static Vector menaion2T = new Vector();
private static Vector menaionV = new Vector();
private static Vector menaionR = new Vector();
private static Vector menaionT = new Vector();
private static Vector suppressedV = new Vector();
private static Vector suppressedR = new Vector();
private static Vector suppressedT = new Vector();
private static OrderedHashtable tomorrowRead = new OrderedHashtable();
private static OrderedHashtable yesterdayRead = new OrderedHashtable();
private static StringOp Information3 = new StringOp();
public Matins(OrderedHashtable dayInfo) {
Information3.dayInfo=dayInfo;
Phrases = new LanguagePack(dayInfo);
TransferredDays = Phrases.obtainValues((String) Phrases.Phrases.get("DayReading"));
Error = Phrases.obtainValues((String) Phrases.Phrases.get("Errors"));
findLanguage=new Helpers(Information3.dayInfo);
}
//THESE ARE THE SAME FUNCTION AS IN MAIN, BUT TRIMMED FOR THE CURRENT NEEDS
public void startDocument() {
}
public void endDocument() {
}
public void startElement(String elem, Hashtable table) {
// THE TAG COULD CONTAIN A COMMAND Cmd
// THE COMMAND TELLS US WHETHER OR NOT TO PROCESS THIS TAG GIVEN
// TODAY'S INFORMATION IN dayInfo.
if (table.get("Cmd") != null) {
// EXECUTE THE COMMAND, AND STOP IF IT IS FALSE
if (Information3.evalbool(table.get("Cmd").toString()) == false) {
return;
}
}
if (elem.equals("COMMAND")) {
//THIS WILL STORE ALL THE POSSIBLE COMMANDS FOR A GIVEN SITUATION AND ALLOW THE RESULTS TO BE DETEMINED.
String name = (String) table.get("Name");
String value = (String) table.get("Value");
//IF THE GIVEN name OCCURS IN THE information HASHTABLE THAN AUGMENT ITS VALUES.
if (Information.containsKey(name)) {
Vector previous = (Vector) Information.get(name);
previous.add(value);
Information.put(name, previous);
} else {
Vector vect = new Vector();
vect.add(value);
Information.put(name, vect);
}
}
//ALL WE CARE ABOUT ARE THE SCRIPTURE READINGS
}
public void endElement(String elem) {
}
public void text(String text) {
}
public String Readings(OrderedHashtable readingsIn, JDate today) {
/********************************************************
SINCE I HAVE CORRECTED THE SCRIPTURE READINGS IN THE MAIN FILE, I CAN NOW PRECEDE WITH A BETTER VERSION OF THIS PROGRAMME!
********************************************************/
//PROCESS THE READINGS INTO THE DESIRED FORMS:
classifyReadings orderedReadings = new classifyReadings(readingsIn);
/* Information3.dayInfo.put("doy","12");
Information3.dayInfo.put("dow","1");
Information3.dayInfo.put("nday","2");
System.out.println("Testing the new StringOp formulation is " + Information3.evalbool("doy == 12"));*/
Information = new OrderedHashtable();
int doy = Integer.parseInt(Information3.dayInfo.get("doy").toString());
int dow = Integer.parseInt(Information3.dayInfo.get("dow").toString());
int nday = Integer.parseInt(Information3.dayInfo.get("nday").toString());
int dRank=Integer.parseInt(Information3.dayInfo.get("dRank").toString());
//DETERMINE THE GOVERNING PARAMETERS FOR COMPILING THE READINGS
/*try {
FileReader frf = new FileReader(findLanguage.langFileFind(StringOp.dayInfo.get("LS").toString(), "xml/Commands/Matins.xml"));
Matins a1 = new Matins();
QDParser.parse(a1, frf);
} catch (Exception e) {
e.printStackTrace();
}*/
//For the time being I will hard code the rules, as it is simple one. Suppress Sequential readings on Sunday if dRank > 6; otherwise suppress the menaion readings.
Vector dailyVf = new Vector();
Vector dailyRf = new Vector();
Vector dailyTf = new Vector();
for (int i=0;i<orderedReadings.dailyV.size();i++){
dailyVf.add(orderedReadings.dailyV.get(i));
dailyRf.add(orderedReadings.dailyR.get(i));
dailyTf.add(dow);
}
for (int i=0;i<orderedReadings.menaionV.size();i++){
dailyVf.add(orderedReadings.menaionV.get(i));
dailyRf.add(orderedReadings.menaionR.get(i));
dailyTf.add(orderedReadings.menaionT.get(i));
}
return format(dailyVf, dailyRf, dailyTf);
}
private OrderedHashtable getReadings(JDate today, String readingType) {
String filename = "";
int lineNumber = 0;
int nday = (int) JDate.difference(today, Paschalion.getPascha(today.getYear()));
//I COPIED THIS FROM THE Main.java FILE BY ALEKS WITH MY MODIFICATIONS (Y.S.)
//FROM HERE UNTIL
if (nday >= -70 && nday < 0) {
filename = triodionFileName;
lineNumber = Math.abs(nday);
} else if (nday < -70) {
// WE HAVE NOT YET REACHED THE LENTEN TRIODION
filename = pentecostarionFileName;
JDate lastPascha = Paschalion.getPascha(today.getYear() - 1);
lineNumber = (int) JDate.difference(today, lastPascha) + 1;
} else {
// WE ARE AFTER PASCHA AND BEFORE THE END OF THE YEAR
filename = pentecostarionFileName;
lineNumber = nday + 1;
}
filename += lineNumber >= 10 ? lineNumber + "" : "0" + lineNumber + ""; // CLEANED UP
// READ THE PENTECOSTARION / TRIODION INFORMATION
Day checkingP = new Day(filename,Information3.dayInfo);
//ADDED 2008/05/19 n.s. Y.S.
//COPYING SOME READINGS FILES
// GET THE MENAION DATA
int m = today.getMonth();
int d = today.getDay();
filename = "";
filename += m < 10 ? "xml/0" + m : "xml/" + m; // CLEANED UP
filename += d < 10 ? "/0" + d : "/" + d; // CLEANED UP
filename += "";
Day checkingM = new Day(filename,Information3.dayInfo);
Information3.dayInfo.put("dRank",Math.max(checkingP.getDayRank(), checkingM.getDayRank()));
OrderedHashtable[] PaschalReadings = checkingP.getReadings();
OrderedHashtable[] MenaionReadings = checkingM.getReadings();
OrderedHashtable CombinedReadings = new OrderedHashtable();
for (int k = 0; k < MenaionReadings.length; k++) {
OrderedHashtable Reading = (OrderedHashtable) MenaionReadings[k].get("Readings");
OrderedHashtable Readings = (OrderedHashtable) Reading.get("Readings");
for (Enumeration e = Readings.enumerateKeys(); e.hasMoreElements();) {
String element1 = e.nextElement().toString();
if (CombinedReadings.get(element1) != null) {
//Type of Reading already exists combine them
OrderedHashtable temp = (OrderedHashtable) CombinedReadings.get(element1);
Vector Readings2 = (Vector) temp.get("Readings");
Vector Rank = (Vector) temp.get("Rank");
Vector Tag = (Vector) temp.get("Tag");
Readings2.add(Readings.get(element1));
Rank.add(Reading.get("Rank"));
Tag.add(Reading.get("Name"));
temp.put("Readings", Readings2);
temp.put("Rank", Rank);
temp.put("Tag", Tag);
CombinedReadings.put(element1, temp);
} else {
//Reading does not exist
Vector Readings2 = new Vector();
Vector Rank = new Vector();
Vector Tag = new Vector();
Readings2.add(Readings.get(element1));
Rank.add(Reading.get("Rank"));
Tag.add(Reading.get("Name"));
OrderedHashtable temp = new OrderedHashtable();
temp.put("Readings", Readings2);
temp.put("Rank", Rank);
temp.put("Tag", Tag);
CombinedReadings.put(element1, temp);
}
}
}
for (int k = 0; k < PaschalReadings.length; k++) {
OrderedHashtable Reading = (OrderedHashtable) PaschalReadings[k].get("Readings");
OrderedHashtable Readings = (OrderedHashtable) Reading.get("Readings");
for (Enumeration e = Readings.enumerateKeys(); e.hasMoreElements();) {
String element1 = e.nextElement().toString();
if (CombinedReadings.get(element1) != null) {
//Type of Reading already exists combine them
OrderedHashtable temp = (OrderedHashtable) CombinedReadings.get(element1);
Vector Readings2 = (Vector) temp.get("Readings");
Vector Rank = (Vector) temp.get("Rank");
Vector Tag = (Vector) temp.get("Tag");
Readings2.add(Readings.get(element1));
Rank.add(Reading.get("Rank"));
Tag.add(Reading.get("Name"));
temp.put("Readings", Readings2);
temp.put("Rank", Rank);
temp.put("Tag", Tag);
CombinedReadings.put(element1, temp);
} else {
//Reading does not exist
Vector Readings2 = new Vector();
Vector Rank = new Vector();
Vector Tag = new Vector();
Readings2.add(Readings.get(element1));
Rank.add(Reading.get("Rank"));
Tag.add(Reading.get("Name"));
OrderedHashtable temp = new OrderedHashtable();
temp.put("Readings", Readings2);
temp.put("Rank", Rank);
temp.put("Tag", Tag);
CombinedReadings.put(element1, temp);
}
}
}
OrderedHashtable temp = (OrderedHashtable) CombinedReadings.get("LITURGY");
//System.out.println("temp values (423)" + temp);
Vector Readings = (Vector) temp.get("Readings");
Vector Rank = (Vector) temp.get("Rank");
Vector Tag = (Vector) temp.get("Tag");
//Special case and consider it differently
Vector type = new Vector();
for (int j = 0; j < Readings.size(); j++) {
OrderedHashtable liturgy = (OrderedHashtable) Readings.get(j);
OrderedHashtable stepE = (OrderedHashtable) liturgy.get(readingType);
if (stepE != null)
{
type.add(stepE.get("Reading").toString());
}
else
{
//type.add("");
}
}
//output += RSep;
OrderedHashtable Final2 = new OrderedHashtable();
Final2.put("Readings", type);
Final2.put("Rank", Rank);
Final2.put("Tag", Tag);
return Final2;
}
protected String Display(String a, String b, String c) {
//THIS FUNCTION TAKES THE POSSIBLE 3 READINGS AND COMBINES THEM AS APPROPRIATE, SO THAT NO SPACES OR OTHER UNDESIRED STUFF IS DISPLAYED!
String output = "";
if (a.length() > 0) {
output += a;
}
if (b.length() > 0) {
if (output.length() > 0) {
output += Information3.dayInfo.get("ReadSep") + " ";
}
output += b;
}
if (c.length() > 0) {
if (output.length() > 0) {
output += Information3.dayInfo.get("ReadSep") + " ";
}
output += c;
}
//TECHNICALLY, IF THERE ARE 3 OR MORE READINGS, THEN SOME SHOULD BE TAKEN "FROM THE BEGINNING" (nod zachalo).
return output;
}
public String format(Vector vectV, Vector vectR, Vector vectT) {
String output = "";
Bible ShortForm = new Bible(Information3.dayInfo);
try {
Enumeration e3 = vectV.elements();
for (int k = 0; k < vectV.size(); k++) {
String reading = (String) vectV.get(k);
output += ShortForm.getHyperlink(reading);
if ((Integer) vectR.get(k) == -2 ) {
if (vectV.size()>1){
int tag = (Integer) vectT.get(k);
output += " (" + Week(vectT.get(k).toString()) + ")";
}
} else {
output += vectT.get(k);
}
if (k < vectV.size() - 1) {
output += Information3.dayInfo.get("ReadSep"); //IF THERE ARE MORE READINGS OF THE SAME TYPE APPEND A SEMICOLON!
}
}
} catch (Exception a) {
System.out.println(a.toString());
StackTraceElement[] trial=a.getStackTrace();
System.out.println(trial[0].toString());
}
return output;
}
private String Week(String dow) {
//CONVERTS THE DOW STRING INTO A NAME. THIS SHOULD BE IN THE ACCUSATIVE CASE
try {
return TransferredDays[Integer.parseInt(dow)];
} catch (Exception a) {
return dow; //A DAY OF THE WEEK WAS NOT SENT
}
}
public static void main(String[] argz) {
}
class classifyReadings implements DocHandler {
private final String configFileName = "ponomar.config"; // CONFIGURATIONS FILE
//private final static String generalFileName="Ponomar/xml/";
private final String triodionFileName = "xml/triodion/"; // TRIODION FILE
private final String pentecostarionFileName = "xml/pentecostarion/"; // PENTECOSTARION FILE
private OrderedHashtable Information2; //CONTAINS COMMANDS ABOUT HOW TO CARRY OUT THE ORDERING OF THE READINGS
public Vector dailyV = new Vector();
public Vector dailyR = new Vector();
public Vector dailyT = new Vector();
public Vector menaionV = new Vector();
public Vector menaionR = new Vector();
public Vector menaionT = new Vector();
public Vector suppressedV = new Vector();
public Vector suppressedR = new Vector();
public Vector suppressedT = new Vector();
private StringOp ParameterValues=new StringOp();
public classifyReadings() {
}
public classifyReadings(OrderedHashtable readingsInA) {
StringOp Testing = new StringOp();
ParameterValues.dayInfo=Information3.dayInfo;
classify(readingsInA);
}
public classifyReadings(OrderedHashtable readingsInA, StringOp ParameterValues) {
classify(readingsInA);
}
private void classify(OrderedHashtable readingsIn)
{
//Initialise Information.
Information2=new OrderedHashtable();
/*try {
FileReader frf = new FileReader(findLanguage.langFileFind(ParameterValues.dayInfo.get("LS").toString(), "xml/Commands/Matins.xml"));
//System.out.println(findLanguage.langFileFind(ParameterValues.dayInfo.get("LS").toString(), "xml/Commands/DivineLiturgy.xml"));
//DivineLiturgy a1 = new classifyReadin();
QDParser.parse(this, frf);
} catch (Exception e) {
e.printStackTrace();
}*/
Vector paschalV = (Vector) readingsIn.get("Readings");
Vector paschalR = (Vector) readingsIn.get("Rank");
Vector paschalT = (Vector) readingsIn.get("Tag");
dailyV = new Vector();
dailyR = new Vector();
dailyT = new Vector();
if (paschalV == null){
return;
}
for (int k = 0; k < paschalV.size(); k++) {
if ((Integer) paschalR.get(k) == -2) {
//THIS IS A DAILY READING THAT CAN BE SKIPPED, EXCEPT MAYBE ON SUNDAYS.
dailyV.add(paschalV.get(k));
dailyR.add(paschalR.get(k));
dailyT.add(paschalT.get(k));
} else {
menaionV.add(paschalV.get(k));
menaionR.add(paschalR.get(k));
menaionT.add(paschalT.get(k));
}
}
Suppress();
//LeapReadings();
}
public void startDocument() {
}
public void endDocument() {
}
public void startElement(String elem, Hashtable table) {
// THE TAG COULD CONTAIN A COMMAND Cmd
// THE COMMAND TELLS US WHETHER OR NOT TO PROCESS THIS TAG GIVEN
// TODAY'S INFORMATION IN dayInfo.
if (table.get("Cmd") != null) {
// EXECUTE THE COMMAND, AND STOP IF IT IS FALSE
if (ParameterValues.evalbool(table.get("Cmd").toString()) == false) {
return;
}
}
if (elem.equals("COMMAND")) {
//THIS WILL STORE ALL THE POSSIBLE COMMANDS FOR A GIVEN SITUATION AND ALLOW THE RESULTS TO BE DETEMINED.
String name = (String) table.get("Name");
String value = (String) table.get("Value");
//IF THE GIVEN name OCCURS IN THE information HASHTABLE THAN AUGMENT ITS VALUES.
//System.out.println("==============================\nTesting Information\n++++++++++++++++++++");
if (Information2.containsKey(name)) {
Vector previous = (Vector) Information2.get(name);
previous.add(value);
Information2.put(name, previous);
} else {
Vector vect = new Vector();
vect.add(value);
Information2.put(name, vect);
}
}
//ALL WE CARE ABOUT ARE THE SCRIPTURE READINGS
}
public void endElement(String elem) {
}
public void text(String text) {
}
private void Suppress() {
//THIS FUNCTION CONSIDERS WHAT HOLIDAYS ARE CURRENTLY OCCURING AND RETURNS THE READINGS FOR THE DAY, WHERE SUPPRESSED CONTAINS THE READINGS THAT WERE SUPPRESSED.
int doy = Integer.parseInt(ParameterValues.dayInfo.get("doy").toString());
int dow = Integer.parseInt(ParameterValues.dayInfo.get("dow").toString());
int nday = Integer.parseInt(ParameterValues.dayInfo.get("nday").toString());
int ndayF = Integer.parseInt(ParameterValues.dayInfo.get("ndayF").toString());
int ndayP = Integer.parseInt(ParameterValues.dayInfo.get("ndayP").toString());
int dRank = Integer.parseInt(ParameterValues.dayInfo.get("dRank").toString());
//LeapReadings(); //THIS ALLOWS APPROPRIATE SKIPPING OF READINGS OVER THE NATIVITY SEASON!
if (dow == 0 && dRank > 6 && (nday < -49 || nday > 0)) {
for (int k = 0; k < dailyV.size(); k++) {
suppressedV.add(dailyV.get(k));
suppressedR.add(dailyR.get(k));
suppressedT.add(dailyT.get(k));
}
dailyV.clear();
dailyR.clear();
dailyT.clear();
return; //There is no need for any other readings to be considered!
}
if (dow == 0 && dRank <= 6){
for (int k = 0; k < menaionV.size(); k++) {
suppressedV.add(menaionV.get(k));
suppressedR.add(menaionV.get(k));
suppressedT.add(menaionV.get(k));
}
menaionV.clear();
menaionV.clear();
menaionV.clear();
return;
}
return;
}
protected void LeapReadings() {
//SKIPS THE READINGS IF THERE ARE ANY BREAKS!
int doy = Integer.parseInt(ParameterValues.dayInfo.get("doy").toString());
int dow = Integer.parseInt(ParameterValues.dayInfo.get("dow").toString());
int nday = Integer.parseInt(ParameterValues.dayInfo.get("nday").toString());
int ndayF = Integer.parseInt(ParameterValues.dayInfo.get("ndayF").toString());
int ndayP = Integer.parseInt(ParameterValues.dayInfo.get("ndayP").toString());
//IN ALL CASES ONLY THE PENTECOSTARION READINGS ARE EFFECTED!
Vector empty = new Vector();
//USING THE NEWER VERSION OF STORED VALUES
//EACH OF THE STORED COMMANDS ARE EVALUATED IF ANY ARE TRUE THEN THE READINGS ARE SKIPPED IF THERE ARE ANY FURTHER READINGS ON THAT DAY.
int available = menaionV.size();
if (available > 0) {
Vector vect = (Vector) Information2.get("Suppress");
if (vect != null) {
for (Enumeration e2 = vect.elements(); e2.hasMoreElements();) {
String Command = (String) e2.nextElement();
if (ParameterValues.evalbool(Command)) {
//THE CURRENT COMMAND WAS TRUE AND THE SEQUENTITIAL READING IS TO BE SKIPPED
dailyV.clear();
dailyR.clear();
dailyT.clear();
suppressedV.clear();
suppressedR.clear();
suppressedT.clear();
return;
}
}
}
}
return;
}
}
}
|
55482_54 | package org.zoodb.internal.util;
import java.nio.ByteBuffer;
import java.util.Arrays;
public class ClassDebugger {
private static final byte[] BA = {
-54, -2, -70, -66, // 0-3: magic number
0, 0, //4-5: minor version
0, 50, //6-7: major version
0, 16, //8-9: constant pools size+1
7, 0, 2, 1, 0, 11, 98, 99, 101, 47,
77, 121, 67, 108, 97, 115, 115, 7, 0, 4,
1, 0, 25, 98, 99, 101, 47, 80, 101, 114,
115, 105, 115, 116, 101, 110, 116, 67, 97, 112,
97, 98, 108, 101, 73, 109, 112, 108, 1, 0,
6, 60, 105, 110, 105, 116, 62, 1, 0, 3,
40, 41, 86, 1, 0, 4, 67, 111, 100, 101,
10, 0, 3, 0, 9, 12, 0, 5, 0, 6,
1, 0, 15, 76, 105, 110, 101, 78, 117, 109,
98, 101, 114, 84, 97, 98, 108, 101, 1, 0,
18, 76, 111, 99, 97, 108, 86, 97, 114, 105,
97, 98, 108, 101, 84, 97, 98, 108, 101, 1,
0, 4, 116, 104, 105, 115, 1, 0, 13, 76,
98, 99, 101, 47, 77, 121, 67, 108, 97, 115,
115, 59, 1, 0, 10, 83, 111, 117, 114, 99,
101, 70, 105, 108, 101, 1, 0, 12, 77, 121,
67, 108, 97, 115, 115, 46, 106, 97, 118, 97,
0, 33, 0, 1, 0, 3, 0, 0, 0, 0,
0, 1, 0, 1, 0, 5, 0, 6, 0, 1,
0, 7, 0, 0, 0, 47, 0, 1, 0, 1,
0, 0, 0, 5, 42, -73, 0, 8, -79, 0,
0, 0, 2, 0, 10, 0, 0, 0, 6, 0,
1, 0, 0, 0, 3, 0, 11, 0, 0, 0,
12, 0, 1, 0, 0, 0, 5, 0, 12, 0,
13, 0, 0, 0, 1, 0, 14, 0, 0, 0,
2, 0, 15
};
public enum CP {
CONSTANT_0,
CONSTANT_Utf8, // 1 Laenge des unterminierten Strings in Anzahl Byte (2 bytes)
//String in Utf8-Darstellung (variable Laenge)
CONSTANT_Unicode, // 2 Laenge nachfolgenden Zeichenkette in Anzahl Byte (2 bytes)
//Unicode-Zeichenkette (variable Laenge)
CONSTANT_Integer, // 3 Vorzeichenbehafteter Integer-Wert, big-endian (4 bytes)
CONSTANT_Float, // 4 Float-Wert nach IEEE 754 (4 bytes)
CONSTANT_Long, // 5 Vorzeichenbehafteter Integer-Wert, big-endian (8 bytes)
CONSTANT_Double, // 6 Double-Wert nach IEEE 754 (8 bytes)
CONSTANT_Class, // 7 Index zu einem weiteren Konstantpool-Eintrag vom Typ CONSTANT_Utf8, der
//den Klassennamen beinhaltet (2 bytes)
CONSTANT_String, // 8 Index zu einem weiteren Konstantpool-Eintrag vom Typ CONSTANT_Utf8, der
//den String beinhaltet (2 bytes)
CONSTANT_Fieldref, // 9 Index zu einem CONSTANT_Class Eintrag, der die Klasse bezeichnet, die das
//Feld enthaelt (2 bytes) plus ein Index zu einem CONSTANT_NameAndType Eintrag,
//der die Signatur des Feldes angibt (2 bytes)
CONSTANT_Methodref, // A Index zu einem CONSTANT_Class Eintrag, der die Klasse bezeichnet, welche die
//Methode enthaelt (2 bytes) plus ein Index zu einem CONSTANT_NameAndType
//Eintrag, der die Signatur der Methode angibt (2 bytes)
CONSTANT_InterfaceMethodref, // B Index zu einem CONSTANT_Class Eintrag, der das Interface bezeichnet, welches
//die jeweilige Methode deklariert (2 bytes) plus ein Index zu einem
//CONSTANT_NameAndType Eintrag, der die Signatur des Interfaces angibt (2
//bytes)
CONSTANT_NameAndType, // C Index zu einem CONSTANT_Utf8 Eintrag, der den Namen des Feldes oder der
//Methode enthaelt (2 bytes) plus ein weiteren Index zu einem CONSTANT_Utf8
//Eintrag, der die Signatur des Feldes oder der Methode angibt (2 bytes)
}
private static final int ACC_PUBLIC = 0x0001;// Kann ausserhalb des Package verwendet werden.
private static final int ACC_PRIVATE = 0x0002; // Kann nur von innerhalb der Klasse zugegriffen werden.
private static final int ACC_PROTECTED = 0x0004; // Kann von innerhalb der Klasse und von abgeleiteten Klassen
// zugegriffen werden.
private static final int ACC_STATIC = 0x0008; // Als static deklariert (Klassenvariable).
private static final int ACC_FINAL = 0x0010; // Kann nicht abgeleitet werden.
private static final int ACC_SUPER = 0x0020; // Behandelt Methodenaufrufe der Superklasse speziell. Dieses
// Flag dient zur Rueckwaertskompatibilitaet und wird von neueren
// Compilern immer gesetzt.
private static final int ACC_VOLATILE = 0x0040; // Kann nicht ge-cached werden.
private static final int ACC_TRANSIENT = 0x0080; // Feld als transient deklariert.
private static final int ACC_NATIVE = 0x0100; // In einer anderen Sprache (als Java) implementiert.
private static final int ACC_INTERFACE = 0x0200; // Dieses Flag ist gesetzt, wenn es sich um ein Interface und
// nicht um eine Klasse handelt.
private static final int ACC_ABSTRACT = 0x0400; // Kann nicht instanziert werden.
private static final int ACC_STRICT = 0x0800; // Als strictfp deklariert.
private static final FormattedStringBuilder sb = new FormattedStringBuilder();
public static boolean VERBOSE = true;
public static void main(String[] args) {
run(BA);
byte[] ba2 = ClassBuilderSimple.build("MySubClass", "MySuperClass");
run(ba2);
}
private static void run(byte[] ba) {
ByteBuffer bb = ByteBuffer.wrap(ba);
logHex("Magic:", bb.get(), bb.get(), bb.get(), bb.get());
log("Version:", bb.getShort(), bb.getShort());
int poolSize = bb.getShort();
log("Pool size:", poolSize);
for (int i = 1; i < poolSize; i++) {
int tag = bb.get();
CP cp = CP.values()[tag];
log("entry=" + i + ":", Integer.toString(tag), cp.name());
switch(cp) {
case CONSTANT_Utf8: {
int len = bb.getShort();
sb.fill(20);
for (int c = 0; c < len; c++) {
sb.append((char)bb.get());
}
sb.appendln();
break;
}
case CONSTANT_Class: {
int id = bb.getShort();
log(" ID=", id);
break;
}
case CONSTANT_Methodref: {
int idClass = bb.getShort();
int idType = bb.getShort();
log(" classID=", idClass + " typeNameID=" + idType);
break;
}
case CONSTANT_NameAndType: {
int idName = bb.getShort();
int idType = bb.getShort();
log(" nameID=", idName + " typeID=" + idType);
break;
}
default: throw new UnsupportedOperationException(cp.name());
}
}
sb.appendln("p=" + bb.position());
sb.appendln();
sb.appendln("Class descriptor");
sb.appendln("================");
int classMods = bb.getShort();
sb.append("Modifiers:").fill(20);
getModifiers(classMods, true);
sb.appendln();
sb.append("Name:").fill(20);
int thisID = bb.getShort();
sb.appendln("ID=" + thisID);
int superID = bb.getShort();
sb.append("Super-class").fill(20);
sb.appendln("ID=" + superID);
int nInter = bb.getShort();
sb.append("Interfaces").fill(20);
sb.appendln("n=" + nInter);
sb.appendln();
sb.appendln("Fields");
sb.appendln("================");
int nFields = bb.getShort();
sb.append("Fields").fill(20);
sb.appendln("n=" + nFields);
sb.appendln();
sb.appendln("Methods");
sb.appendln("================");
int nMethods = bb.getShort();
sb.append("Methods").fill(20);
sb.appendln("n=" + nMethods);
for (int c = 0; c < nMethods; c++) {
int mods = bb.getShort();
sb.append("Method").fill(20);
getModifiers(mods, false);
int nameID = bb.getShort();
sb.append("nameID=" + nameID);
int signID = bb.getShort();
sb.append(" signatureID=" + signID);
sb.appendln();
sb.fill(20);
int nAttr = bb.getShort();
sb.append("attributes=" + nAttr);
sb.appendln();
for (int a = 0; a < nAttr; a++) {
int attrID = bb.getShort();
int attrLen = bb.getInt();
byte[] mba = new byte[attrLen];
bb.get(mba);
sb.fill(20);
sb.append("ID=" + attrID);
sb.append(" len=" + attrLen);
sb.append(" code=" + Arrays.toString(mba));
sb.appendln();
}
}
sb.appendln();
sb.appendln("Class attributes");
sb.appendln("================");
int nClassAttr = bb.getShort();
sb.append("Attributes").fill(20);
sb.appendln("n=" + nClassAttr);
for (int a = 0; a < nClassAttr; a++) {
int attrID = bb.getShort();
int attrLen = bb.getInt();
byte[] mba = new byte[attrLen];
bb.get(mba);
sb.fill(20);
sb.append("ID=" + attrID);
sb.append(" len=" + attrLen);
sb.append(" code=" + Arrays.toString(mba));
sb.appendln();
}
// int classMods = bb.getShort();
// sb.append("Modifiers:").fill(20);
// if ((classMods & ACC_PUBLIC) != 0) sb.append("public ");
// if ((classMods & ACC_FINAL) != 0) sb.append("final ");
// if ((classMods & ACC_SUPER) != 0) sb.append("super ");
// if ((classMods & ACC_ABSTRACT) != 0) sb.append("abstract ");
// if ((classMods & ACC_INTERFACE) != 0) sb.append("interface ");
// else sb.append("class ");
// sb.appendln();
// sb.append("Name:").fill(20);
// int thisID = bb.getShort();
// sb.appendln("ID=" + thisID);
// int superID = bb.getShort();
// sb.append("Super-class").fill(20);
// sb.appendln("ID=" + superID);
// int nInter = bb.getShort();
// sb.append("Interfaces").fill(20);
// sb.appendln("n=" + nInter);
sb.appendln("p=" + bb.position() + "/" + ba.length);
if (VERBOSE) {
System.out.println(sb);
}
}
private static void getModifiers(int mods, boolean isClass) {
if ((mods & ACC_PUBLIC) != 0) sb.append("public ");
if ((mods & ACC_PRIVATE) != 0) sb.append("private ");
if ((mods & ACC_PROTECTED) != 0) sb.append("protected ");
if ((mods & ACC_STATIC) != 0) sb.append("static ");
if ((mods & ACC_FINAL) != 0) sb.append("final ");
if (isClass) {
if ((mods & ACC_SUPER) != 0) sb.append("super ");
} else {
if ((mods & ACC_SUPER) != 0) sb.append("synchronized ");
}
if ((mods & ACC_ABSTRACT) != 0) sb.append("abstract ");
if (isClass) {
if ((mods & ACC_INTERFACE) != 0) sb.append("interface ");
else sb.append("class ");
}
}
private static void logHex(String string, byte ... bytes) {
sb.append(string).fill(20);
for (byte b: bytes) {
sb.append(toHex(b));
sb.append(" ");
}
sb.appendln();
}
private static void log(String string, int ... values) {
sb.append(string).fill(20);
for (int v: values) {
sb.append(v);
sb.append(" ");
}
sb.appendln();
}
private static void log(String string, String ... values) {
sb.append(string).fill(20);
for (String v: values) {
sb.append(v);
sb.append(" ");
}
sb.appendln();
}
private static String toHex(byte b) {
String s = Integer.toHexString(b);
return s.substring(6);
}
}
| tzaeschke/zoodb | src/org/zoodb/internal/util/ClassDebugger.java | 4,250 | // int nInter = bb.getShort(); | line_comment | nl | package org.zoodb.internal.util;
import java.nio.ByteBuffer;
import java.util.Arrays;
public class ClassDebugger {
private static final byte[] BA = {
-54, -2, -70, -66, // 0-3: magic number
0, 0, //4-5: minor version
0, 50, //6-7: major version
0, 16, //8-9: constant pools size+1
7, 0, 2, 1, 0, 11, 98, 99, 101, 47,
77, 121, 67, 108, 97, 115, 115, 7, 0, 4,
1, 0, 25, 98, 99, 101, 47, 80, 101, 114,
115, 105, 115, 116, 101, 110, 116, 67, 97, 112,
97, 98, 108, 101, 73, 109, 112, 108, 1, 0,
6, 60, 105, 110, 105, 116, 62, 1, 0, 3,
40, 41, 86, 1, 0, 4, 67, 111, 100, 101,
10, 0, 3, 0, 9, 12, 0, 5, 0, 6,
1, 0, 15, 76, 105, 110, 101, 78, 117, 109,
98, 101, 114, 84, 97, 98, 108, 101, 1, 0,
18, 76, 111, 99, 97, 108, 86, 97, 114, 105,
97, 98, 108, 101, 84, 97, 98, 108, 101, 1,
0, 4, 116, 104, 105, 115, 1, 0, 13, 76,
98, 99, 101, 47, 77, 121, 67, 108, 97, 115,
115, 59, 1, 0, 10, 83, 111, 117, 114, 99,
101, 70, 105, 108, 101, 1, 0, 12, 77, 121,
67, 108, 97, 115, 115, 46, 106, 97, 118, 97,
0, 33, 0, 1, 0, 3, 0, 0, 0, 0,
0, 1, 0, 1, 0, 5, 0, 6, 0, 1,
0, 7, 0, 0, 0, 47, 0, 1, 0, 1,
0, 0, 0, 5, 42, -73, 0, 8, -79, 0,
0, 0, 2, 0, 10, 0, 0, 0, 6, 0,
1, 0, 0, 0, 3, 0, 11, 0, 0, 0,
12, 0, 1, 0, 0, 0, 5, 0, 12, 0,
13, 0, 0, 0, 1, 0, 14, 0, 0, 0,
2, 0, 15
};
public enum CP {
CONSTANT_0,
CONSTANT_Utf8, // 1 Laenge des unterminierten Strings in Anzahl Byte (2 bytes)
//String in Utf8-Darstellung (variable Laenge)
CONSTANT_Unicode, // 2 Laenge nachfolgenden Zeichenkette in Anzahl Byte (2 bytes)
//Unicode-Zeichenkette (variable Laenge)
CONSTANT_Integer, // 3 Vorzeichenbehafteter Integer-Wert, big-endian (4 bytes)
CONSTANT_Float, // 4 Float-Wert nach IEEE 754 (4 bytes)
CONSTANT_Long, // 5 Vorzeichenbehafteter Integer-Wert, big-endian (8 bytes)
CONSTANT_Double, // 6 Double-Wert nach IEEE 754 (8 bytes)
CONSTANT_Class, // 7 Index zu einem weiteren Konstantpool-Eintrag vom Typ CONSTANT_Utf8, der
//den Klassennamen beinhaltet (2 bytes)
CONSTANT_String, // 8 Index zu einem weiteren Konstantpool-Eintrag vom Typ CONSTANT_Utf8, der
//den String beinhaltet (2 bytes)
CONSTANT_Fieldref, // 9 Index zu einem CONSTANT_Class Eintrag, der die Klasse bezeichnet, die das
//Feld enthaelt (2 bytes) plus ein Index zu einem CONSTANT_NameAndType Eintrag,
//der die Signatur des Feldes angibt (2 bytes)
CONSTANT_Methodref, // A Index zu einem CONSTANT_Class Eintrag, der die Klasse bezeichnet, welche die
//Methode enthaelt (2 bytes) plus ein Index zu einem CONSTANT_NameAndType
//Eintrag, der die Signatur der Methode angibt (2 bytes)
CONSTANT_InterfaceMethodref, // B Index zu einem CONSTANT_Class Eintrag, der das Interface bezeichnet, welches
//die jeweilige Methode deklariert (2 bytes) plus ein Index zu einem
//CONSTANT_NameAndType Eintrag, der die Signatur des Interfaces angibt (2
//bytes)
CONSTANT_NameAndType, // C Index zu einem CONSTANT_Utf8 Eintrag, der den Namen des Feldes oder der
//Methode enthaelt (2 bytes) plus ein weiteren Index zu einem CONSTANT_Utf8
//Eintrag, der die Signatur des Feldes oder der Methode angibt (2 bytes)
}
private static final int ACC_PUBLIC = 0x0001;// Kann ausserhalb des Package verwendet werden.
private static final int ACC_PRIVATE = 0x0002; // Kann nur von innerhalb der Klasse zugegriffen werden.
private static final int ACC_PROTECTED = 0x0004; // Kann von innerhalb der Klasse und von abgeleiteten Klassen
// zugegriffen werden.
private static final int ACC_STATIC = 0x0008; // Als static deklariert (Klassenvariable).
private static final int ACC_FINAL = 0x0010; // Kann nicht abgeleitet werden.
private static final int ACC_SUPER = 0x0020; // Behandelt Methodenaufrufe der Superklasse speziell. Dieses
// Flag dient zur Rueckwaertskompatibilitaet und wird von neueren
// Compilern immer gesetzt.
private static final int ACC_VOLATILE = 0x0040; // Kann nicht ge-cached werden.
private static final int ACC_TRANSIENT = 0x0080; // Feld als transient deklariert.
private static final int ACC_NATIVE = 0x0100; // In einer anderen Sprache (als Java) implementiert.
private static final int ACC_INTERFACE = 0x0200; // Dieses Flag ist gesetzt, wenn es sich um ein Interface und
// nicht um eine Klasse handelt.
private static final int ACC_ABSTRACT = 0x0400; // Kann nicht instanziert werden.
private static final int ACC_STRICT = 0x0800; // Als strictfp deklariert.
private static final FormattedStringBuilder sb = new FormattedStringBuilder();
public static boolean VERBOSE = true;
public static void main(String[] args) {
run(BA);
byte[] ba2 = ClassBuilderSimple.build("MySubClass", "MySuperClass");
run(ba2);
}
private static void run(byte[] ba) {
ByteBuffer bb = ByteBuffer.wrap(ba);
logHex("Magic:", bb.get(), bb.get(), bb.get(), bb.get());
log("Version:", bb.getShort(), bb.getShort());
int poolSize = bb.getShort();
log("Pool size:", poolSize);
for (int i = 1; i < poolSize; i++) {
int tag = bb.get();
CP cp = CP.values()[tag];
log("entry=" + i + ":", Integer.toString(tag), cp.name());
switch(cp) {
case CONSTANT_Utf8: {
int len = bb.getShort();
sb.fill(20);
for (int c = 0; c < len; c++) {
sb.append((char)bb.get());
}
sb.appendln();
break;
}
case CONSTANT_Class: {
int id = bb.getShort();
log(" ID=", id);
break;
}
case CONSTANT_Methodref: {
int idClass = bb.getShort();
int idType = bb.getShort();
log(" classID=", idClass + " typeNameID=" + idType);
break;
}
case CONSTANT_NameAndType: {
int idName = bb.getShort();
int idType = bb.getShort();
log(" nameID=", idName + " typeID=" + idType);
break;
}
default: throw new UnsupportedOperationException(cp.name());
}
}
sb.appendln("p=" + bb.position());
sb.appendln();
sb.appendln("Class descriptor");
sb.appendln("================");
int classMods = bb.getShort();
sb.append("Modifiers:").fill(20);
getModifiers(classMods, true);
sb.appendln();
sb.append("Name:").fill(20);
int thisID = bb.getShort();
sb.appendln("ID=" + thisID);
int superID = bb.getShort();
sb.append("Super-class").fill(20);
sb.appendln("ID=" + superID);
int nInter = bb.getShort();
sb.append("Interfaces").fill(20);
sb.appendln("n=" + nInter);
sb.appendln();
sb.appendln("Fields");
sb.appendln("================");
int nFields = bb.getShort();
sb.append("Fields").fill(20);
sb.appendln("n=" + nFields);
sb.appendln();
sb.appendln("Methods");
sb.appendln("================");
int nMethods = bb.getShort();
sb.append("Methods").fill(20);
sb.appendln("n=" + nMethods);
for (int c = 0; c < nMethods; c++) {
int mods = bb.getShort();
sb.append("Method").fill(20);
getModifiers(mods, false);
int nameID = bb.getShort();
sb.append("nameID=" + nameID);
int signID = bb.getShort();
sb.append(" signatureID=" + signID);
sb.appendln();
sb.fill(20);
int nAttr = bb.getShort();
sb.append("attributes=" + nAttr);
sb.appendln();
for (int a = 0; a < nAttr; a++) {
int attrID = bb.getShort();
int attrLen = bb.getInt();
byte[] mba = new byte[attrLen];
bb.get(mba);
sb.fill(20);
sb.append("ID=" + attrID);
sb.append(" len=" + attrLen);
sb.append(" code=" + Arrays.toString(mba));
sb.appendln();
}
}
sb.appendln();
sb.appendln("Class attributes");
sb.appendln("================");
int nClassAttr = bb.getShort();
sb.append("Attributes").fill(20);
sb.appendln("n=" + nClassAttr);
for (int a = 0; a < nClassAttr; a++) {
int attrID = bb.getShort();
int attrLen = bb.getInt();
byte[] mba = new byte[attrLen];
bb.get(mba);
sb.fill(20);
sb.append("ID=" + attrID);
sb.append(" len=" + attrLen);
sb.append(" code=" + Arrays.toString(mba));
sb.appendln();
}
// int classMods = bb.getShort();
// sb.append("Modifiers:").fill(20);
// if ((classMods & ACC_PUBLIC) != 0) sb.append("public ");
// if ((classMods & ACC_FINAL) != 0) sb.append("final ");
// if ((classMods & ACC_SUPER) != 0) sb.append("super ");
// if ((classMods & ACC_ABSTRACT) != 0) sb.append("abstract ");
// if ((classMods & ACC_INTERFACE) != 0) sb.append("interface ");
// else sb.append("class ");
// sb.appendln();
// sb.append("Name:").fill(20);
// int thisID = bb.getShort();
// sb.appendln("ID=" + thisID);
// int superID = bb.getShort();
// sb.append("Super-class").fill(20);
// sb.appendln("ID=" + superID);
// int nInter<SUF>
// sb.append("Interfaces").fill(20);
// sb.appendln("n=" + nInter);
sb.appendln("p=" + bb.position() + "/" + ba.length);
if (VERBOSE) {
System.out.println(sb);
}
}
private static void getModifiers(int mods, boolean isClass) {
if ((mods & ACC_PUBLIC) != 0) sb.append("public ");
if ((mods & ACC_PRIVATE) != 0) sb.append("private ");
if ((mods & ACC_PROTECTED) != 0) sb.append("protected ");
if ((mods & ACC_STATIC) != 0) sb.append("static ");
if ((mods & ACC_FINAL) != 0) sb.append("final ");
if (isClass) {
if ((mods & ACC_SUPER) != 0) sb.append("super ");
} else {
if ((mods & ACC_SUPER) != 0) sb.append("synchronized ");
}
if ((mods & ACC_ABSTRACT) != 0) sb.append("abstract ");
if (isClass) {
if ((mods & ACC_INTERFACE) != 0) sb.append("interface ");
else sb.append("class ");
}
}
private static void logHex(String string, byte ... bytes) {
sb.append(string).fill(20);
for (byte b: bytes) {
sb.append(toHex(b));
sb.append(" ");
}
sb.appendln();
}
private static void log(String string, int ... values) {
sb.append(string).fill(20);
for (int v: values) {
sb.append(v);
sb.append(" ");
}
sb.appendln();
}
private static void log(String string, String ... values) {
sb.append(string).fill(20);
for (String v: values) {
sb.append(v);
sb.append(" ");
}
sb.appendln();
}
private static String toHex(byte b) {
String s = Integer.toHexString(b);
return s.substring(6);
}
}
|
74627_34 | package com.uber.okbuck;
import com.facebook.infer.annotation.Initializer;
import com.google.common.collect.Sets;
import com.uber.okbuck.core.annotation.AnnotationProcessorCache;
import com.uber.okbuck.core.dependency.DependencyCache;
import com.uber.okbuck.core.dependency.DependencyFactory;
import com.uber.okbuck.core.dependency.exporter.DependencyExporter;
import com.uber.okbuck.core.dependency.exporter.JsonDependencyExporter;
import com.uber.okbuck.core.manager.BuckFileManager;
import com.uber.okbuck.core.manager.BuckManager;
import com.uber.okbuck.core.manager.D8Manager;
import com.uber.okbuck.core.manager.DependencyManager;
import com.uber.okbuck.core.manager.GroovyManager;
import com.uber.okbuck.core.manager.JetifierManager;
import com.uber.okbuck.core.manager.KotlinManager;
import com.uber.okbuck.core.manager.LintManager;
import com.uber.okbuck.core.manager.ManifestMergerManager;
import com.uber.okbuck.core.manager.RobolectricManager;
import com.uber.okbuck.core.manager.ScalaManager;
import com.uber.okbuck.core.manager.TransformManager;
import com.uber.okbuck.core.model.base.ProjectType;
import com.uber.okbuck.core.task.OkBuckCleanTask;
import com.uber.okbuck.core.task.OkBuckTask;
import com.uber.okbuck.core.util.FileUtil;
import com.uber.okbuck.core.util.MoreCollectors;
import com.uber.okbuck.core.util.ProjectCache;
import com.uber.okbuck.core.util.ProjectUtil;
import com.uber.okbuck.extension.KotlinExtension;
import com.uber.okbuck.extension.OkBuckExtension;
import com.uber.okbuck.extension.ScalaExtension;
import com.uber.okbuck.extension.WrapperExtension;
import com.uber.okbuck.generator.BuckFileGenerator;
import com.uber.okbuck.template.common.ExportFile;
import com.uber.okbuck.template.core.Rule;
import com.uber.okbuck.wrapper.BuckWrapperTask;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
// Dependency Tree
//
// rootOkBuckTask
// / \
// / v
// / okbuckClean
// / / | \
// / v v v
// / :p1:okbuck :p2:okbuck :p3:okbuck ...
// | / / /
// v v v v
// setupOkbuck
//
public class OkBuckGradlePlugin implements Plugin<Project> {
public static final String OKBUCK = "okbuck";
private static final String DOT_OKBUCK = "." + OKBUCK;
public static final String WORKSPACE_PATH = DOT_OKBUCK + "/workspace";
public static final String GROUP = OKBUCK;
public static final String BUCK_LINT = "buckLint";
private static final String OKBUCK_TARGETS_BZL = "okbuck_targets.bzl";
public static final String OKBUCK_TARGETS_FILE = DOT_OKBUCK + "/defs/" + OKBUCK_TARGETS_BZL;
public static final String OKBUCK_TARGETS_TARGET =
"//" + DOT_OKBUCK + "/defs:" + OKBUCK_TARGETS_BZL;
private static final String OKBUCK_PREBUILT_BZL = "okbuck_prebuilt.bzl";
public static final String OKBUCK_PREBUILT_FOLDER = DOT_OKBUCK + "/defs";
public static final String OKBUCK_PREBUILT_FILE =
OKBUCK_PREBUILT_FOLDER + "/" + OKBUCK_PREBUILT_BZL;
public static final String OKBUCK_PREBUILT_TARGET =
"//" + DOT_OKBUCK + "/defs:" + OKBUCK_PREBUILT_BZL;
private static final String OKBUCK_ANDROID_MODULES_BZL = "okbuck_android_modules.bzl";
public static final String OKBUCK_ANDROID_MODULES_FILE =
DOT_OKBUCK + "/defs/" + OKBUCK_ANDROID_MODULES_BZL;
public static final String OKBUCK_ANDROID_MODULES_TARGET =
"//" + DOT_OKBUCK + "/defs:" + OKBUCK_ANDROID_MODULES_BZL;
public static final String OKBUCK_CONFIG = DOT_OKBUCK + "/config";
private static final String OKBUCK_STATE_DIR = DOT_OKBUCK + "/state";
private static final String OKBUCK_CLEAN = "okbuckClean";
private static final String BUCK_WRAPPER = "buckWrapper";
private static final String FORCED_OKBUCK = "forcedOkbuck";
private static final String PROCESSOR_BUILD_FOLDER = WORKSPACE_PATH + "/processor";
private static final String LINT_BUILD_FOLDER = WORKSPACE_PATH + "/lint";
public static final String OKBUCK_STATE = OKBUCK_STATE_DIR + "/STATE";
public static final String DEFAULT_OKBUCK_SHA256 = OKBUCK_STATE_DIR + "/SHA256";
public final Set<String> exportedPaths = Sets.newConcurrentHashSet();
public DependencyCache depCache;
public DependencyFactory dependencyFactory;
public DependencyManager dependencyManager;
public AnnotationProcessorCache annotationProcessorCache;
public LintManager lintManager;
public KotlinManager kotlinManager;
public ScalaManager scalaManager;
public GroovyManager groovyManager;
public JetifierManager jetifierManager;
public TransformManager transformManager;
public D8Manager d8Manager;
ManifestMergerManager manifestMergerManager;
RobolectricManager robolectricManager;
BuckManager buckManager;
// Only apply to the root project
@Initializer
@SuppressWarnings("NullAway")
@Override
public void apply(Project rootProject) {
// Create extensions
OkBuckExtension okbuckExt =
rootProject.getExtensions().create(OKBUCK, OkBuckExtension.class, rootProject);
// Create configurations
rootProject.getConfigurations().maybeCreate(TransformManager.CONFIGURATION_TRANSFORM);
rootProject.getConfigurations().maybeCreate(FORCED_OKBUCK);
rootProject.afterEvaluate(
rootBuckProject -> {
// Create autovalue extension configurations
Set<String> configs =
okbuckExt.getExternalDependenciesExtension().getAutoValueConfigurations();
for (String config : configs) {
rootBuckProject.getConfigurations().maybeCreate(config);
}
// Create tasks
Task setupOkbuck = rootBuckProject.getTasks().create("setupOkbuck");
setupOkbuck.setGroup(GROUP);
setupOkbuck.setDescription("Setup okbuck cache and dependencies");
// Create buck file manager.
BuckFileManager buckFileManager =
new BuckFileManager(okbuckExt.getRuleOverridesExtension());
dependencyFactory = new DependencyFactory();
// Create Annotation Processor cache
String processorBuildFile = PROCESSOR_BUILD_FOLDER + "/" + okbuckExt.buildFileName;
annotationProcessorCache =
new AnnotationProcessorCache(rootBuckProject, buckFileManager, processorBuildFile);
// Create Dependency manager
dependencyManager =
new DependencyManager(
rootBuckProject, okbuckExt, buckFileManager, createDependencyExporter(okbuckExt));
// Create Lint Manager
String lintBuildFile = LINT_BUILD_FOLDER + "/" + okbuckExt.buildFileName;
lintManager = new LintManager(rootBuckProject, lintBuildFile, buckFileManager);
// Create Kotlin Manager
kotlinManager = new KotlinManager(rootBuckProject, buckFileManager);
// Create Scala Manager
scalaManager = new ScalaManager(rootBuckProject, buckFileManager);
// Create Scala Manager
groovyManager = new GroovyManager(rootBuckProject, buckFileManager);
// Create Jetifier Manager
jetifierManager = new JetifierManager(rootBuckProject, buckFileManager);
// Create Robolectric Manager
robolectricManager = new RobolectricManager(rootBuckProject, buckFileManager);
// Create Transform Manager
transformManager = new TransformManager(rootBuckProject, buckFileManager);
// Create D8 Manager
d8Manager = new D8Manager(rootBuckProject);
// Create Buck Manager
buckManager = new BuckManager(rootBuckProject);
// Create Manifest Merger Manager
manifestMergerManager = new ManifestMergerManager(rootBuckProject, buckFileManager);
KotlinExtension kotlin = okbuckExt.getKotlinExtension();
ScalaExtension scala = okbuckExt.getScalaExtension();
Task rootOkBuckTask =
rootBuckProject
.getTasks()
.create(OKBUCK, OkBuckTask.class, okbuckExt, kotlin, scala, buckFileManager);
rootOkBuckTask.dependsOn(setupOkbuck);
rootOkBuckTask.doLast(
task -> {
annotationProcessorCache.finalizeProcessors();
dependencyManager.resolveCurrentRawDeps();
dependencyManager.finalizeDependencies(okbuckExt);
jetifierManager.finalizeDependencies(okbuckExt);
lintManager.finalizeDependencies();
kotlinManager.finalizeDependencies(okbuckExt);
scalaManager.finalizeDependencies(okbuckExt);
groovyManager.finalizeDependencies(okbuckExt);
robolectricManager.finalizeDependencies(okbuckExt);
transformManager.finalizeDependencies(okbuckExt);
buckManager.finalizeDependencies();
manifestMergerManager.finalizeDependencies(okbuckExt);
dependencyFactory.finalizeDependencies();
writeExportedFileRules(rootBuckProject, okbuckExt);
// Reset root project's scope cache at the very end
ProjectCache.resetScopeCache(rootProject);
// Reset all project's target cache at the very end.
// This cannot be done for a project just after its okbuck task since,
// the target cache is accessed by other projects and have to
// be available until okbuck tasks of all the projects finishes.
ProjectCache.resetTargetCacheForAll(rootProject);
});
WrapperExtension wrapper = okbuckExt.getWrapperExtension();
// Create wrapper task
rootBuckProject
.getTasks()
.create(
BUCK_WRAPPER,
BuckWrapperTask.class,
wrapper.repo,
wrapper.watch,
wrapper.sourceRoots,
wrapper.ignoredDirs);
Map<String, Configuration> extraConfigurations =
okbuckExt.extraDepCachesMap.keySet().stream()
.collect(
Collectors.toMap(
Function.identity(),
cacheName ->
rootBuckProject
.getConfigurations()
.maybeCreate(cacheName + "ExtraDepCache")));
setupOkbuck.doFirst(
task -> {
if (System.getProperty("okbuck.wrapper", "false").equals("false")) {
throw new IllegalArgumentException(
"Okbuck cannot be invoked without 'okbuck.wrapper' set to true. Use buckw instead");
}
});
// Configure setup task
setupOkbuck.doLast(
task -> {
// Init all project's target cache at the very start since a project
// can access other project's target cache. Hence, all target cache
// needs to be initialized before any okbuck task starts.
ProjectCache.initTargetCacheForAll(rootProject);
// Init root project's scope cache.
ProjectCache.initScopeCache(rootProject);
depCache = new DependencyCache(rootBuckProject, dependencyManager, FORCED_OKBUCK);
// Fetch Lint deps if needed
if (!okbuckExt.getLintExtension().disabled
&& okbuckExt.getLintExtension().version != null) {
lintManager.fetchLintDeps(okbuckExt.getLintExtension().version);
}
// Fetch transform deps if needed
if (!okbuckExt.getTransformExtension().transforms.isEmpty()) {
transformManager.fetchTransformDeps();
}
// Setup d8 deps
d8Manager.copyDeps(buckFileManager, okbuckExt);
// Fetch robolectric deps if needed
if (okbuckExt.getTestExtension().robolectric) {
robolectricManager.download();
}
if (JetifierManager.isJetifierEnabled(rootProject)) {
jetifierManager.setupJetifier(okbuckExt.getJetifierExtension().version);
}
extraConfigurations.forEach(
(cacheName, extraConfiguration) ->
new DependencyCache(
rootBuckProject,
dependencyManager,
okbuckExt.extraDepCachesMap.getOrDefault(cacheName, false))
.build(extraConfiguration));
buckManager.setupBuckBinary();
manifestMergerManager.fetchManifestMergerDeps();
});
// Create clean task
Task okBuckClean =
rootBuckProject
.getTasks()
.create(OKBUCK_CLEAN, OkBuckCleanTask.class, okbuckExt.buckProjects);
rootOkBuckTask.dependsOn(okBuckClean);
// Create okbuck task on each project to generate their buck file
okbuckExt.buckProjects.stream()
.filter(p -> p.getBuildFile().exists())
.forEach(
bp -> {
bp.getConfigurations().maybeCreate(BUCK_LINT);
Task okbuckProjectTask = bp.getTasks().maybeCreate(OKBUCK);
okbuckProjectTask.doLast(
task -> {
ProjectCache.initScopeCache(bp);
BuckFileGenerator.generate(bp, buckFileManager, okbuckExt);
ProjectCache.resetScopeCache(bp);
});
okbuckProjectTask.dependsOn(setupOkbuck);
okBuckClean.dependsOn(okbuckProjectTask);
});
});
}
private void writeExportedFileRules(Project rootBuckProject, OkBuckExtension okBuckExtension) {
Set<String> currentProjectPaths =
okBuckExtension.buckProjects.stream()
.filter(project -> ProjectUtil.getType(project) != ProjectType.UNKNOWN)
.map(
project ->
rootBuckProject
.getProjectDir()
.toPath()
.relativize(project.getProjectDir().toPath())
.toString())
.collect(MoreCollectors.toImmutableSet());
Map<String, Set<Rule>> pathToRules = new HashMap<>();
for (String exportedPath : exportedPaths) {
File exportedFile = rootBuckProject.file(exportedPath);
String containingPath =
FileUtil.getRelativePath(rootBuckProject.getProjectDir(), exportedFile.getParentFile());
Set<Rule> rules = pathToRules.getOrDefault(containingPath, new HashSet<>());
rules.add(new ExportFile().name(exportedFile.getName()));
pathToRules.put(containingPath, rules);
}
for (Map.Entry<String, Set<Rule>> entry : pathToRules.entrySet()) {
File buckFile =
rootBuckProject
.getRootDir()
.toPath()
.resolve(entry.getKey())
.resolve(okBuckExtension.buildFileName)
.toFile();
try (OutputStream os =
new FileOutputStream(buckFile, currentProjectPaths.contains(entry.getKey()))) {
entry.getValue().stream()
.sorted((rule1, rule2) -> rule1.name().compareToIgnoreCase(rule2.name()))
.forEach(rule -> rule.render(os));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
private static DependencyExporter createDependencyExporter(OkBuckExtension okbuckExt) {
return new JsonDependencyExporter(okbuckExt.getExportDependenciesExtension());
}
}
| uber/okbuck | buildSrc/src/main/java/com/uber/okbuck/OkBuckGradlePlugin.java | 4,580 | // Fetch Lint deps if needed | line_comment | nl | package com.uber.okbuck;
import com.facebook.infer.annotation.Initializer;
import com.google.common.collect.Sets;
import com.uber.okbuck.core.annotation.AnnotationProcessorCache;
import com.uber.okbuck.core.dependency.DependencyCache;
import com.uber.okbuck.core.dependency.DependencyFactory;
import com.uber.okbuck.core.dependency.exporter.DependencyExporter;
import com.uber.okbuck.core.dependency.exporter.JsonDependencyExporter;
import com.uber.okbuck.core.manager.BuckFileManager;
import com.uber.okbuck.core.manager.BuckManager;
import com.uber.okbuck.core.manager.D8Manager;
import com.uber.okbuck.core.manager.DependencyManager;
import com.uber.okbuck.core.manager.GroovyManager;
import com.uber.okbuck.core.manager.JetifierManager;
import com.uber.okbuck.core.manager.KotlinManager;
import com.uber.okbuck.core.manager.LintManager;
import com.uber.okbuck.core.manager.ManifestMergerManager;
import com.uber.okbuck.core.manager.RobolectricManager;
import com.uber.okbuck.core.manager.ScalaManager;
import com.uber.okbuck.core.manager.TransformManager;
import com.uber.okbuck.core.model.base.ProjectType;
import com.uber.okbuck.core.task.OkBuckCleanTask;
import com.uber.okbuck.core.task.OkBuckTask;
import com.uber.okbuck.core.util.FileUtil;
import com.uber.okbuck.core.util.MoreCollectors;
import com.uber.okbuck.core.util.ProjectCache;
import com.uber.okbuck.core.util.ProjectUtil;
import com.uber.okbuck.extension.KotlinExtension;
import com.uber.okbuck.extension.OkBuckExtension;
import com.uber.okbuck.extension.ScalaExtension;
import com.uber.okbuck.extension.WrapperExtension;
import com.uber.okbuck.generator.BuckFileGenerator;
import com.uber.okbuck.template.common.ExportFile;
import com.uber.okbuck.template.core.Rule;
import com.uber.okbuck.wrapper.BuckWrapperTask;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
// Dependency Tree
//
// rootOkBuckTask
// / \
// / v
// / okbuckClean
// / / | \
// / v v v
// / :p1:okbuck :p2:okbuck :p3:okbuck ...
// | / / /
// v v v v
// setupOkbuck
//
public class OkBuckGradlePlugin implements Plugin<Project> {
public static final String OKBUCK = "okbuck";
private static final String DOT_OKBUCK = "." + OKBUCK;
public static final String WORKSPACE_PATH = DOT_OKBUCK + "/workspace";
public static final String GROUP = OKBUCK;
public static final String BUCK_LINT = "buckLint";
private static final String OKBUCK_TARGETS_BZL = "okbuck_targets.bzl";
public static final String OKBUCK_TARGETS_FILE = DOT_OKBUCK + "/defs/" + OKBUCK_TARGETS_BZL;
public static final String OKBUCK_TARGETS_TARGET =
"//" + DOT_OKBUCK + "/defs:" + OKBUCK_TARGETS_BZL;
private static final String OKBUCK_PREBUILT_BZL = "okbuck_prebuilt.bzl";
public static final String OKBUCK_PREBUILT_FOLDER = DOT_OKBUCK + "/defs";
public static final String OKBUCK_PREBUILT_FILE =
OKBUCK_PREBUILT_FOLDER + "/" + OKBUCK_PREBUILT_BZL;
public static final String OKBUCK_PREBUILT_TARGET =
"//" + DOT_OKBUCK + "/defs:" + OKBUCK_PREBUILT_BZL;
private static final String OKBUCK_ANDROID_MODULES_BZL = "okbuck_android_modules.bzl";
public static final String OKBUCK_ANDROID_MODULES_FILE =
DOT_OKBUCK + "/defs/" + OKBUCK_ANDROID_MODULES_BZL;
public static final String OKBUCK_ANDROID_MODULES_TARGET =
"//" + DOT_OKBUCK + "/defs:" + OKBUCK_ANDROID_MODULES_BZL;
public static final String OKBUCK_CONFIG = DOT_OKBUCK + "/config";
private static final String OKBUCK_STATE_DIR = DOT_OKBUCK + "/state";
private static final String OKBUCK_CLEAN = "okbuckClean";
private static final String BUCK_WRAPPER = "buckWrapper";
private static final String FORCED_OKBUCK = "forcedOkbuck";
private static final String PROCESSOR_BUILD_FOLDER = WORKSPACE_PATH + "/processor";
private static final String LINT_BUILD_FOLDER = WORKSPACE_PATH + "/lint";
public static final String OKBUCK_STATE = OKBUCK_STATE_DIR + "/STATE";
public static final String DEFAULT_OKBUCK_SHA256 = OKBUCK_STATE_DIR + "/SHA256";
public final Set<String> exportedPaths = Sets.newConcurrentHashSet();
public DependencyCache depCache;
public DependencyFactory dependencyFactory;
public DependencyManager dependencyManager;
public AnnotationProcessorCache annotationProcessorCache;
public LintManager lintManager;
public KotlinManager kotlinManager;
public ScalaManager scalaManager;
public GroovyManager groovyManager;
public JetifierManager jetifierManager;
public TransformManager transformManager;
public D8Manager d8Manager;
ManifestMergerManager manifestMergerManager;
RobolectricManager robolectricManager;
BuckManager buckManager;
// Only apply to the root project
@Initializer
@SuppressWarnings("NullAway")
@Override
public void apply(Project rootProject) {
// Create extensions
OkBuckExtension okbuckExt =
rootProject.getExtensions().create(OKBUCK, OkBuckExtension.class, rootProject);
// Create configurations
rootProject.getConfigurations().maybeCreate(TransformManager.CONFIGURATION_TRANSFORM);
rootProject.getConfigurations().maybeCreate(FORCED_OKBUCK);
rootProject.afterEvaluate(
rootBuckProject -> {
// Create autovalue extension configurations
Set<String> configs =
okbuckExt.getExternalDependenciesExtension().getAutoValueConfigurations();
for (String config : configs) {
rootBuckProject.getConfigurations().maybeCreate(config);
}
// Create tasks
Task setupOkbuck = rootBuckProject.getTasks().create("setupOkbuck");
setupOkbuck.setGroup(GROUP);
setupOkbuck.setDescription("Setup okbuck cache and dependencies");
// Create buck file manager.
BuckFileManager buckFileManager =
new BuckFileManager(okbuckExt.getRuleOverridesExtension());
dependencyFactory = new DependencyFactory();
// Create Annotation Processor cache
String processorBuildFile = PROCESSOR_BUILD_FOLDER + "/" + okbuckExt.buildFileName;
annotationProcessorCache =
new AnnotationProcessorCache(rootBuckProject, buckFileManager, processorBuildFile);
// Create Dependency manager
dependencyManager =
new DependencyManager(
rootBuckProject, okbuckExt, buckFileManager, createDependencyExporter(okbuckExt));
// Create Lint Manager
String lintBuildFile = LINT_BUILD_FOLDER + "/" + okbuckExt.buildFileName;
lintManager = new LintManager(rootBuckProject, lintBuildFile, buckFileManager);
// Create Kotlin Manager
kotlinManager = new KotlinManager(rootBuckProject, buckFileManager);
// Create Scala Manager
scalaManager = new ScalaManager(rootBuckProject, buckFileManager);
// Create Scala Manager
groovyManager = new GroovyManager(rootBuckProject, buckFileManager);
// Create Jetifier Manager
jetifierManager = new JetifierManager(rootBuckProject, buckFileManager);
// Create Robolectric Manager
robolectricManager = new RobolectricManager(rootBuckProject, buckFileManager);
// Create Transform Manager
transformManager = new TransformManager(rootBuckProject, buckFileManager);
// Create D8 Manager
d8Manager = new D8Manager(rootBuckProject);
// Create Buck Manager
buckManager = new BuckManager(rootBuckProject);
// Create Manifest Merger Manager
manifestMergerManager = new ManifestMergerManager(rootBuckProject, buckFileManager);
KotlinExtension kotlin = okbuckExt.getKotlinExtension();
ScalaExtension scala = okbuckExt.getScalaExtension();
Task rootOkBuckTask =
rootBuckProject
.getTasks()
.create(OKBUCK, OkBuckTask.class, okbuckExt, kotlin, scala, buckFileManager);
rootOkBuckTask.dependsOn(setupOkbuck);
rootOkBuckTask.doLast(
task -> {
annotationProcessorCache.finalizeProcessors();
dependencyManager.resolveCurrentRawDeps();
dependencyManager.finalizeDependencies(okbuckExt);
jetifierManager.finalizeDependencies(okbuckExt);
lintManager.finalizeDependencies();
kotlinManager.finalizeDependencies(okbuckExt);
scalaManager.finalizeDependencies(okbuckExt);
groovyManager.finalizeDependencies(okbuckExt);
robolectricManager.finalizeDependencies(okbuckExt);
transformManager.finalizeDependencies(okbuckExt);
buckManager.finalizeDependencies();
manifestMergerManager.finalizeDependencies(okbuckExt);
dependencyFactory.finalizeDependencies();
writeExportedFileRules(rootBuckProject, okbuckExt);
// Reset root project's scope cache at the very end
ProjectCache.resetScopeCache(rootProject);
// Reset all project's target cache at the very end.
// This cannot be done for a project just after its okbuck task since,
// the target cache is accessed by other projects and have to
// be available until okbuck tasks of all the projects finishes.
ProjectCache.resetTargetCacheForAll(rootProject);
});
WrapperExtension wrapper = okbuckExt.getWrapperExtension();
// Create wrapper task
rootBuckProject
.getTasks()
.create(
BUCK_WRAPPER,
BuckWrapperTask.class,
wrapper.repo,
wrapper.watch,
wrapper.sourceRoots,
wrapper.ignoredDirs);
Map<String, Configuration> extraConfigurations =
okbuckExt.extraDepCachesMap.keySet().stream()
.collect(
Collectors.toMap(
Function.identity(),
cacheName ->
rootBuckProject
.getConfigurations()
.maybeCreate(cacheName + "ExtraDepCache")));
setupOkbuck.doFirst(
task -> {
if (System.getProperty("okbuck.wrapper", "false").equals("false")) {
throw new IllegalArgumentException(
"Okbuck cannot be invoked without 'okbuck.wrapper' set to true. Use buckw instead");
}
});
// Configure setup task
setupOkbuck.doLast(
task -> {
// Init all project's target cache at the very start since a project
// can access other project's target cache. Hence, all target cache
// needs to be initialized before any okbuck task starts.
ProjectCache.initTargetCacheForAll(rootProject);
// Init root project's scope cache.
ProjectCache.initScopeCache(rootProject);
depCache = new DependencyCache(rootBuckProject, dependencyManager, FORCED_OKBUCK);
// Fetch Lint<SUF>
if (!okbuckExt.getLintExtension().disabled
&& okbuckExt.getLintExtension().version != null) {
lintManager.fetchLintDeps(okbuckExt.getLintExtension().version);
}
// Fetch transform deps if needed
if (!okbuckExt.getTransformExtension().transforms.isEmpty()) {
transformManager.fetchTransformDeps();
}
// Setup d8 deps
d8Manager.copyDeps(buckFileManager, okbuckExt);
// Fetch robolectric deps if needed
if (okbuckExt.getTestExtension().robolectric) {
robolectricManager.download();
}
if (JetifierManager.isJetifierEnabled(rootProject)) {
jetifierManager.setupJetifier(okbuckExt.getJetifierExtension().version);
}
extraConfigurations.forEach(
(cacheName, extraConfiguration) ->
new DependencyCache(
rootBuckProject,
dependencyManager,
okbuckExt.extraDepCachesMap.getOrDefault(cacheName, false))
.build(extraConfiguration));
buckManager.setupBuckBinary();
manifestMergerManager.fetchManifestMergerDeps();
});
// Create clean task
Task okBuckClean =
rootBuckProject
.getTasks()
.create(OKBUCK_CLEAN, OkBuckCleanTask.class, okbuckExt.buckProjects);
rootOkBuckTask.dependsOn(okBuckClean);
// Create okbuck task on each project to generate their buck file
okbuckExt.buckProjects.stream()
.filter(p -> p.getBuildFile().exists())
.forEach(
bp -> {
bp.getConfigurations().maybeCreate(BUCK_LINT);
Task okbuckProjectTask = bp.getTasks().maybeCreate(OKBUCK);
okbuckProjectTask.doLast(
task -> {
ProjectCache.initScopeCache(bp);
BuckFileGenerator.generate(bp, buckFileManager, okbuckExt);
ProjectCache.resetScopeCache(bp);
});
okbuckProjectTask.dependsOn(setupOkbuck);
okBuckClean.dependsOn(okbuckProjectTask);
});
});
}
private void writeExportedFileRules(Project rootBuckProject, OkBuckExtension okBuckExtension) {
Set<String> currentProjectPaths =
okBuckExtension.buckProjects.stream()
.filter(project -> ProjectUtil.getType(project) != ProjectType.UNKNOWN)
.map(
project ->
rootBuckProject
.getProjectDir()
.toPath()
.relativize(project.getProjectDir().toPath())
.toString())
.collect(MoreCollectors.toImmutableSet());
Map<String, Set<Rule>> pathToRules = new HashMap<>();
for (String exportedPath : exportedPaths) {
File exportedFile = rootBuckProject.file(exportedPath);
String containingPath =
FileUtil.getRelativePath(rootBuckProject.getProjectDir(), exportedFile.getParentFile());
Set<Rule> rules = pathToRules.getOrDefault(containingPath, new HashSet<>());
rules.add(new ExportFile().name(exportedFile.getName()));
pathToRules.put(containingPath, rules);
}
for (Map.Entry<String, Set<Rule>> entry : pathToRules.entrySet()) {
File buckFile =
rootBuckProject
.getRootDir()
.toPath()
.resolve(entry.getKey())
.resolve(okBuckExtension.buildFileName)
.toFile();
try (OutputStream os =
new FileOutputStream(buckFile, currentProjectPaths.contains(entry.getKey()))) {
entry.getValue().stream()
.sorted((rule1, rule2) -> rule1.name().compareToIgnoreCase(rule2.name()))
.forEach(rule -> rule.render(os));
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
private static DependencyExporter createDependencyExporter(OkBuckExtension okbuckExt) {
return new JsonDependencyExporter(okbuckExt.getExportDependenciesExtension());
}
}
|
16220_3 | /* This file is part of Waisda
Copyright (c) 2012 Netherlands Institute for Sound and Vision
https://github.com/beeldengeluid/waisda
Waisda 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.
Waisda 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 Waisda. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.waisda.domain;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.annotations.Formula;
@Entity
public class Video {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Basic
private String title;
/** Duration in ms. */
@Column(nullable = false)
private int duration;
@Basic
private String imageUrl;
@Basic
private boolean enabled;
@Formula("(SELECT COUNT(*) FROM Game g WHERE g.video_id = id)")
private int timesPlayed;
@Enumerated(EnumType.STRING)
private PlayerType playerType;
@Basic
private String fragmentID;
/** Start time within episode, in ms. */
@Basic
private Integer startTime;
/** Fragmentenrubriek zoals in MBH dump. */
private Integer sectionNid;
private String sourceUrl;
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public int getDuration() {
return duration;
}
public String getImageUrl() {
return imageUrl;
}
public boolean isEnabled() {
return enabled;
}
public int getTimesPlayed() {
return timesPlayed;
}
public PlayerType getPlayerType() {
return playerType;
}
public String getFragmentID() {
return fragmentID;
}
public Integer getStartTime() {
return startTime;
}
public Integer getSectionNid() {
return sectionNid;
}
public String getSourceUrl() {
return sourceUrl;
}
public String getPrettyDuration() {
return TagEntry.getFriendlyTime(duration);
}
} | ucds-vu/waisda | src/main/java/nl/waisda/domain/Video.java | 816 | /** Fragmentenrubriek zoals in MBH dump. */ | block_comment | nl | /* This file is part of Waisda
Copyright (c) 2012 Netherlands Institute for Sound and Vision
https://github.com/beeldengeluid/waisda
Waisda 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.
Waisda 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 Waisda. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.waisda.domain;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.annotations.Formula;
@Entity
public class Video {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Basic
private String title;
/** Duration in ms. */
@Column(nullable = false)
private int duration;
@Basic
private String imageUrl;
@Basic
private boolean enabled;
@Formula("(SELECT COUNT(*) FROM Game g WHERE g.video_id = id)")
private int timesPlayed;
@Enumerated(EnumType.STRING)
private PlayerType playerType;
@Basic
private String fragmentID;
/** Start time within episode, in ms. */
@Basic
private Integer startTime;
/** Fragmentenrubriek zoals in<SUF>*/
private Integer sectionNid;
private String sourceUrl;
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public int getDuration() {
return duration;
}
public String getImageUrl() {
return imageUrl;
}
public boolean isEnabled() {
return enabled;
}
public int getTimesPlayed() {
return timesPlayed;
}
public PlayerType getPlayerType() {
return playerType;
}
public String getFragmentID() {
return fragmentID;
}
public Integer getStartTime() {
return startTime;
}
public Integer getSectionNid() {
return sectionNid;
}
public String getSourceUrl() {
return sourceUrl;
}
public String getPrettyDuration() {
return TagEntry.getFriendlyTime(duration);
}
} |
112457_14 | /*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor Benoit Macq
* Copyright (c) 2002-2007, Patrick Piscaglia, Telemis s.a.
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `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 THE COPYRIGHT OWNER OR 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.
*/
package org.openJpeg;
import java.util.Vector;
/** This class decodes one J2K codestream into an image (width + height + depth + pixels[],
* using the OpenJPEG.org library.
* To be able to log messages, the called must register a IJavaJ2KDecoderLogger object.
*/
public class OpenJPEGJavaDecoder {
public interface IJavaJ2KDecoderLogger {
public void logDecoderMessage(String message);
public void logDecoderError(String message);
}
private static boolean isInitialized = false;
// ===== decompression parameters =============>
// These value may be changed for each image
private String[] decoder_arguments = null;
/** number of resolutions decompositions */
private int nbResolutions = -1;
/** the quality layers */
private int[] layers = null;
/** Contains the 8 bpp version of the image. May NOT be filled together with image16 or image24.<P>
* We store in Java the 8 or 16 bpp version of the image while the decoder uses a 32 bpp version, because <UL>
* <LI> the storage capacity required is smaller
* <LI> the transfer Java <-- C will be faster
* <LI> the conversion byte/short ==> int will be done faster by the C
* </UL>*/
private byte[] image8 = null;
/** Contains the 16 bpp version of the image. May NOT be filled together with image8 or image24*/
private short[] image16 = null;
/** Contains the 24 bpp version of the image. May NOT be filled together with image8 or image16 */
private int[] image24 = null;
/** Holds the J2K compressed bytecode to decode */
private byte compressedStream[] = null;
/** Holds the compressed version of the index file, to be used by the decoder */
private byte compressedIndex[] = null;
/** Width and Height of the image */
private int width = -1;
private int height = -1;
private int depth = -1;
/** This parameter is never used in Java but is read by the C library to know the number of resolutions to skip when decoding,
* i.e. if there are 5 resolutions and skipped=1 ==> decode until resolution 4. */
private int skippedResolutions = 0;
private Vector<IJavaJ2KDecoderLogger> loggers = new Vector();
public OpenJPEGJavaDecoder(String openJPEGlibraryFullPathAndName, IJavaJ2KDecoderLogger messagesAndErrorsLogger) throws ExceptionInInitializerError
{
this(openJPEGlibraryFullPathAndName);
loggers.addElement(messagesAndErrorsLogger);
}
public OpenJPEGJavaDecoder(String openJPEGlibraryFullPathAndName) throws ExceptionInInitializerError
{
if (!isInitialized) {
try {
System.load(openJPEGlibraryFullPathAndName);
isInitialized = true;
} catch (Throwable t) {
throw new ExceptionInInitializerError("OpenJPEG Java Decoder: probably impossible to find the C library");
}
}
}
public void addLogger(IJavaJ2KDecoderLogger messagesAndErrorsLogger) {
loggers.addElement(messagesAndErrorsLogger);
}
public void removeLogger(IJavaJ2KDecoderLogger messagesAndErrorsLogger) {
loggers.removeElement(messagesAndErrorsLogger);
}
public int decodeJ2KtoImage() {
if ((image16 == null || (image16 != null && image16.length != width*height)) && (depth==-1 || depth==16)) {
image16 = new short[width*height];
logMessage("OpenJPEGJavaDecoder.decompressImage: image16 length = " + image16.length + " (" + width + " x " + height + ") ");
}
if ((image8 == null || (image8 != null && image8.length != width*height)) && (depth==-1 || depth==8)) {
image8 = new byte[width*height];
logMessage("OpenJPEGJavaDecoder.decompressImage: image8 length = " + image8.length + " (" + width + " x " + height + ") ");
}
if ((image24 == null || (image24 != null && image24.length != width*height)) && (depth==-1 || depth==24)) {
image24 = new int[width*height];
logMessage("OpenJPEGJavaDecoder.decompressImage: image24 length = " + image24.length + " (" + width + " x " + height + ") ");
}
String[] arguments = new String[0 + (decoder_arguments != null ? decoder_arguments.length : 0)];
int offset = 0;
if (decoder_arguments != null) {
for (int i=0; i<decoder_arguments.length; i++) {
arguments[i+offset] = decoder_arguments[i];
}
}
return internalDecodeJ2KtoImage(arguments);
}
/**
* Decode the j2k stream given in the codestream byte[] and fills the image8, image16 or image24 array, according to the bit depth.
*/
private native int internalDecodeJ2KtoImage(String[] parameters);
/** Image depth in bpp */
public int getDepth() {
return depth;
}
/** Image depth in bpp */
public void setDepth(int depth) {
this.depth = depth;
}
/** Image height in pixels */
public int getHeight() {
return height;
}
/** Image height in pixels */
public void setHeight(int height) {
this.height = height;
}
/** Number of resolutions contained in the image */
public int getNbResolutions() {
return nbResolutions;
}
/** Number of resolutions contained in the image */
public void setNbResolutions(int nbResolutions) {
this.nbResolutions = nbResolutions;
}
/** Width of the image in pixels */
public int getWidth() {
return width;
}
/** Width of the image in pixels */
public void setWidth(int width) {
this.width = width;
}
/** Contains the decompressed version of the image, if the depth in is [9,16] bpp.
* Returns NULL otherwise.
*/
public short[] getImage16() {
return image16;
}
/** Contains the decompressed version of the image, if the depth in is [17,24] bpp and the image is in color.
* Returns NULL otherwise.
*/
public int[] getImage24() {
return image24;
}
/** Contains the decompressed version of the image, if the depth in is [1,8] bpp.
* Returns NULL otherwise.
*/
public byte[] getImage8() {
return image8;
}
/** Sets the compressed version of the index file for this image.
* This index file is used by the decompressor
*/
public void setCompressedIndex(byte[] compressedIndex) {
this.compressedIndex = compressedIndex;
}
/** Sets the codestream to be decoded */
public void setCompressedStream(byte[] compressedStream) {
this.compressedStream = compressedStream;
}
/** @return the compressed code stream length, or -1 if not defined */
public long getCodestreamLength() {
if (compressedStream == null)
return -1;
else return compressedStream.length;
}
/** This method is called either directly or by the C methods */
public void logMessage(String message) {
for (IJavaJ2KDecoderLogger logger:loggers)
logger.logDecoderMessage(message);
}
/** This method is called either directly or by the C methods */
public void logError(String error) {
for (IJavaJ2KDecoderLogger logger:loggers)
logger.logDecoderError(error);
}
public void reset() {
nbResolutions = -1;
layers = null;
image8 = null;
image16 = null;
image24 = null;
compressedStream = null;
compressedIndex = null;
width = -1;
height = -1;
depth = -1;
}
public void setSkippedResolutions(int numberOfSkippedResolutions) {
skippedResolutions = numberOfSkippedResolutions;
}
/** Contains all the decoding arguments other than the input/output file */
public void setDecoderArguments(String[] argumentsForTheDecoder) {
decoder_arguments = argumentsForTheDecoder;
}
}
| uclouvain/openjpeg | wrapping/java/openjp2/java-sources/org/openJpeg/OpenJPEGJavaDecoder.java | 2,735 | /** Image depth in bpp */ | block_comment | nl | /*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor Benoit Macq
* Copyright (c) 2002-2007, Patrick Piscaglia, Telemis s.a.
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `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 THE COPYRIGHT OWNER OR 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.
*/
package org.openJpeg;
import java.util.Vector;
/** This class decodes one J2K codestream into an image (width + height + depth + pixels[],
* using the OpenJPEG.org library.
* To be able to log messages, the called must register a IJavaJ2KDecoderLogger object.
*/
public class OpenJPEGJavaDecoder {
public interface IJavaJ2KDecoderLogger {
public void logDecoderMessage(String message);
public void logDecoderError(String message);
}
private static boolean isInitialized = false;
// ===== decompression parameters =============>
// These value may be changed for each image
private String[] decoder_arguments = null;
/** number of resolutions decompositions */
private int nbResolutions = -1;
/** the quality layers */
private int[] layers = null;
/** Contains the 8 bpp version of the image. May NOT be filled together with image16 or image24.<P>
* We store in Java the 8 or 16 bpp version of the image while the decoder uses a 32 bpp version, because <UL>
* <LI> the storage capacity required is smaller
* <LI> the transfer Java <-- C will be faster
* <LI> the conversion byte/short ==> int will be done faster by the C
* </UL>*/
private byte[] image8 = null;
/** Contains the 16 bpp version of the image. May NOT be filled together with image8 or image24*/
private short[] image16 = null;
/** Contains the 24 bpp version of the image. May NOT be filled together with image8 or image16 */
private int[] image24 = null;
/** Holds the J2K compressed bytecode to decode */
private byte compressedStream[] = null;
/** Holds the compressed version of the index file, to be used by the decoder */
private byte compressedIndex[] = null;
/** Width and Height of the image */
private int width = -1;
private int height = -1;
private int depth = -1;
/** This parameter is never used in Java but is read by the C library to know the number of resolutions to skip when decoding,
* i.e. if there are 5 resolutions and skipped=1 ==> decode until resolution 4. */
private int skippedResolutions = 0;
private Vector<IJavaJ2KDecoderLogger> loggers = new Vector();
public OpenJPEGJavaDecoder(String openJPEGlibraryFullPathAndName, IJavaJ2KDecoderLogger messagesAndErrorsLogger) throws ExceptionInInitializerError
{
this(openJPEGlibraryFullPathAndName);
loggers.addElement(messagesAndErrorsLogger);
}
public OpenJPEGJavaDecoder(String openJPEGlibraryFullPathAndName) throws ExceptionInInitializerError
{
if (!isInitialized) {
try {
System.load(openJPEGlibraryFullPathAndName);
isInitialized = true;
} catch (Throwable t) {
throw new ExceptionInInitializerError("OpenJPEG Java Decoder: probably impossible to find the C library");
}
}
}
public void addLogger(IJavaJ2KDecoderLogger messagesAndErrorsLogger) {
loggers.addElement(messagesAndErrorsLogger);
}
public void removeLogger(IJavaJ2KDecoderLogger messagesAndErrorsLogger) {
loggers.removeElement(messagesAndErrorsLogger);
}
public int decodeJ2KtoImage() {
if ((image16 == null || (image16 != null && image16.length != width*height)) && (depth==-1 || depth==16)) {
image16 = new short[width*height];
logMessage("OpenJPEGJavaDecoder.decompressImage: image16 length = " + image16.length + " (" + width + " x " + height + ") ");
}
if ((image8 == null || (image8 != null && image8.length != width*height)) && (depth==-1 || depth==8)) {
image8 = new byte[width*height];
logMessage("OpenJPEGJavaDecoder.decompressImage: image8 length = " + image8.length + " (" + width + " x " + height + ") ");
}
if ((image24 == null || (image24 != null && image24.length != width*height)) && (depth==-1 || depth==24)) {
image24 = new int[width*height];
logMessage("OpenJPEGJavaDecoder.decompressImage: image24 length = " + image24.length + " (" + width + " x " + height + ") ");
}
String[] arguments = new String[0 + (decoder_arguments != null ? decoder_arguments.length : 0)];
int offset = 0;
if (decoder_arguments != null) {
for (int i=0; i<decoder_arguments.length; i++) {
arguments[i+offset] = decoder_arguments[i];
}
}
return internalDecodeJ2KtoImage(arguments);
}
/**
* Decode the j2k stream given in the codestream byte[] and fills the image8, image16 or image24 array, according to the bit depth.
*/
private native int internalDecodeJ2KtoImage(String[] parameters);
/** Image depth in<SUF>*/
public int getDepth() {
return depth;
}
/** Image depth in bpp */
public void setDepth(int depth) {
this.depth = depth;
}
/** Image height in pixels */
public int getHeight() {
return height;
}
/** Image height in pixels */
public void setHeight(int height) {
this.height = height;
}
/** Number of resolutions contained in the image */
public int getNbResolutions() {
return nbResolutions;
}
/** Number of resolutions contained in the image */
public void setNbResolutions(int nbResolutions) {
this.nbResolutions = nbResolutions;
}
/** Width of the image in pixels */
public int getWidth() {
return width;
}
/** Width of the image in pixels */
public void setWidth(int width) {
this.width = width;
}
/** Contains the decompressed version of the image, if the depth in is [9,16] bpp.
* Returns NULL otherwise.
*/
public short[] getImage16() {
return image16;
}
/** Contains the decompressed version of the image, if the depth in is [17,24] bpp and the image is in color.
* Returns NULL otherwise.
*/
public int[] getImage24() {
return image24;
}
/** Contains the decompressed version of the image, if the depth in is [1,8] bpp.
* Returns NULL otherwise.
*/
public byte[] getImage8() {
return image8;
}
/** Sets the compressed version of the index file for this image.
* This index file is used by the decompressor
*/
public void setCompressedIndex(byte[] compressedIndex) {
this.compressedIndex = compressedIndex;
}
/** Sets the codestream to be decoded */
public void setCompressedStream(byte[] compressedStream) {
this.compressedStream = compressedStream;
}
/** @return the compressed code stream length, or -1 if not defined */
public long getCodestreamLength() {
if (compressedStream == null)
return -1;
else return compressedStream.length;
}
/** This method is called either directly or by the C methods */
public void logMessage(String message) {
for (IJavaJ2KDecoderLogger logger:loggers)
logger.logDecoderMessage(message);
}
/** This method is called either directly or by the C methods */
public void logError(String error) {
for (IJavaJ2KDecoderLogger logger:loggers)
logger.logDecoderError(error);
}
public void reset() {
nbResolutions = -1;
layers = null;
image8 = null;
image16 = null;
image24 = null;
compressedStream = null;
compressedIndex = null;
width = -1;
height = -1;
depth = -1;
}
public void setSkippedResolutions(int numberOfSkippedResolutions) {
skippedResolutions = numberOfSkippedResolutions;
}
/** Contains all the decoding arguments other than the input/output file */
public void setDecoderArguments(String[] argumentsForTheDecoder) {
decoder_arguments = argumentsForTheDecoder;
}
}
|
178799_6 | public class Simulation {
// gravitational constant
public static final double G = 6.6743e-11;
// one astronomical unit (AU) is the average distance of earth to the sun.
public static final double AU = 150e9;
// all quantities are based on units of kilogram respectively second and meter.
// The main simulation method using instances of other classes.
public static void main(String[] args) {
//TODO: change implementation of this method according to 'Aufgabe1.md'.
Body sun = new Body("Sol",1.989e30,696340e3,new Vector3(0,0,0),new Vector3(0,0,0),StdDraw.YELLOW);
Body earth = new Body("Earth",5.972e24,6371e3,new Vector3(-1.394555e11,5.103346e10,0),new Vector3(-10308.53,-28169.38,0),StdDraw.BLUE);
Body mercury = new Body("Mercury",3.301e23,2440e3,new Vector3(-5.439054e10,9.394878e9,0),new Vector3(-17117.83,-46297.48,-1925.57),StdDraw.GRAY);
Body venus = new Body("Venus",4.86747e24,6052e3,new Vector3(-1.707667e10,1.066132e11,2.450232e9),new Vector3(-34446.02,-5567.47,2181.10),StdDraw.PINK);
Body mars = new Body("Mars",6.41712e23,3390e3,new Vector3(-1.010178e11,-2.043939e11,-1.591727E9),new Vector3(20651.98,-10186.67,-2302.79),StdDraw.RED);
CosmicSystem cs = new CosmicSystem("CosmicSystem");
cs.add(sun);
cs.add(earth);
cs.add(mercury);
cs.add(venus);
cs.add(mars);
StdDraw.setCanvasSize(500, 500);
StdDraw.setXscale(-2 * AU, 2 * AU);
StdDraw.setYscale(-2 * AU, 2 * AU);
StdDraw.enableDoubleBuffering();
StdDraw.clear(StdDraw.BLACK);
double seconds = 0;
// simulation loop
while (true) {
seconds++; // each iteration computes the movement of the celestial bodies within one second.
// for each body (with index i): compute the total force exerted on it.
for (int i = 0; i < cs.size(); i++) {
cs.get(i).setForce(new Vector3(0, 0, 0)); // begin with zero
for (int j = 0; j < cs.size(); j++) {
if (i == j) continue;
Vector3 forceToAdd = cs.get(i).gravitationalForce(cs.get(j));
cs.get(i).setForce(forceToAdd.plus(cs.get(i).getForce()));
}
}
// now forceOnBody[i] holds the force vector exerted on body with index i.
// for each body (with index i): move it according to the total force exerted on it.
for (int i = 0; i < cs.size(); i++) {
cs.get(i).move();
}
// show all movements in StdDraw canvas only every 3 hours (to speed up the simulation)
if (seconds % (3 * 3600) == 0) {
// clear old positions (exclude the following line if you want to draw orbits).
StdDraw.clear(StdDraw.BLACK);
// draw new positions
for (int i = 0; i < cs.size(); i++) {
cs.get(i).draw();
}
// show new positions
StdDraw.show();
}
}
}
}
//TODO: answer additional questions of 'Aufgabe1'.
//Was versteht man unter Datenkapselung? Geben Sie ein Beispiel, wo dieses Konzept in dieser Aufgabenstellung angewendet wird.
// Unter der Datenkapselung versteht man, dass zusammenfassen von Methoden und Variablen zu einer Einheit.
//
// Bei der Methode gravitationalForce wurde dieses System angewandt.
//Was versteht man unter Data Hiding? Geben Sie ein Beispiel, wo dieses Konzept in dieser Aufgabenstellung angewendet wird.
// private/public
// public gehört zur Außen- und Innensicht
// private gehört nur zur Innensicht
// Man versteckt bewusst Informationen und verhindert so unbefugten Zugriff.
//
// Alle Variablen oder Methoden.
// Beispielsweise bei der Klasse Vector3 x,y,z. | ukalto/Introduction_To_Programming_2 | src/Simulation.java | 1,266 | // begin with zero | line_comment | nl | public class Simulation {
// gravitational constant
public static final double G = 6.6743e-11;
// one astronomical unit (AU) is the average distance of earth to the sun.
public static final double AU = 150e9;
// all quantities are based on units of kilogram respectively second and meter.
// The main simulation method using instances of other classes.
public static void main(String[] args) {
//TODO: change implementation of this method according to 'Aufgabe1.md'.
Body sun = new Body("Sol",1.989e30,696340e3,new Vector3(0,0,0),new Vector3(0,0,0),StdDraw.YELLOW);
Body earth = new Body("Earth",5.972e24,6371e3,new Vector3(-1.394555e11,5.103346e10,0),new Vector3(-10308.53,-28169.38,0),StdDraw.BLUE);
Body mercury = new Body("Mercury",3.301e23,2440e3,new Vector3(-5.439054e10,9.394878e9,0),new Vector3(-17117.83,-46297.48,-1925.57),StdDraw.GRAY);
Body venus = new Body("Venus",4.86747e24,6052e3,new Vector3(-1.707667e10,1.066132e11,2.450232e9),new Vector3(-34446.02,-5567.47,2181.10),StdDraw.PINK);
Body mars = new Body("Mars",6.41712e23,3390e3,new Vector3(-1.010178e11,-2.043939e11,-1.591727E9),new Vector3(20651.98,-10186.67,-2302.79),StdDraw.RED);
CosmicSystem cs = new CosmicSystem("CosmicSystem");
cs.add(sun);
cs.add(earth);
cs.add(mercury);
cs.add(venus);
cs.add(mars);
StdDraw.setCanvasSize(500, 500);
StdDraw.setXscale(-2 * AU, 2 * AU);
StdDraw.setYscale(-2 * AU, 2 * AU);
StdDraw.enableDoubleBuffering();
StdDraw.clear(StdDraw.BLACK);
double seconds = 0;
// simulation loop
while (true) {
seconds++; // each iteration computes the movement of the celestial bodies within one second.
// for each body (with index i): compute the total force exerted on it.
for (int i = 0; i < cs.size(); i++) {
cs.get(i).setForce(new Vector3(0, 0, 0)); // begin with<SUF>
for (int j = 0; j < cs.size(); j++) {
if (i == j) continue;
Vector3 forceToAdd = cs.get(i).gravitationalForce(cs.get(j));
cs.get(i).setForce(forceToAdd.plus(cs.get(i).getForce()));
}
}
// now forceOnBody[i] holds the force vector exerted on body with index i.
// for each body (with index i): move it according to the total force exerted on it.
for (int i = 0; i < cs.size(); i++) {
cs.get(i).move();
}
// show all movements in StdDraw canvas only every 3 hours (to speed up the simulation)
if (seconds % (3 * 3600) == 0) {
// clear old positions (exclude the following line if you want to draw orbits).
StdDraw.clear(StdDraw.BLACK);
// draw new positions
for (int i = 0; i < cs.size(); i++) {
cs.get(i).draw();
}
// show new positions
StdDraw.show();
}
}
}
}
//TODO: answer additional questions of 'Aufgabe1'.
//Was versteht man unter Datenkapselung? Geben Sie ein Beispiel, wo dieses Konzept in dieser Aufgabenstellung angewendet wird.
// Unter der Datenkapselung versteht man, dass zusammenfassen von Methoden und Variablen zu einer Einheit.
//
// Bei der Methode gravitationalForce wurde dieses System angewandt.
//Was versteht man unter Data Hiding? Geben Sie ein Beispiel, wo dieses Konzept in dieser Aufgabenstellung angewendet wird.
// private/public
// public gehört zur Außen- und Innensicht
// private gehört nur zur Innensicht
// Man versteckt bewusst Informationen und verhindert so unbefugten Zugriff.
//
// Alle Variablen oder Methoden.
// Beispielsweise bei der Klasse Vector3 x,y,z. |
152463_83 | package uk.bl.wa.nlp.analysers;
///**
// * A nice idea, but seems to rely of many local resources from the local filesystem, which is awkward.
//
// i.e. the following is not enough:
//
// <dependency>
// <groupId>uk.ac.gate</groupId>
// <artifactId>gate-core</artifactId>
// <version>7.1</version>
// </dependency>
//
//
//
// if (conf.hasPath("warc.index.extract.content.text_gate") &&
// conf.getBoolean("warc.index.extract.content.text_gate")) {
// analysers.add(new GateTextAnalyser(conf)); }
//
//
//
// */
//package uk.bl.wa.analyser.text;
/*
* #%L
* warc-indexer
* %%
* Copyright (C) 2013 - 2020 The webarchive-discovery project contributors
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
//
//
//
///*
// * StandAloneAnnie.java
// *
// *
// * Copyright (c) 2000-2001, The University of Sheffield.
// *
// * This file is part of GATE (see http://gate.ac.uk/), and is free
// * software, licenced under the GNU Library General Public License,
// * Version 2, June1991.
// *
// * A copy of this licence is included in the distribution in the file
// * licence.html, and is also available at http://gate.ac.uk/gate/licence.html.
// *
// * hamish, 29/1/2002
// *
// * $Id: StandAloneAnnie.java,v 1.6 2006/01/09 16:43:22 ian Exp $
// */
//
//import gate.Annotation;
//import gate.AnnotationSet;
//import gate.Corpus;
//import gate.CorpusController;
//import gate.Document;
//import gate.Factory;
//import gate.FeatureMap;
//import gate.Gate;
//import gate.GateConstants;
//import gate.corpora.RepositioningInfo;
//import gate.util.GateException;
//import gate.util.Out;
//import gate.util.persistence.PersistenceManager;
//
//import java.io.File;
//import java.io.FileWriter;
//import java.io.IOException;
//import java.net.URL;
//import java.util.HashSet;
//import java.util.Iterator;
//import java.util.Set;
//import java.util.Vector;
//
///**
// * This class illustrates how to use ANNIE as a sausage machine
// * in another application - put ingredients in one end (URLs pointing
// * to documents) and get sausages (e.g. Named Entities) out the
// * other end.
// * <P><B>NOTE:</B><BR>
// * For simplicity's sake, we don't do any exception handling.
// */
//public class GateTextAnalyser {
//
// /** The Corpus Pipeline application to contain ANNIE */
// private CorpusController annieController;
//
// /**
// * Initialise the ANNIE system. This creates a "corpus pipeline"
// * application that can be used to run sets of documents through
// * the extraction system.
// */
// public void initAnnie() throws GateException, IOException {
// Out.prln("Initialising ANNIE...");
//
// // load the ANNIE application from the saved state in plugins/ANNIE
// File pluginsHome = Gate.getPluginsHome();
// File anniePlugin = new File(pluginsHome, "ANNIE");
// File annieGapp = new File(anniePlugin, "ANNIE_with_defaults.gapp");
// annieController =
// (CorpusController) PersistenceManager.loadObjectFromFile(annieGapp);
//
// Out.prln("...ANNIE loaded");
// } // initAnnie()
//
// /** Tell ANNIE's controller about the corpus you want to run on */
// public void setCorpus(Corpus corpus) {
// annieController.setCorpus(corpus);
// } // setCorpus
//
// /** Run ANNIE */
// public void execute() throws GateException {
// Out.prln("Running ANNIE...");
// annieController.execute();
// Out.prln("...ANNIE complete");
// } // execute()
//
// /**
// * Run from the command-line, with a list of URLs as argument.
// * <P><B>NOTE:</B><BR>
// * This code will run with all the documents in memory - if you
// * want to unload each from memory after use, add code to store
// * the corpus in a DataStore.
// */
// public static void main(String args[]) throws GateException, IOException {
// // initialise the GATE library
// Out.prln("Initialising GATE...");
// Gate.init();
// Out.prln("...GATE initialised");
//
// // initialise ANNIE (this may take several minutes)
// GateTextAnalyser annie = new GateTextAnalyser();
// annie.initAnnie();
//
// // create a GATE corpus and add a document for each command-line
// // argument
// Corpus corpus = Factory.newCorpus("StandAloneAnnie corpus");
// for(int i = 0; i < args.length; i++) {
// URL u = new URL(args[i]);
// FeatureMap params = Factory.newFeatureMap();
// params.put("sourceUrl", u);
// params.put("preserveOriginalContent", new Boolean(true));
// params.put("collectRepositioningInfo", new Boolean(true));
// Out.prln("Creating doc for " + u);
// Document doc = (Document)
// Factory.createResource("gate.corpora.DocumentImpl", params);
// corpus.add(doc);
// } // for each of args
//
// // tell the pipeline about the corpus and run it
// annie.setCorpus(corpus);
// annie.execute();
//
// // for each document, get an XML document with the
// // person and location names added
// Iterator iter = corpus.iterator();
// int count = 0;
// String startTagPart_1 = "<span GateID=\"";
// String startTagPart_2 = "\" title=\"";
// String startTagPart_3 = "\" style=\"background:Red;\">";
// String endTag = "</span>";
//
// while(iter.hasNext()) {
// Document doc = (Document) iter.next();
// AnnotationSet defaultAnnotSet = doc.getAnnotations();
// Set annotTypesRequired = new HashSet();
// annotTypesRequired.add("Person");
// annotTypesRequired.add("Location");
// Set<Annotation> peopleAndPlaces =
// new HashSet<Annotation>(defaultAnnotSet.get(annotTypesRequired));
//
// FeatureMap features = doc.getFeatures();
// String originalContent = (String)
// features.get(GateConstants.ORIGINAL_DOCUMENT_CONTENT_FEATURE_NAME);
// RepositioningInfo info = (RepositioningInfo)
// features.get(GateConstants.DOCUMENT_REPOSITIONING_INFO_FEATURE_NAME);
//
// ++count;
// File file = new File("StANNIE_" + count + ".HTML");
// Out.prln("File name: '"+file.getAbsolutePath()+"'");
// if(originalContent != null && info != null) {
// Out.prln("OrigContent and reposInfo existing. Generate file...");
//
// Iterator it = peopleAndPlaces.iterator();
// Annotation currAnnot;
// SortedAnnotationList sortedAnnotations = new SortedAnnotationList();
//
// while(it.hasNext()) {
// currAnnot = (Annotation) it.next();
// sortedAnnotations.addSortedExclusive(currAnnot);
// } // while
//
// StringBuffer editableContent = new StringBuffer(originalContent);
// long insertPositionEnd;
// long insertPositionStart;
// // insert anotation tags backward
// Out.prln("Unsorted annotations count: "+peopleAndPlaces.size());
// Out.prln("Sorted annotations count: "+sortedAnnotations.size());
// for(int i=sortedAnnotations.size()-1; i>=0; --i) {
// currAnnot = (Annotation) sortedAnnotations.get(i);
// insertPositionStart =
// currAnnot.getStartNode().getOffset().longValue();
// insertPositionStart = info.getOriginalPos(insertPositionStart);
// insertPositionEnd = currAnnot.getEndNode().getOffset().longValue();
// insertPositionEnd = info.getOriginalPos(insertPositionEnd, true);
// if(insertPositionEnd != -1 && insertPositionStart != -1) {
// editableContent.insert((int)insertPositionEnd, endTag);
// editableContent.insert((int)insertPositionStart, startTagPart_3);
// editableContent.insert((int)insertPositionStart,
// currAnnot.getType());
// editableContent.insert((int)insertPositionStart, startTagPart_2);
// editableContent.insert((int)insertPositionStart,
// currAnnot.getId().toString());
// editableContent.insert((int)insertPositionStart, startTagPart_1);
// } // if
// } // for
//
// FileWriter writer = new FileWriter(file);
// writer.write(editableContent.toString());
// writer.close();
// } // if - should generate
// else if (originalContent != null) {
// Out.prln("OrigContent existing. Generate file...");
//
// Iterator it = peopleAndPlaces.iterator();
// Annotation currAnnot;
// SortedAnnotationList sortedAnnotations = new SortedAnnotationList();
//
// while(it.hasNext()) {
// currAnnot = (Annotation) it.next();
// sortedAnnotations.addSortedExclusive(currAnnot);
// } // while
//
// StringBuffer editableContent = new StringBuffer(originalContent);
// long insertPositionEnd;
// long insertPositionStart;
// // insert anotation tags backward
// Out.prln("Unsorted annotations count: "+peopleAndPlaces.size());
// Out.prln("Sorted annotations count: "+sortedAnnotations.size());
// for(int i=sortedAnnotations.size()-1; i>=0; --i) {
// currAnnot = (Annotation) sortedAnnotations.get(i);
// insertPositionStart =
// currAnnot.getStartNode().getOffset().longValue();
// insertPositionEnd = currAnnot.getEndNode().getOffset().longValue();
// if(insertPositionEnd != -1 && insertPositionStart != -1) {
// editableContent.insert((int)insertPositionEnd, endTag);
// editableContent.insert((int)insertPositionStart, startTagPart_3);
// editableContent.insert((int)insertPositionStart,
// currAnnot.getType());
// editableContent.insert((int)insertPositionStart, startTagPart_2);
// editableContent.insert((int)insertPositionStart,
// currAnnot.getId().toString());
// editableContent.insert((int)insertPositionStart, startTagPart_1);
// } // if
// } // for
//
// FileWriter writer = new FileWriter(file);
// writer.write(editableContent.toString());
// writer.close();
// }
// else {
// Out.prln("Content : "+originalContent);
// Out.prln("Repositioning: "+info);
// }
//
// String xmlDocument = doc.toXml(peopleAndPlaces, false);
// String fileName = new String("StANNIE_toXML_" + count + ".HTML");
// FileWriter writer = new FileWriter(fileName);
// writer.write(xmlDocument);
// writer.close();
//
// } // for each doc
// } // main
//
// /**
// *
// */
// public static class SortedAnnotationList extends Vector {
// public SortedAnnotationList() {
// super();
// } // SortedAnnotationList
//
// public boolean addSortedExclusive(Annotation annot) {
// Annotation currAnot = null;
//
// // overlapping check
// for (int i=0; i<size(); ++i) {
// currAnot = (Annotation) get(i);
// if(annot.overlaps(currAnot)) {
// return false;
// } // if
// } // for
//
// long annotStart = annot.getStartNode().getOffset().longValue();
// long currStart;
// // insert
// for (int i=0; i < size(); ++i) {
// currAnot = (Annotation) get(i);
// currStart = currAnot.getStartNode().getOffset().longValue();
// if(annotStart < currStart) {
// insertElementAt(annot, i);
// /*
// Out.prln("Insert start: "+annotStart+" at position: "+i+" size="+size());
// Out.prln("Current start: "+currStart);
// */
// return true;
// } // if
// } // for
//
// int size = size();
// insertElementAt(annot, size);
////Out.prln("Insert start: "+annotStart+" at size position: "+size);
// return true;
// } // addSorted
// } // SortedAnnotationList
// } // class StandAloneAnnie
| ukwa/webarchive-discovery | warc-nlp/src/main/java/uk/bl/wa/nlp/analysers/GateTextAnalyser.java | 3,841 | // insertPositionEnd = currAnnot.getEndNode().getOffset().longValue(); | line_comment | nl | package uk.bl.wa.nlp.analysers;
///**
// * A nice idea, but seems to rely of many local resources from the local filesystem, which is awkward.
//
// i.e. the following is not enough:
//
// <dependency>
// <groupId>uk.ac.gate</groupId>
// <artifactId>gate-core</artifactId>
// <version>7.1</version>
// </dependency>
//
//
//
// if (conf.hasPath("warc.index.extract.content.text_gate") &&
// conf.getBoolean("warc.index.extract.content.text_gate")) {
// analysers.add(new GateTextAnalyser(conf)); }
//
//
//
// */
//package uk.bl.wa.analyser.text;
/*
* #%L
* warc-indexer
* %%
* Copyright (C) 2013 - 2020 The webarchive-discovery project contributors
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
//
//
//
///*
// * StandAloneAnnie.java
// *
// *
// * Copyright (c) 2000-2001, The University of Sheffield.
// *
// * This file is part of GATE (see http://gate.ac.uk/), and is free
// * software, licenced under the GNU Library General Public License,
// * Version 2, June1991.
// *
// * A copy of this licence is included in the distribution in the file
// * licence.html, and is also available at http://gate.ac.uk/gate/licence.html.
// *
// * hamish, 29/1/2002
// *
// * $Id: StandAloneAnnie.java,v 1.6 2006/01/09 16:43:22 ian Exp $
// */
//
//import gate.Annotation;
//import gate.AnnotationSet;
//import gate.Corpus;
//import gate.CorpusController;
//import gate.Document;
//import gate.Factory;
//import gate.FeatureMap;
//import gate.Gate;
//import gate.GateConstants;
//import gate.corpora.RepositioningInfo;
//import gate.util.GateException;
//import gate.util.Out;
//import gate.util.persistence.PersistenceManager;
//
//import java.io.File;
//import java.io.FileWriter;
//import java.io.IOException;
//import java.net.URL;
//import java.util.HashSet;
//import java.util.Iterator;
//import java.util.Set;
//import java.util.Vector;
//
///**
// * This class illustrates how to use ANNIE as a sausage machine
// * in another application - put ingredients in one end (URLs pointing
// * to documents) and get sausages (e.g. Named Entities) out the
// * other end.
// * <P><B>NOTE:</B><BR>
// * For simplicity's sake, we don't do any exception handling.
// */
//public class GateTextAnalyser {
//
// /** The Corpus Pipeline application to contain ANNIE */
// private CorpusController annieController;
//
// /**
// * Initialise the ANNIE system. This creates a "corpus pipeline"
// * application that can be used to run sets of documents through
// * the extraction system.
// */
// public void initAnnie() throws GateException, IOException {
// Out.prln("Initialising ANNIE...");
//
// // load the ANNIE application from the saved state in plugins/ANNIE
// File pluginsHome = Gate.getPluginsHome();
// File anniePlugin = new File(pluginsHome, "ANNIE");
// File annieGapp = new File(anniePlugin, "ANNIE_with_defaults.gapp");
// annieController =
// (CorpusController) PersistenceManager.loadObjectFromFile(annieGapp);
//
// Out.prln("...ANNIE loaded");
// } // initAnnie()
//
// /** Tell ANNIE's controller about the corpus you want to run on */
// public void setCorpus(Corpus corpus) {
// annieController.setCorpus(corpus);
// } // setCorpus
//
// /** Run ANNIE */
// public void execute() throws GateException {
// Out.prln("Running ANNIE...");
// annieController.execute();
// Out.prln("...ANNIE complete");
// } // execute()
//
// /**
// * Run from the command-line, with a list of URLs as argument.
// * <P><B>NOTE:</B><BR>
// * This code will run with all the documents in memory - if you
// * want to unload each from memory after use, add code to store
// * the corpus in a DataStore.
// */
// public static void main(String args[]) throws GateException, IOException {
// // initialise the GATE library
// Out.prln("Initialising GATE...");
// Gate.init();
// Out.prln("...GATE initialised");
//
// // initialise ANNIE (this may take several minutes)
// GateTextAnalyser annie = new GateTextAnalyser();
// annie.initAnnie();
//
// // create a GATE corpus and add a document for each command-line
// // argument
// Corpus corpus = Factory.newCorpus("StandAloneAnnie corpus");
// for(int i = 0; i < args.length; i++) {
// URL u = new URL(args[i]);
// FeatureMap params = Factory.newFeatureMap();
// params.put("sourceUrl", u);
// params.put("preserveOriginalContent", new Boolean(true));
// params.put("collectRepositioningInfo", new Boolean(true));
// Out.prln("Creating doc for " + u);
// Document doc = (Document)
// Factory.createResource("gate.corpora.DocumentImpl", params);
// corpus.add(doc);
// } // for each of args
//
// // tell the pipeline about the corpus and run it
// annie.setCorpus(corpus);
// annie.execute();
//
// // for each document, get an XML document with the
// // person and location names added
// Iterator iter = corpus.iterator();
// int count = 0;
// String startTagPart_1 = "<span GateID=\"";
// String startTagPart_2 = "\" title=\"";
// String startTagPart_3 = "\" style=\"background:Red;\">";
// String endTag = "</span>";
//
// while(iter.hasNext()) {
// Document doc = (Document) iter.next();
// AnnotationSet defaultAnnotSet = doc.getAnnotations();
// Set annotTypesRequired = new HashSet();
// annotTypesRequired.add("Person");
// annotTypesRequired.add("Location");
// Set<Annotation> peopleAndPlaces =
// new HashSet<Annotation>(defaultAnnotSet.get(annotTypesRequired));
//
// FeatureMap features = doc.getFeatures();
// String originalContent = (String)
// features.get(GateConstants.ORIGINAL_DOCUMENT_CONTENT_FEATURE_NAME);
// RepositioningInfo info = (RepositioningInfo)
// features.get(GateConstants.DOCUMENT_REPOSITIONING_INFO_FEATURE_NAME);
//
// ++count;
// File file = new File("StANNIE_" + count + ".HTML");
// Out.prln("File name: '"+file.getAbsolutePath()+"'");
// if(originalContent != null && info != null) {
// Out.prln("OrigContent and reposInfo existing. Generate file...");
//
// Iterator it = peopleAndPlaces.iterator();
// Annotation currAnnot;
// SortedAnnotationList sortedAnnotations = new SortedAnnotationList();
//
// while(it.hasNext()) {
// currAnnot = (Annotation) it.next();
// sortedAnnotations.addSortedExclusive(currAnnot);
// } // while
//
// StringBuffer editableContent = new StringBuffer(originalContent);
// long insertPositionEnd;
// long insertPositionStart;
// // insert anotation tags backward
// Out.prln("Unsorted annotations count: "+peopleAndPlaces.size());
// Out.prln("Sorted annotations count: "+sortedAnnotations.size());
// for(int i=sortedAnnotations.size()-1; i>=0; --i) {
// currAnnot = (Annotation) sortedAnnotations.get(i);
// insertPositionStart =
// currAnnot.getStartNode().getOffset().longValue();
// insertPositionStart = info.getOriginalPos(insertPositionStart);
// insertPositionEnd =<SUF>
// insertPositionEnd = info.getOriginalPos(insertPositionEnd, true);
// if(insertPositionEnd != -1 && insertPositionStart != -1) {
// editableContent.insert((int)insertPositionEnd, endTag);
// editableContent.insert((int)insertPositionStart, startTagPart_3);
// editableContent.insert((int)insertPositionStart,
// currAnnot.getType());
// editableContent.insert((int)insertPositionStart, startTagPart_2);
// editableContent.insert((int)insertPositionStart,
// currAnnot.getId().toString());
// editableContent.insert((int)insertPositionStart, startTagPart_1);
// } // if
// } // for
//
// FileWriter writer = new FileWriter(file);
// writer.write(editableContent.toString());
// writer.close();
// } // if - should generate
// else if (originalContent != null) {
// Out.prln("OrigContent existing. Generate file...");
//
// Iterator it = peopleAndPlaces.iterator();
// Annotation currAnnot;
// SortedAnnotationList sortedAnnotations = new SortedAnnotationList();
//
// while(it.hasNext()) {
// currAnnot = (Annotation) it.next();
// sortedAnnotations.addSortedExclusive(currAnnot);
// } // while
//
// StringBuffer editableContent = new StringBuffer(originalContent);
// long insertPositionEnd;
// long insertPositionStart;
// // insert anotation tags backward
// Out.prln("Unsorted annotations count: "+peopleAndPlaces.size());
// Out.prln("Sorted annotations count: "+sortedAnnotations.size());
// for(int i=sortedAnnotations.size()-1; i>=0; --i) {
// currAnnot = (Annotation) sortedAnnotations.get(i);
// insertPositionStart =
// currAnnot.getStartNode().getOffset().longValue();
// insertPositionEnd = currAnnot.getEndNode().getOffset().longValue();
// if(insertPositionEnd != -1 && insertPositionStart != -1) {
// editableContent.insert((int)insertPositionEnd, endTag);
// editableContent.insert((int)insertPositionStart, startTagPart_3);
// editableContent.insert((int)insertPositionStart,
// currAnnot.getType());
// editableContent.insert((int)insertPositionStart, startTagPart_2);
// editableContent.insert((int)insertPositionStart,
// currAnnot.getId().toString());
// editableContent.insert((int)insertPositionStart, startTagPart_1);
// } // if
// } // for
//
// FileWriter writer = new FileWriter(file);
// writer.write(editableContent.toString());
// writer.close();
// }
// else {
// Out.prln("Content : "+originalContent);
// Out.prln("Repositioning: "+info);
// }
//
// String xmlDocument = doc.toXml(peopleAndPlaces, false);
// String fileName = new String("StANNIE_toXML_" + count + ".HTML");
// FileWriter writer = new FileWriter(fileName);
// writer.write(xmlDocument);
// writer.close();
//
// } // for each doc
// } // main
//
// /**
// *
// */
// public static class SortedAnnotationList extends Vector {
// public SortedAnnotationList() {
// super();
// } // SortedAnnotationList
//
// public boolean addSortedExclusive(Annotation annot) {
// Annotation currAnot = null;
//
// // overlapping check
// for (int i=0; i<size(); ++i) {
// currAnot = (Annotation) get(i);
// if(annot.overlaps(currAnot)) {
// return false;
// } // if
// } // for
//
// long annotStart = annot.getStartNode().getOffset().longValue();
// long currStart;
// // insert
// for (int i=0; i < size(); ++i) {
// currAnot = (Annotation) get(i);
// currStart = currAnot.getStartNode().getOffset().longValue();
// if(annotStart < currStart) {
// insertElementAt(annot, i);
// /*
// Out.prln("Insert start: "+annotStart+" at position: "+i+" size="+size());
// Out.prln("Current start: "+currStart);
// */
// return true;
// } // if
// } // for
//
// int size = size();
// insertElementAt(annot, size);
////Out.prln("Insert start: "+annotStart+" at size position: "+size);
// return true;
// } // addSorted
// } // SortedAnnotationList
// } // class StandAloneAnnie
|
72526_17 | package weka.classifiers.trees;
import static com.metsci.glimpse.util.logging.LoggerUtils.logWarning;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Logger;
import weka.classifiers.Classifier;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.NoSupportForMissingValuesException;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import edu.gmu.vfml.tree.Node;
/**
* <!-- globalinfo-start -->
* will be automatically replaced
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start -->
* will be automatically replaced
* <!-- technical-bibtex-end -->
*
* <!-- options-start -->
* will be automatically replaced
* <!-- options-end -->
*
* @see weka.classifiers.trees.Id3
* @author ulman
*/
public class VFDT extends Classifier implements TechnicalInformationHandler, OptionHandler
{
private static final Logger logger = Logger.getLogger( VFDT.class.getName( ) );
private static final long serialVersionUID = 1L;
/** Root node of classification tree. */
protected Node root;
protected Attribute classAttribute;
protected int numClasses;
// if the hoeffding bound drops below tie confidence, assume the best two attributes
// are very similar (and thus might require an extremely large number of instances
// to separate with high confidence), so just choose the current best
protected double tieConfidence = 0.05;
// 1-delta is the probability of choosing the correct attribute at any given node
protected double delta = 1e-4;
// nodes are only rechecked for potential splits every nmin data instances
protected int nMin = 30;
transient protected double R_squared; // log2( numClasses )^2
transient protected double ln_inv_delta; // ln( 1 / delta )
/**
* Returns the tip text for this property.
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String nMinTipText( )
{
return "Nodes are only rechecked for splits every multiple of this many data instances.";
}
/**
* Nodes are only checked for splits when the reach multiple of nMin instances.
*/
public int getNMin( )
{
return nMin;
}
/**
* @see #getNMin()
*/
public void setNMin( int nmin )
{
this.nMin = nmin;
}
/**
* Returns the tip text for this property.
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String confidenceLevelTipText( )
{
return "One minus the probability that each attribute split in " + "the VFDT tree will be the same as a batch generated tree.";
}
/**
* See equation (1) in "Mining High-Speed Data Streams." The Hoeffding Bound provides
* a bound on the true mean of a random variable given n independent
* observations of the random variable, with probability 1 - delta
* (where delta is the confidence level returned by this method).
*
* @return the Hoeffding Bound confidence level
*/
public double getConfidenceLevel( )
{
return delta;
}
/**
* @see #getConfidenceLevel( )
* @param delta
*/
public void setConfidenceLevel( double delta )
{
this.delta = delta;
}
/**
* Returns the tip text for this property.
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String tieConfidenceTipText( )
{
return "If the Hoeffding bound falls below this value, the node will " + "be automatically split on the current best attribute. This" + "prevents nodes with two very similar attributes from taking " + "excessiely many instances to split with high confidence.";
}
/**
* If two attributes have very similar information gain, then
* it may take many instances to choose between them with
* high confidence. Tie confidence sets an alternative threshold
* which causes a split decision to be automatically made if the
* Hoeffding bound drops below the tie confidence.
*
* @return
*/
public double getTieConfidence( )
{
return this.tieConfidence;
}
/**
* #see {@link #getConfidenceLevel()}
* @param tieConfidence
*/
public void setTieConfidence( double tieConfidence )
{
this.tieConfidence = tieConfidence;
}
/**
* Lists the command line options available to this classifier.
*/
@Override
@SuppressWarnings( { "rawtypes" } )
public Enumeration listOptions( )
{
return listOptionsVector( ).elements( );
}
/**
* @see #listOptions()
*/
@SuppressWarnings( { "rawtypes", "unchecked" } )
public Vector listOptionsVector( )
{
Vector newVector = new Vector( );
newVector.addElement( new Option( "\tTie Confidence.", "T", 1, "-T <tie confidence>" ) );
newVector.addElement( new Option( "\tHoeffding Confidence.\n", "H", 1, "-H <hoeffding confidence>" ) );
newVector.addElement( new Option( "\tN Minimum.\n", "N", 1, "-N <nmin>" ) );
return newVector;
}
/**
* Parses a given list of options.
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions( String[] options ) throws Exception
{
String tieConfidenceString = Utils.getOption( 'T', options );
if ( !tieConfidenceString.isEmpty( ) )
{
tieConfidence = Double.parseDouble( tieConfidenceString );
}
String hoeffdingConfidenceString = Utils.getOption( 'H', options );
if ( !hoeffdingConfidenceString.isEmpty( ) )
{
delta = Double.parseDouble( hoeffdingConfidenceString );
}
String nMinString = Utils.getOption( 'N', options );
if ( !nMinString.isEmpty( ) )
{
nMin = Integer.parseInt( nMinString );
}
}
/**
* Gets the current settings of the Classifier.
*
* @see #getOptions()
* @return an array of strings suitable for passing to setOptions
*/
public List<String> getOptionsList( )
{
List<String> options = new LinkedList<String>( );
options.add( "-H" );
options.add( String.valueOf( delta ) );
options.add( "-T" );
options.add( String.valueOf( tieConfidence ) );
options.add( "-N" );
options.add( String.valueOf( nMin ) );
return options;
}
/**
* Gets the current settings of the Classifier.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions( )
{
return getOptionsList( ).toArray( new String[0] );
}
/**
* Returns a string describing the classifier.
* @return a description suitable for the GUI.
*/
public String globalInfo( )
{
//@formatter:off
return "Class for constructing an unpruned decision tree based on the VFDT " +
"algorithm. For more information see: \n\n" +
getTechnicalInformation( ).toString( );
//@formatter:on
}
/**
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
@Override
public TechnicalInformation getTechnicalInformation( )
{
TechnicalInformation info = new TechnicalInformation( Type.ARTICLE );
info.setValue( Field.AUTHOR, "Domingos, Pedro" );
info.setValue( Field.YEAR, "2000" );
info.setValue( Field.TITLE, "Mining high-speed data streams" );
info.setValue( Field.JOURNAL, "Proceedings of the sixth ACM SIGKDD international conference on Knowledge discovery and data mining" );
info.setValue( Field.SERIES, "KDD '00" );
info.setValue( Field.ISBN, "1-58113-233-6" );
info.setValue( Field.LOCATION, "Boston, Massachusetts, USA" );
info.setValue( Field.PAGES, "71-80" );
info.setValue( Field.URL, "http://doi.acm.org/10.1145/347090.347107" );
info.setValue( Field.PUBLISHER, "ACM" );
return info;
}
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
@Override
public Capabilities getCapabilities( )
{
Capabilities result = super.getCapabilities( );
result.disableAll( );
// attributes
result.enable( Capability.NOMINAL_ATTRIBUTES );
// class
result.enable( Capability.NOMINAL_CLASS );
result.enable( Capability.MISSING_CLASS_VALUES );
// instances
result.setMinimumNumberInstances( 0 );
return result;
}
public Node getRoot( )
{
return root;
}
/**
* Classifies a given test instance using the decision tree.
*
* @param instance the instance to be classified
* @return the classification
* @throws NoSupportForMissingValuesException if instance has missing values
* @see weka.classifiers.trees.Id3#classifyInstance(Instance)
*/
@Override
public double classifyInstance( Instance instance ) throws NoSupportForMissingValuesException
{
if ( instance.hasMissingValue( ) )
{
throw new NoSupportForMissingValuesException( "VFDT: missing values not supported." );
}
// get the class value for the leaf node corresponding to the provided instance
return root.getLeafNode( instance ).getClassValue( );
}
/**
* Builds VDFT decision tree classifier.
*
* @param data the training data
* @exception Exception if classifier can't be built successfully
*/
@Override
public void buildClassifier( Instances data ) throws Exception
{
// Initialize the classifier. As per the Weka classifier contract,
// this method takes care of completely resetting the classifier
// from any previous runs.
initialize( data );
// build the Hoeffding tree
makeTree( data );
}
/**
* Perform classifier initialization steps.
*/
public void initialize( Instances data ) throws Exception
{
// can classifier handle the data?
getCapabilities( ).testWithFail( data );
// remove instances with missing class
data = new Instances( data );
data.deleteWithMissingClass( );
// store the class attribute for the data set
classAttribute = data.classAttribute( );
// record number of class values, attributes, and values for each attribute
numClasses = data.classAttribute( ).numValues( );
R_squared = Math.pow( Utils.log2( numClasses ), 2 );
ln_inv_delta = Math.log( 1 / delta );
// create root node
root = newNode( data );
}
public void addInstance( Instance instance )
{
try
{
// traverse the classification tree to find the leaf node for this instance
Node node = root.getLeafNode( instance );
// update the counts associated with this instance
node.incrementCounts( instance );
// check whether or not to split the node on an attribute
if ( node.getCount( ) % nMin == 0 )
{
checkNodeSplit( instance, node );
}
}
catch ( Exception e )
{
logWarning( logger, "Trouble processing instance.", e );
}
}
protected Node newNode( Instances instances )
{
return new Node( instances, classAttribute );
}
/**
* Method for building a VFDT tree.
*
* @param data the training data
* @exception Exception if decision tree can't be built successfully
*/
protected void makeTree( Instances data ) throws Exception
{
makeTree( data.enumerateInstances( ) );
}
@SuppressWarnings( "rawtypes" )
protected void makeTree( Enumeration data )
{
while ( data.hasMoreElements( ) )
{
// retrieve the next data instance
Instance instance = ( Instance ) data.nextElement( );
addInstance( instance );
}
}
protected void checkNodeSplit( Instance instance, Node node )
{
// compute the node entropy with no split
double nullValue = computeEntropy( node );
// determine based on Hoeffding Bound whether to split node
int firstIndex = 0;
double firstValue = Double.MAX_VALUE;
double secondValue = Double.MAX_VALUE;
// loop through all the attributes, calculating information gains
// and keeping the attributes with the two highest information gains
for ( int attrIndex = 0; attrIndex < instance.numAttributes( ); attrIndex++ )
{
// don't consider the class attribute
if ( attrIndex == classAttribute.index( ) ) continue;
Attribute attribute = instance.attribute( attrIndex );
double value = computeEntropySum( node, attribute );
if ( value < firstValue )
{
secondValue = firstValue;
firstValue = value;
firstIndex = attrIndex;
}
else if ( value < secondValue )
{
secondValue = value;
}
}
// if the difference between the information gain of the two best attributes
// has exceeded the Hoeffding bound (which will continually shrink as more
// attributes are added to the node) then split on the best attribute
double hoeffdingBound = calculateHoeffdingBound( node );
// split if there is a large enough entropy difference between the first/second place attributes
boolean confident = secondValue - firstValue > hoeffdingBound;
// or if the first/second attributes are so close that the hoeffding bound has decreased below
// the tie threshold (in this case it really doesn't matter which attribute is chosen
boolean tie = tieConfidence > hoeffdingBound;
// don't split if even the best split would increase overall entropy
boolean preprune = nullValue <= firstValue;
// see: vfdt-engine.c:871
if ( ( tie || confident ) && !preprune )
{
Attribute attribute = instance.attribute( firstIndex );
splitNode( node, attribute, instance );
}
}
protected void splitNode( Node node, Attribute attribute, Instance instance )
{
node.split( attribute, instance );
}
/**
* Computes information gain for an attribute.
*
* @param data the data for which info gain is to be computed
* @param att the attribute
* @return the information gain for the given attribute and data
* @throws Exception if computation fails
* @see weka.classifiers.trees.Id3#computeInfoGain( Instances, Attribute )
*/
protected double computeInfoGain( Node node, Attribute attr )
{
return computeEntropy( node ) - computeEntropySum( node, attr );
}
protected double computeEntropySum( Node node, Attribute attr )
{
double sum = 0.0;
for ( int valueIndex = 0; valueIndex < attr.numValues( ); valueIndex++ )
{
int count = node.getCount( attr, valueIndex );
if ( count > 0 )
{
double entropy = computeEntropy( node, attr, valueIndex );
double ratio = ( ( double ) count / ( double ) node.getCount( ) );
sum += ratio * entropy;
}
}
return sum;
}
/**
* Computes the entropy of a dataset.
*
* @param node the tree node for which entropy is to be computed
* @return the entropy of the node's class distribution
* @throws Exception if computation fails
* @see weka.classifiers.trees.Id3#computeEntropy( Instances )
*/
protected double computeEntropy( Node node )
{
double entropy = 0;
double totalCount = ( double ) node.getCount( );
for ( int classIndex = 0; classIndex < numClasses; classIndex++ )
{
int count = node.getCount( classIndex );
if ( count > 0 )
{
double p = count / totalCount;
entropy -= p * Utils.log2( p );
}
}
return entropy;
}
/**
* Computes the entropy of the child node created by splitting on the
* provided attribute and value.
*
* @param node the tree node for which entropy is to be computed
* @param attribute the attribute to split on before calculating entropy
* @param valueIndex calculate entropy for the child node corresponding
* to this nominal attribute value index
* @return calculated entropy
* @throws Exception if computation fails
*/
protected double computeEntropy( Node node, Attribute attribute, int valueIndex )
{
double entropy = 0;
double totalCount = ( double ) node.getCount( attribute, valueIndex );
for ( int classIndex = 0; classIndex < numClasses; classIndex++ )
{
int count = node.getCount( attribute, valueIndex, classIndex );
if ( count > 0 )
{
double p = count / totalCount;
entropy -= p * Utils.log2( p );
}
}
return entropy;
}
/**
* Calculates the difference in information gain, epsilon, between the
* attribute with the best and second best information gain necessary to
* make a splitting decision based on the current set of observed attributes.
* As more attributes are gathered, the required difference will decrease.
*
* @param node
* @return
*/
// see: vfdt-engine.c:833
protected double calculateHoeffdingBound( Node node )
{
int n = node.getCount( );
double epsilon = Math.sqrt( ( R_squared * ln_inv_delta ) / ( 2 * n ) );
return epsilon;
}
/**
* Prints the decision tree using the private toString method from below.
*
* @return a textual description of the classifier
*/
public String toString( )
{
if ( root == null )
{
return "VFDT: No model built yet.";
}
return "VFDT\n\n" + root.toString( );
}
}
| ulmangt/vfml | weka/src/main/java/weka/classifiers/trees/VFDT.java | 5,056 | /**
* #see {@link #getConfidenceLevel()}
* @param tieConfidence
*/ | block_comment | nl | package weka.classifiers.trees;
import static com.metsci.glimpse.util.logging.LoggerUtils.logWarning;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import java.util.logging.Logger;
import weka.classifiers.Classifier;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.NoSupportForMissingValuesException;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import edu.gmu.vfml.tree.Node;
/**
* <!-- globalinfo-start -->
* will be automatically replaced
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start -->
* will be automatically replaced
* <!-- technical-bibtex-end -->
*
* <!-- options-start -->
* will be automatically replaced
* <!-- options-end -->
*
* @see weka.classifiers.trees.Id3
* @author ulman
*/
public class VFDT extends Classifier implements TechnicalInformationHandler, OptionHandler
{
private static final Logger logger = Logger.getLogger( VFDT.class.getName( ) );
private static final long serialVersionUID = 1L;
/** Root node of classification tree. */
protected Node root;
protected Attribute classAttribute;
protected int numClasses;
// if the hoeffding bound drops below tie confidence, assume the best two attributes
// are very similar (and thus might require an extremely large number of instances
// to separate with high confidence), so just choose the current best
protected double tieConfidence = 0.05;
// 1-delta is the probability of choosing the correct attribute at any given node
protected double delta = 1e-4;
// nodes are only rechecked for potential splits every nmin data instances
protected int nMin = 30;
transient protected double R_squared; // log2( numClasses )^2
transient protected double ln_inv_delta; // ln( 1 / delta )
/**
* Returns the tip text for this property.
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String nMinTipText( )
{
return "Nodes are only rechecked for splits every multiple of this many data instances.";
}
/**
* Nodes are only checked for splits when the reach multiple of nMin instances.
*/
public int getNMin( )
{
return nMin;
}
/**
* @see #getNMin()
*/
public void setNMin( int nmin )
{
this.nMin = nmin;
}
/**
* Returns the tip text for this property.
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String confidenceLevelTipText( )
{
return "One minus the probability that each attribute split in " + "the VFDT tree will be the same as a batch generated tree.";
}
/**
* See equation (1) in "Mining High-Speed Data Streams." The Hoeffding Bound provides
* a bound on the true mean of a random variable given n independent
* observations of the random variable, with probability 1 - delta
* (where delta is the confidence level returned by this method).
*
* @return the Hoeffding Bound confidence level
*/
public double getConfidenceLevel( )
{
return delta;
}
/**
* @see #getConfidenceLevel( )
* @param delta
*/
public void setConfidenceLevel( double delta )
{
this.delta = delta;
}
/**
* Returns the tip text for this property.
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String tieConfidenceTipText( )
{
return "If the Hoeffding bound falls below this value, the node will " + "be automatically split on the current best attribute. This" + "prevents nodes with two very similar attributes from taking " + "excessiely many instances to split with high confidence.";
}
/**
* If two attributes have very similar information gain, then
* it may take many instances to choose between them with
* high confidence. Tie confidence sets an alternative threshold
* which causes a split decision to be automatically made if the
* Hoeffding bound drops below the tie confidence.
*
* @return
*/
public double getTieConfidence( )
{
return this.tieConfidence;
}
/**
* #see {@link #getConfidenceLevel()}<SUF>*/
public void setTieConfidence( double tieConfidence )
{
this.tieConfidence = tieConfidence;
}
/**
* Lists the command line options available to this classifier.
*/
@Override
@SuppressWarnings( { "rawtypes" } )
public Enumeration listOptions( )
{
return listOptionsVector( ).elements( );
}
/**
* @see #listOptions()
*/
@SuppressWarnings( { "rawtypes", "unchecked" } )
public Vector listOptionsVector( )
{
Vector newVector = new Vector( );
newVector.addElement( new Option( "\tTie Confidence.", "T", 1, "-T <tie confidence>" ) );
newVector.addElement( new Option( "\tHoeffding Confidence.\n", "H", 1, "-H <hoeffding confidence>" ) );
newVector.addElement( new Option( "\tN Minimum.\n", "N", 1, "-N <nmin>" ) );
return newVector;
}
/**
* Parses a given list of options.
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
@Override
public void setOptions( String[] options ) throws Exception
{
String tieConfidenceString = Utils.getOption( 'T', options );
if ( !tieConfidenceString.isEmpty( ) )
{
tieConfidence = Double.parseDouble( tieConfidenceString );
}
String hoeffdingConfidenceString = Utils.getOption( 'H', options );
if ( !hoeffdingConfidenceString.isEmpty( ) )
{
delta = Double.parseDouble( hoeffdingConfidenceString );
}
String nMinString = Utils.getOption( 'N', options );
if ( !nMinString.isEmpty( ) )
{
nMin = Integer.parseInt( nMinString );
}
}
/**
* Gets the current settings of the Classifier.
*
* @see #getOptions()
* @return an array of strings suitable for passing to setOptions
*/
public List<String> getOptionsList( )
{
List<String> options = new LinkedList<String>( );
options.add( "-H" );
options.add( String.valueOf( delta ) );
options.add( "-T" );
options.add( String.valueOf( tieConfidence ) );
options.add( "-N" );
options.add( String.valueOf( nMin ) );
return options;
}
/**
* Gets the current settings of the Classifier.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions( )
{
return getOptionsList( ).toArray( new String[0] );
}
/**
* Returns a string describing the classifier.
* @return a description suitable for the GUI.
*/
public String globalInfo( )
{
//@formatter:off
return "Class for constructing an unpruned decision tree based on the VFDT " +
"algorithm. For more information see: \n\n" +
getTechnicalInformation( ).toString( );
//@formatter:on
}
/**
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
@Override
public TechnicalInformation getTechnicalInformation( )
{
TechnicalInformation info = new TechnicalInformation( Type.ARTICLE );
info.setValue( Field.AUTHOR, "Domingos, Pedro" );
info.setValue( Field.YEAR, "2000" );
info.setValue( Field.TITLE, "Mining high-speed data streams" );
info.setValue( Field.JOURNAL, "Proceedings of the sixth ACM SIGKDD international conference on Knowledge discovery and data mining" );
info.setValue( Field.SERIES, "KDD '00" );
info.setValue( Field.ISBN, "1-58113-233-6" );
info.setValue( Field.LOCATION, "Boston, Massachusetts, USA" );
info.setValue( Field.PAGES, "71-80" );
info.setValue( Field.URL, "http://doi.acm.org/10.1145/347090.347107" );
info.setValue( Field.PUBLISHER, "ACM" );
return info;
}
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
@Override
public Capabilities getCapabilities( )
{
Capabilities result = super.getCapabilities( );
result.disableAll( );
// attributes
result.enable( Capability.NOMINAL_ATTRIBUTES );
// class
result.enable( Capability.NOMINAL_CLASS );
result.enable( Capability.MISSING_CLASS_VALUES );
// instances
result.setMinimumNumberInstances( 0 );
return result;
}
public Node getRoot( )
{
return root;
}
/**
* Classifies a given test instance using the decision tree.
*
* @param instance the instance to be classified
* @return the classification
* @throws NoSupportForMissingValuesException if instance has missing values
* @see weka.classifiers.trees.Id3#classifyInstance(Instance)
*/
@Override
public double classifyInstance( Instance instance ) throws NoSupportForMissingValuesException
{
if ( instance.hasMissingValue( ) )
{
throw new NoSupportForMissingValuesException( "VFDT: missing values not supported." );
}
// get the class value for the leaf node corresponding to the provided instance
return root.getLeafNode( instance ).getClassValue( );
}
/**
* Builds VDFT decision tree classifier.
*
* @param data the training data
* @exception Exception if classifier can't be built successfully
*/
@Override
public void buildClassifier( Instances data ) throws Exception
{
// Initialize the classifier. As per the Weka classifier contract,
// this method takes care of completely resetting the classifier
// from any previous runs.
initialize( data );
// build the Hoeffding tree
makeTree( data );
}
/**
* Perform classifier initialization steps.
*/
public void initialize( Instances data ) throws Exception
{
// can classifier handle the data?
getCapabilities( ).testWithFail( data );
// remove instances with missing class
data = new Instances( data );
data.deleteWithMissingClass( );
// store the class attribute for the data set
classAttribute = data.classAttribute( );
// record number of class values, attributes, and values for each attribute
numClasses = data.classAttribute( ).numValues( );
R_squared = Math.pow( Utils.log2( numClasses ), 2 );
ln_inv_delta = Math.log( 1 / delta );
// create root node
root = newNode( data );
}
public void addInstance( Instance instance )
{
try
{
// traverse the classification tree to find the leaf node for this instance
Node node = root.getLeafNode( instance );
// update the counts associated with this instance
node.incrementCounts( instance );
// check whether or not to split the node on an attribute
if ( node.getCount( ) % nMin == 0 )
{
checkNodeSplit( instance, node );
}
}
catch ( Exception e )
{
logWarning( logger, "Trouble processing instance.", e );
}
}
protected Node newNode( Instances instances )
{
return new Node( instances, classAttribute );
}
/**
* Method for building a VFDT tree.
*
* @param data the training data
* @exception Exception if decision tree can't be built successfully
*/
protected void makeTree( Instances data ) throws Exception
{
makeTree( data.enumerateInstances( ) );
}
@SuppressWarnings( "rawtypes" )
protected void makeTree( Enumeration data )
{
while ( data.hasMoreElements( ) )
{
// retrieve the next data instance
Instance instance = ( Instance ) data.nextElement( );
addInstance( instance );
}
}
protected void checkNodeSplit( Instance instance, Node node )
{
// compute the node entropy with no split
double nullValue = computeEntropy( node );
// determine based on Hoeffding Bound whether to split node
int firstIndex = 0;
double firstValue = Double.MAX_VALUE;
double secondValue = Double.MAX_VALUE;
// loop through all the attributes, calculating information gains
// and keeping the attributes with the two highest information gains
for ( int attrIndex = 0; attrIndex < instance.numAttributes( ); attrIndex++ )
{
// don't consider the class attribute
if ( attrIndex == classAttribute.index( ) ) continue;
Attribute attribute = instance.attribute( attrIndex );
double value = computeEntropySum( node, attribute );
if ( value < firstValue )
{
secondValue = firstValue;
firstValue = value;
firstIndex = attrIndex;
}
else if ( value < secondValue )
{
secondValue = value;
}
}
// if the difference between the information gain of the two best attributes
// has exceeded the Hoeffding bound (which will continually shrink as more
// attributes are added to the node) then split on the best attribute
double hoeffdingBound = calculateHoeffdingBound( node );
// split if there is a large enough entropy difference between the first/second place attributes
boolean confident = secondValue - firstValue > hoeffdingBound;
// or if the first/second attributes are so close that the hoeffding bound has decreased below
// the tie threshold (in this case it really doesn't matter which attribute is chosen
boolean tie = tieConfidence > hoeffdingBound;
// don't split if even the best split would increase overall entropy
boolean preprune = nullValue <= firstValue;
// see: vfdt-engine.c:871
if ( ( tie || confident ) && !preprune )
{
Attribute attribute = instance.attribute( firstIndex );
splitNode( node, attribute, instance );
}
}
protected void splitNode( Node node, Attribute attribute, Instance instance )
{
node.split( attribute, instance );
}
/**
* Computes information gain for an attribute.
*
* @param data the data for which info gain is to be computed
* @param att the attribute
* @return the information gain for the given attribute and data
* @throws Exception if computation fails
* @see weka.classifiers.trees.Id3#computeInfoGain( Instances, Attribute )
*/
protected double computeInfoGain( Node node, Attribute attr )
{
return computeEntropy( node ) - computeEntropySum( node, attr );
}
protected double computeEntropySum( Node node, Attribute attr )
{
double sum = 0.0;
for ( int valueIndex = 0; valueIndex < attr.numValues( ); valueIndex++ )
{
int count = node.getCount( attr, valueIndex );
if ( count > 0 )
{
double entropy = computeEntropy( node, attr, valueIndex );
double ratio = ( ( double ) count / ( double ) node.getCount( ) );
sum += ratio * entropy;
}
}
return sum;
}
/**
* Computes the entropy of a dataset.
*
* @param node the tree node for which entropy is to be computed
* @return the entropy of the node's class distribution
* @throws Exception if computation fails
* @see weka.classifiers.trees.Id3#computeEntropy( Instances )
*/
protected double computeEntropy( Node node )
{
double entropy = 0;
double totalCount = ( double ) node.getCount( );
for ( int classIndex = 0; classIndex < numClasses; classIndex++ )
{
int count = node.getCount( classIndex );
if ( count > 0 )
{
double p = count / totalCount;
entropy -= p * Utils.log2( p );
}
}
return entropy;
}
/**
* Computes the entropy of the child node created by splitting on the
* provided attribute and value.
*
* @param node the tree node for which entropy is to be computed
* @param attribute the attribute to split on before calculating entropy
* @param valueIndex calculate entropy for the child node corresponding
* to this nominal attribute value index
* @return calculated entropy
* @throws Exception if computation fails
*/
protected double computeEntropy( Node node, Attribute attribute, int valueIndex )
{
double entropy = 0;
double totalCount = ( double ) node.getCount( attribute, valueIndex );
for ( int classIndex = 0; classIndex < numClasses; classIndex++ )
{
int count = node.getCount( attribute, valueIndex, classIndex );
if ( count > 0 )
{
double p = count / totalCount;
entropy -= p * Utils.log2( p );
}
}
return entropy;
}
/**
* Calculates the difference in information gain, epsilon, between the
* attribute with the best and second best information gain necessary to
* make a splitting decision based on the current set of observed attributes.
* As more attributes are gathered, the required difference will decrease.
*
* @param node
* @return
*/
// see: vfdt-engine.c:833
protected double calculateHoeffdingBound( Node node )
{
int n = node.getCount( );
double epsilon = Math.sqrt( ( R_squared * ln_inv_delta ) / ( 2 * n ) );
return epsilon;
}
/**
* Prints the decision tree using the private toString method from below.
*
* @return a textual description of the classifier
*/
public String toString( )
{
if ( root == null )
{
return "VFDT: No model built yet.";
}
return "VFDT\n\n" + root.toString( );
}
}
|
47116_6 | package ultimate.karoapi4j;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.core.type.TypeReference;
import ultimate.karoapi4j.enums.EnumContentType;
import ultimate.karoapi4j.utils.JSONUtil;
import ultimate.karoapi4j.utils.URLLoader;
import ultimate.karoapi4j.utils.Version;
/**
* This is the wrapper for accessing the Karo Wiki API. It provides the basic functionality such as:
* <ul>
* <li>{@link KaroWikiAPI#login(String, String)}</li>
* <li>{@link KaroWikiAPI#logout()}</li>
* <li>{@link KaroWikiAPI#edit(String, String, String, boolean, boolean)}</li>
* <li>{@link KaroWikiAPI#getContent(String)}</li>
* </ul>
* and other operations, that are necessary for editing
* <ul>
* <li>{@link KaroWikiAPI#query(String, String, String, String...)}</li>
* <li>{@link KaroWikiAPI#queryRevisionProperties(String, String...)}</li>
* <li>{@link KaroWikiAPI#queryInfoProperties(String, String...)}</li>
* <li>{@link KaroWikiAPI#getTimestamp(String)}</li>
* <li>{@link KaroWikiAPI#getToken(String, String)}</li>
* <li>inlcuding automated captcha answering</li>
* </ul>
* Note: the Wiki API itself provides much more operations and informations, but those haven't been implemented here. If you have a feature request,
* visit https://github.com/ultimate/KaroToolsCollection/issues and create an issue :)
* <br>
* Note: Accessing the Wiki API requires a user and password for wiki.karopapier.de. Other than the {@link KaroAPI} this API is cookie based and hence
* does not support multiple instances, since cookies are handled globally during program execution. So once a
* {@link KaroWikiAPI#login(String, String)} is performed the user is set for all subsequent operations. If it is required to perform actions for
* different users, dedicated {@link KaroWikiAPI#logout()} and {@link KaroWikiAPI#login(String, String)} need to be used.
* <br>
* Each API call will return a {@link CompletableFuture} which wraps the underlying API call and which then can be used to either load the results
* either blocking or asynchronously (see {@link URLLoader}).
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @author ultimate
*/
public class KaroWikiAPI
{
/**
* Logger-Instance
*/
protected transient final Logger logger = LogManager.getLogger(KaroWikiAPI.class);
/**
* The config key
*/
public static final String CONFIG_KEY = "karoWIKI";
//////////////
// api URLs //
//////////////
protected static final URLLoader KAROWIKI = new URLLoader("https://wiki.karopapier.de");
protected static final URLLoader API = KAROWIKI.relative("/api.php");
//////////////////////////
// parameters & actions //
//////////////////////////
public static final String PARAMETER_ACTION = "action";
public static final String PARAMETER_FORMAT = "format";
public static final String ACTION_LOGIN = "login";
public static final String PARAMETER_ACTION_LOGIN_USER = "lgname";
public static final String PARAMETER_ACTION_LOGIN_PASSWORD = "lgpassword";
public static final String PARAMETER_ACTION_LOGIN_TOKEN = "lgtoken";
public static final String ACTION_LOGOUT = "logout";
public static final String PARAMETER_ACTION_LOGOUT_TOKEN = "token";
public static final String ACTION_QUERY = "query";
public static final String PARAMETER_ACTION_QUERY_META = "meta";
public static final String PARAMETER_ACTION_QUERY_META_TOKENS = "tokens";
public static final String PARAMETER_ACTION_QUERY_PROP = "prop";
public static final String PARAMETER_ACTION_QUERY_PROP_RV = "revisions";
public static final String PARAMETER_ACTION_QUERY_PROP_IN = "info";
public static final String PARAMETER_ACTION_QUERY_TITLES = "titles";
public static final String PARAMETER_ACTION_QUERY_RVPROP = "rvprop";
public static final String PARAMETER_ACTION_QUERY_INPROP = "inprop";
public static final String PARAMETER_ACTION_QUERY_INTOKEN = "intoken";
public static final String ACTION_PARSE = "parse";
public static final String PARAMETER_ACTION_PARSE_PAGE = "page";
public static final String PARAMETER_ACTION_PARSE_PROP = "prop";
public static final String PARAMETER_ACTION_PARSE_PROP_TEXT = "text";
public static final String PARAMETER_ACTION_PARSE_PROP_WIKI = "wikitext";
public static final String ACTION_EDIT = "edit";
public static final String PARAMETER_ACTION_EDIT_TITLE = "title";
public static final String PARAMETER_ACTION_EDIT_TEXT = "text";
public static final String PARAMETER_ACTION_EDIT_TOKEN = "token";
public static final String PARAMETER_ACTION_EDIT_SUMMARY = "summary";
public static final String PARAMETER_ACTION_EDIT_BASETIMESTAMP = "basetimestamp";
public static final String PARAMETER_ACTION_EDIT_CAPTCHAID = "captchaid";
public static final String PARAMETER_ACTION_EDIT_CAPTCHAWORD = "captchaword";
public static final String PARAMETER_ACTION_EDIT_BOT = "bot";
public static final String FORMAT_JSON = "json";
public static final String FORMAT_WIKI = "wiki";
public static final String FORMAT_HTML = "html";
/**
* @see KaroAPI#getVersion()
* @return the version of the {@link KaroAPI}
*/
public static Version getVersion()
{
return KaroAPI.getVersion();
}
////////////////////
// parsers needed //
////////////////////
public static final Function<String, Map<String, Object>> PARSER_JSON_OBJECT = new JSONUtil.Parser<>(new TypeReference<Map<String, Object>>() {});
/**
* Default Constructor.<br>
* Initializes the {@link CookieHandler}
*/
public KaroWikiAPI()
{
if(CookieHandler.getDefault() == null)
CookieHandler.setDefault(new CookieManager());
}
/**
* Login with username and password
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param username
* @param password
* @return true, if the operation was successful, false otherwise
*/
@SuppressWarnings("unchecked")
public CompletableFuture<Boolean> login(String username, String password)
{
logger.debug("Performing login: \"" + username + "\"...");
logger.debug(" Obtaining token...");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(PARAMETER_ACTION, ACTION_LOGIN);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
parameters.put(PARAMETER_ACTION_LOGIN_USER, username);
//@formatter:off
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text))
.thenApply(PARSER_JSON_OBJECT)
.thenCompose(jsonObject -> {
String token = (String) ((Map<String, Object>) jsonObject.get("login")).get("token");
logger.debug(" Performing login...");
parameters.put(PARAMETER_ACTION_LOGIN_PASSWORD, password);
parameters.put(PARAMETER_ACTION_LOGIN_TOKEN, token);
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text));
})
.thenApply(PARSER_JSON_OBJECT)
.thenApply(jsonObject -> {
String result = (String) ((Map<String, Object>) jsonObject.get("login")).get("result");
String resultUser = (String) ((Map<String, Object>) jsonObject.get("login")).get("lgusername");
boolean success = "success".equalsIgnoreCase(result) && username.equalsIgnoreCase(resultUser);
logger.debug(" " + (success ? "Successful!" : "Failed"));
return success;
})
.exceptionally((ex) -> {
logger.debug(" " + "Failed (" + ex + ")");
return false;
});
//@formatter:on
}
/**
* Logout from the current session
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @return true, if the operation was successful, false otherwise
*/
@SuppressWarnings("unchecked")
public CompletableFuture<Boolean> logout()
{
logger.debug("Performing logout...");
logger.debug(" Obtaining token...");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(PARAMETER_ACTION, ACTION_QUERY);
parameters.put(PARAMETER_ACTION_QUERY_META, PARAMETER_ACTION_QUERY_META_TOKENS);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
//@formatter:off
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text))
.thenApply(PARSER_JSON_OBJECT)
.thenCompose(jsonObject -> {
String token = (String) ((Map<String, Object>) ((Map<String, Object>) jsonObject.get("query")).get("tokens")).get("csrftoken");
logger.debug(" Performing logout...");
parameters.clear();
parameters.put(PARAMETER_ACTION, ACTION_LOGOUT);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
parameters.put(PARAMETER_ACTION_LOGOUT_TOKEN, token);
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text));
})
.thenApply(json -> {
boolean success = "{}".equalsIgnoreCase(json);
logger.debug(" " + (success ? "Successful!" : "Failed"));
return success;
})
.exceptionally((ex) -> {
logger.debug(" " + "Failed (" + ex + ")");
return false;
});
//@formatter:on
}
/**
* Query properties from a given page
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param prop
* @param propParam
* @param propertiesList
* @return the map with the queried properties
*/
@SuppressWarnings("unchecked")
public CompletableFuture<Map<String, Object>> query(String title, String prop, String propParam, String... propertiesList)
{
String properties = String.join("|", propertiesList);
logger.debug("Performing prop=" + prop + " for page \"" + title + "\"...");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(PARAMETER_ACTION, ACTION_QUERY);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
parameters.put(PARAMETER_ACTION_QUERY_PROP, prop);
parameters.put(PARAMETER_ACTION_QUERY_TITLES, title);
parameters.put(propParam, properties);
//@formatter:off
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text))
.thenApply(PARSER_JSON_OBJECT)
.thenApply(jsonObject -> {
return (Map<String, Object>) ((Map<String, Object>) jsonObject.get("query")).get("pages");
})
.thenApply(pages -> {
if(pages.size() != 1)
{
logger.debug(" Wrong number of results!");
return null;
}
else if(pages.containsKey("-1"))
{
logger.debug(" Page not existing");
return (Map<String, Object>) pages.get("-1");
}
else
{
String id = pages.keySet().iterator().next();
logger.debug(" Page existing with id " + id);
return (Map<String, Object>) pages.get(id);
}
})
.exceptionally((ex) -> {
logger.debug(" " + "Failed (" + ex + ")");
return null;
});
//@formatter:on
}
/**
* Query the revision properties for the given page
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param propertiesList
* @return the map with the queried properties
*/
public CompletableFuture<Map<String, Object>> queryRevisionProperties(String title, String... propertiesList)
{
return query(title, PARAMETER_ACTION_QUERY_PROP_RV, PARAMETER_ACTION_QUERY_RVPROP, propertiesList);
}
/**
* Query the info properties for the given page
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param propertiesList
* @return the map with the queried properties
*/
public CompletableFuture<Map<String, Object>> queryInfoProperties(String title, String... propertiesList)
{
return query(title, PARAMETER_ACTION_QUERY_PROP_IN, PARAMETER_ACTION_QUERY_INPROP, propertiesList);
}
/**
* Edit the page with the given title
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param content - the updated content of the page
* @param summary - an optional edit summary
* @param ignoreConflicts - ignore conflicts? if true, the page will be overwritten regardless of the differences
* @param bot - is this a bot?
* @return true, if the operation was successful, false otherwise
*/
public CompletableFuture<Boolean> edit(String title, String content, String summary, boolean ignoreConflicts, boolean bot)
{
logger.debug("Performing edit of page \"" + title + "\"...");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(PARAMETER_ACTION, ACTION_EDIT);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
parameters.put(PARAMETER_ACTION_EDIT_TITLE, title);
parameters.put(PARAMETER_ACTION_EDIT_TEXT, content);
if(summary != null)
parameters.put(PARAMETER_ACTION_EDIT_SUMMARY, summary);
if(bot)
parameters.put(PARAMETER_ACTION_EDIT_BOT, "true");
//@formatter:off
logger.debug(" Obtaining token...");
CompletableFuture<Void> cf = getToken(title, "edit")
.thenAccept(token -> {
parameters.put(PARAMETER_ACTION_EDIT_TOKEN, token);
});
if(!ignoreConflicts)
{
cf = cf.thenComposeAsync(result -> {
logger.debug(" Obtaining Timestamp...");
return getTimestamp(title);
})
.thenAccept(baseTimestamp -> {
parameters.put(PARAMETER_ACTION_EDIT_BASETIMESTAMP, baseTimestamp);
});
}
return cf.thenComposeAsync(no_value -> {
return tryEdit(parameters, 5);
});
//@formatter:on
}
/**
* Internal operation that is used to handle edit retries (required if a captcha needs to be solved).
*
* @param parameters - the parameters to post to the edit page
* @param retries - the number of remaining retries
* @return true, if the operation was successful, false otherwise
*/
@SuppressWarnings("unchecked")
private CompletableFuture<Boolean> tryEdit(Map<String, Object> parameters, int retries)
{
logger.debug(" Performing edit... retries=" + retries);
//@formatter:off
return CompletableFuture
.supplyAsync(API.doPost(parameters, EnumContentType.text))
.thenApply(PARSER_JSON_OBJECT)
.thenComposeAsync(jsonObject -> {
String result = (String) ((Map<String, Object>) jsonObject.get("edit")).get("result");
boolean success = "success".equalsIgnoreCase(result);
logger.debug(" " + (success ? "Successful!" : "Failed"));
if(!success && retries > 0)
{
// handle captcha
Map<String, Object> captcha = (Map<String, Object>) ((Map<String, Object>) jsonObject.get("edit")).get("captcha");
if(captcha != null)
{
String question = (String) captcha.get("question");
String id = (String) captcha.get("id");
String answer = getCaptchaAnswer(question);
parameters.put(PARAMETER_ACTION_EDIT_CAPTCHAID, id);
parameters.put(PARAMETER_ACTION_EDIT_CAPTCHAWORD, answer);
logger.debug(" Answering captcha: " + question + " -> " + answer);
// try again
return tryEdit(parameters, retries-1);
}
}
return CompletableFuture.completedFuture(success);
});
//@formatter:on
}
/**
* Parse a given page
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param format - 'wiki' or 'html'
* @return the map with the queried properties
*/
@SuppressWarnings("unchecked")
public CompletableFuture<Map<String, Object>> parse(String title, String format)
{
logger.debug("Performing parse format=" + format + " for page \"" + title + "\"...");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(PARAMETER_ACTION, ACTION_PARSE);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
parameters.put(PARAMETER_ACTION_PARSE_PAGE, title);
parameters.put(PARAMETER_ACTION_PARSE_PROP, format);
parameters.put("disablelimitreport", true);
parameters.put("disableeditsection", true);
parameters.put("disabletoc", true);
//@formatter:off
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text))
.thenApply(PARSER_JSON_OBJECT)
.thenApply(jsonObject -> {
if(jsonObject.containsKey("parse"))
{
Map<String, Object> result = (Map<String, Object>) jsonObject.get("parse");
int id = (int) result.get("pageid");
logger.debug(" Page existing with id " + id);
return result;
}
else
{
logger.debug(" Page not existing");
return null;
}
})
.exceptionally((ex) -> {
logger.debug(" " + "Failed (" + ex + ")");
return null;
});
//@formatter:on
}
/**
* Get the content of the page with the given title
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @return the content
*/
public CompletableFuture<String> getContent(String title)
{
return getContent(title, FORMAT_WIKI);
}
/**
* Get the content of the page with the given title
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param format - 'wiki' or 'html'
* @return the content
*/
@SuppressWarnings("unchecked")
public CompletableFuture<String> getContent(String title, String format)
{
String formatProp;
if(FORMAT_HTML.equalsIgnoreCase(format))
formatProp = PARAMETER_ACTION_PARSE_PROP_TEXT;
else if(FORMAT_WIKI.equalsIgnoreCase(format))
formatProp = PARAMETER_ACTION_PARSE_PROP_WIKI;
else
throw new IllegalArgumentException("format must be either 'wiki' or 'html'");
//@formatter:off
return parse(title, formatProp)
.thenApply(properties -> {
// logger.debug(properties);
return (String) ((Map<String, Object>) properties.get(formatProp)).get("*");
});
//@formatter:on
}
/**
* Get the timestamp of the page with the given title
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @return the timestamp
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public CompletableFuture<String> getTimestamp(String title)
{
//@formatter:off
return queryRevisionProperties(title, "timestamp")
.thenApply(properties -> {
if(properties.containsKey("missing"))
return null;
List<?> revisions = (List) properties.get("revisions");
return (String) ((Map<String, Object>) revisions.get(revisions.size() - 1)).get("timestamp");
});
//@formatter:on
}
/**
* Get a token for the page with the given title
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @return the token
*/
public CompletableFuture<String> getToken(String title, String action)
{
//@formatter:off
return query(title, PARAMETER_ACTION_QUERY_PROP_IN, PARAMETER_ACTION_QUERY_INTOKEN, action)
.thenApply(properties -> {
return (String) properties.get(action + "token");
});
//@formatter:on
}
/**
* Provide the answer to the given captcha question.<br>
* Currently 4 captcha questions are known, which are hardcoded here.
*
* @param question - the question
* @return the answer
*/
private static String getCaptchaAnswer(String question)
{
if("Was steht im Forum hinter uralten Threads?".equals(question))
return "saualt";
if("Wer is hier an allem Schuld? (wer hat's programmiert?)".equals(question))
return "Didi";
if("Wie heisst der Bot (weiblich), der staendig im Chat rumlabert?".equals(question))
return "Botrix";
if("Was erscheint im Chat2.0 fuer ein Bildchen vor den spielegeilen?".equals(question))
return "Spiegelei";
return "";
}
}
| ultimate/KaroToolsCollection | KaroAPI4J/src/main/java/ultimate/karoapi4j/KaroWikiAPI.java | 6,853 | // parsers needed // | line_comment | nl | package ultimate.karoapi4j;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.core.type.TypeReference;
import ultimate.karoapi4j.enums.EnumContentType;
import ultimate.karoapi4j.utils.JSONUtil;
import ultimate.karoapi4j.utils.URLLoader;
import ultimate.karoapi4j.utils.Version;
/**
* This is the wrapper for accessing the Karo Wiki API. It provides the basic functionality such as:
* <ul>
* <li>{@link KaroWikiAPI#login(String, String)}</li>
* <li>{@link KaroWikiAPI#logout()}</li>
* <li>{@link KaroWikiAPI#edit(String, String, String, boolean, boolean)}</li>
* <li>{@link KaroWikiAPI#getContent(String)}</li>
* </ul>
* and other operations, that are necessary for editing
* <ul>
* <li>{@link KaroWikiAPI#query(String, String, String, String...)}</li>
* <li>{@link KaroWikiAPI#queryRevisionProperties(String, String...)}</li>
* <li>{@link KaroWikiAPI#queryInfoProperties(String, String...)}</li>
* <li>{@link KaroWikiAPI#getTimestamp(String)}</li>
* <li>{@link KaroWikiAPI#getToken(String, String)}</li>
* <li>inlcuding automated captcha answering</li>
* </ul>
* Note: the Wiki API itself provides much more operations and informations, but those haven't been implemented here. If you have a feature request,
* visit https://github.com/ultimate/KaroToolsCollection/issues and create an issue :)
* <br>
* Note: Accessing the Wiki API requires a user and password for wiki.karopapier.de. Other than the {@link KaroAPI} this API is cookie based and hence
* does not support multiple instances, since cookies are handled globally during program execution. So once a
* {@link KaroWikiAPI#login(String, String)} is performed the user is set for all subsequent operations. If it is required to perform actions for
* different users, dedicated {@link KaroWikiAPI#logout()} and {@link KaroWikiAPI#login(String, String)} need to be used.
* <br>
* Each API call will return a {@link CompletableFuture} which wraps the underlying API call and which then can be used to either load the results
* either blocking or asynchronously (see {@link URLLoader}).
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @author ultimate
*/
public class KaroWikiAPI
{
/**
* Logger-Instance
*/
protected transient final Logger logger = LogManager.getLogger(KaroWikiAPI.class);
/**
* The config key
*/
public static final String CONFIG_KEY = "karoWIKI";
//////////////
// api URLs //
//////////////
protected static final URLLoader KAROWIKI = new URLLoader("https://wiki.karopapier.de");
protected static final URLLoader API = KAROWIKI.relative("/api.php");
//////////////////////////
// parameters & actions //
//////////////////////////
public static final String PARAMETER_ACTION = "action";
public static final String PARAMETER_FORMAT = "format";
public static final String ACTION_LOGIN = "login";
public static final String PARAMETER_ACTION_LOGIN_USER = "lgname";
public static final String PARAMETER_ACTION_LOGIN_PASSWORD = "lgpassword";
public static final String PARAMETER_ACTION_LOGIN_TOKEN = "lgtoken";
public static final String ACTION_LOGOUT = "logout";
public static final String PARAMETER_ACTION_LOGOUT_TOKEN = "token";
public static final String ACTION_QUERY = "query";
public static final String PARAMETER_ACTION_QUERY_META = "meta";
public static final String PARAMETER_ACTION_QUERY_META_TOKENS = "tokens";
public static final String PARAMETER_ACTION_QUERY_PROP = "prop";
public static final String PARAMETER_ACTION_QUERY_PROP_RV = "revisions";
public static final String PARAMETER_ACTION_QUERY_PROP_IN = "info";
public static final String PARAMETER_ACTION_QUERY_TITLES = "titles";
public static final String PARAMETER_ACTION_QUERY_RVPROP = "rvprop";
public static final String PARAMETER_ACTION_QUERY_INPROP = "inprop";
public static final String PARAMETER_ACTION_QUERY_INTOKEN = "intoken";
public static final String ACTION_PARSE = "parse";
public static final String PARAMETER_ACTION_PARSE_PAGE = "page";
public static final String PARAMETER_ACTION_PARSE_PROP = "prop";
public static final String PARAMETER_ACTION_PARSE_PROP_TEXT = "text";
public static final String PARAMETER_ACTION_PARSE_PROP_WIKI = "wikitext";
public static final String ACTION_EDIT = "edit";
public static final String PARAMETER_ACTION_EDIT_TITLE = "title";
public static final String PARAMETER_ACTION_EDIT_TEXT = "text";
public static final String PARAMETER_ACTION_EDIT_TOKEN = "token";
public static final String PARAMETER_ACTION_EDIT_SUMMARY = "summary";
public static final String PARAMETER_ACTION_EDIT_BASETIMESTAMP = "basetimestamp";
public static final String PARAMETER_ACTION_EDIT_CAPTCHAID = "captchaid";
public static final String PARAMETER_ACTION_EDIT_CAPTCHAWORD = "captchaword";
public static final String PARAMETER_ACTION_EDIT_BOT = "bot";
public static final String FORMAT_JSON = "json";
public static final String FORMAT_WIKI = "wiki";
public static final String FORMAT_HTML = "html";
/**
* @see KaroAPI#getVersion()
* @return the version of the {@link KaroAPI}
*/
public static Version getVersion()
{
return KaroAPI.getVersion();
}
////////////////////
// parsers needed<SUF>
////////////////////
public static final Function<String, Map<String, Object>> PARSER_JSON_OBJECT = new JSONUtil.Parser<>(new TypeReference<Map<String, Object>>() {});
/**
* Default Constructor.<br>
* Initializes the {@link CookieHandler}
*/
public KaroWikiAPI()
{
if(CookieHandler.getDefault() == null)
CookieHandler.setDefault(new CookieManager());
}
/**
* Login with username and password
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param username
* @param password
* @return true, if the operation was successful, false otherwise
*/
@SuppressWarnings("unchecked")
public CompletableFuture<Boolean> login(String username, String password)
{
logger.debug("Performing login: \"" + username + "\"...");
logger.debug(" Obtaining token...");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(PARAMETER_ACTION, ACTION_LOGIN);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
parameters.put(PARAMETER_ACTION_LOGIN_USER, username);
//@formatter:off
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text))
.thenApply(PARSER_JSON_OBJECT)
.thenCompose(jsonObject -> {
String token = (String) ((Map<String, Object>) jsonObject.get("login")).get("token");
logger.debug(" Performing login...");
parameters.put(PARAMETER_ACTION_LOGIN_PASSWORD, password);
parameters.put(PARAMETER_ACTION_LOGIN_TOKEN, token);
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text));
})
.thenApply(PARSER_JSON_OBJECT)
.thenApply(jsonObject -> {
String result = (String) ((Map<String, Object>) jsonObject.get("login")).get("result");
String resultUser = (String) ((Map<String, Object>) jsonObject.get("login")).get("lgusername");
boolean success = "success".equalsIgnoreCase(result) && username.equalsIgnoreCase(resultUser);
logger.debug(" " + (success ? "Successful!" : "Failed"));
return success;
})
.exceptionally((ex) -> {
logger.debug(" " + "Failed (" + ex + ")");
return false;
});
//@formatter:on
}
/**
* Logout from the current session
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @return true, if the operation was successful, false otherwise
*/
@SuppressWarnings("unchecked")
public CompletableFuture<Boolean> logout()
{
logger.debug("Performing logout...");
logger.debug(" Obtaining token...");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(PARAMETER_ACTION, ACTION_QUERY);
parameters.put(PARAMETER_ACTION_QUERY_META, PARAMETER_ACTION_QUERY_META_TOKENS);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
//@formatter:off
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text))
.thenApply(PARSER_JSON_OBJECT)
.thenCompose(jsonObject -> {
String token = (String) ((Map<String, Object>) ((Map<String, Object>) jsonObject.get("query")).get("tokens")).get("csrftoken");
logger.debug(" Performing logout...");
parameters.clear();
parameters.put(PARAMETER_ACTION, ACTION_LOGOUT);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
parameters.put(PARAMETER_ACTION_LOGOUT_TOKEN, token);
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text));
})
.thenApply(json -> {
boolean success = "{}".equalsIgnoreCase(json);
logger.debug(" " + (success ? "Successful!" : "Failed"));
return success;
})
.exceptionally((ex) -> {
logger.debug(" " + "Failed (" + ex + ")");
return false;
});
//@formatter:on
}
/**
* Query properties from a given page
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param prop
* @param propParam
* @param propertiesList
* @return the map with the queried properties
*/
@SuppressWarnings("unchecked")
public CompletableFuture<Map<String, Object>> query(String title, String prop, String propParam, String... propertiesList)
{
String properties = String.join("|", propertiesList);
logger.debug("Performing prop=" + prop + " for page \"" + title + "\"...");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(PARAMETER_ACTION, ACTION_QUERY);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
parameters.put(PARAMETER_ACTION_QUERY_PROP, prop);
parameters.put(PARAMETER_ACTION_QUERY_TITLES, title);
parameters.put(propParam, properties);
//@formatter:off
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text))
.thenApply(PARSER_JSON_OBJECT)
.thenApply(jsonObject -> {
return (Map<String, Object>) ((Map<String, Object>) jsonObject.get("query")).get("pages");
})
.thenApply(pages -> {
if(pages.size() != 1)
{
logger.debug(" Wrong number of results!");
return null;
}
else if(pages.containsKey("-1"))
{
logger.debug(" Page not existing");
return (Map<String, Object>) pages.get("-1");
}
else
{
String id = pages.keySet().iterator().next();
logger.debug(" Page existing with id " + id);
return (Map<String, Object>) pages.get(id);
}
})
.exceptionally((ex) -> {
logger.debug(" " + "Failed (" + ex + ")");
return null;
});
//@formatter:on
}
/**
* Query the revision properties for the given page
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param propertiesList
* @return the map with the queried properties
*/
public CompletableFuture<Map<String, Object>> queryRevisionProperties(String title, String... propertiesList)
{
return query(title, PARAMETER_ACTION_QUERY_PROP_RV, PARAMETER_ACTION_QUERY_RVPROP, propertiesList);
}
/**
* Query the info properties for the given page
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param propertiesList
* @return the map with the queried properties
*/
public CompletableFuture<Map<String, Object>> queryInfoProperties(String title, String... propertiesList)
{
return query(title, PARAMETER_ACTION_QUERY_PROP_IN, PARAMETER_ACTION_QUERY_INPROP, propertiesList);
}
/**
* Edit the page with the given title
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param content - the updated content of the page
* @param summary - an optional edit summary
* @param ignoreConflicts - ignore conflicts? if true, the page will be overwritten regardless of the differences
* @param bot - is this a bot?
* @return true, if the operation was successful, false otherwise
*/
public CompletableFuture<Boolean> edit(String title, String content, String summary, boolean ignoreConflicts, boolean bot)
{
logger.debug("Performing edit of page \"" + title + "\"...");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(PARAMETER_ACTION, ACTION_EDIT);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
parameters.put(PARAMETER_ACTION_EDIT_TITLE, title);
parameters.put(PARAMETER_ACTION_EDIT_TEXT, content);
if(summary != null)
parameters.put(PARAMETER_ACTION_EDIT_SUMMARY, summary);
if(bot)
parameters.put(PARAMETER_ACTION_EDIT_BOT, "true");
//@formatter:off
logger.debug(" Obtaining token...");
CompletableFuture<Void> cf = getToken(title, "edit")
.thenAccept(token -> {
parameters.put(PARAMETER_ACTION_EDIT_TOKEN, token);
});
if(!ignoreConflicts)
{
cf = cf.thenComposeAsync(result -> {
logger.debug(" Obtaining Timestamp...");
return getTimestamp(title);
})
.thenAccept(baseTimestamp -> {
parameters.put(PARAMETER_ACTION_EDIT_BASETIMESTAMP, baseTimestamp);
});
}
return cf.thenComposeAsync(no_value -> {
return tryEdit(parameters, 5);
});
//@formatter:on
}
/**
* Internal operation that is used to handle edit retries (required if a captcha needs to be solved).
*
* @param parameters - the parameters to post to the edit page
* @param retries - the number of remaining retries
* @return true, if the operation was successful, false otherwise
*/
@SuppressWarnings("unchecked")
private CompletableFuture<Boolean> tryEdit(Map<String, Object> parameters, int retries)
{
logger.debug(" Performing edit... retries=" + retries);
//@formatter:off
return CompletableFuture
.supplyAsync(API.doPost(parameters, EnumContentType.text))
.thenApply(PARSER_JSON_OBJECT)
.thenComposeAsync(jsonObject -> {
String result = (String) ((Map<String, Object>) jsonObject.get("edit")).get("result");
boolean success = "success".equalsIgnoreCase(result);
logger.debug(" " + (success ? "Successful!" : "Failed"));
if(!success && retries > 0)
{
// handle captcha
Map<String, Object> captcha = (Map<String, Object>) ((Map<String, Object>) jsonObject.get("edit")).get("captcha");
if(captcha != null)
{
String question = (String) captcha.get("question");
String id = (String) captcha.get("id");
String answer = getCaptchaAnswer(question);
parameters.put(PARAMETER_ACTION_EDIT_CAPTCHAID, id);
parameters.put(PARAMETER_ACTION_EDIT_CAPTCHAWORD, answer);
logger.debug(" Answering captcha: " + question + " -> " + answer);
// try again
return tryEdit(parameters, retries-1);
}
}
return CompletableFuture.completedFuture(success);
});
//@formatter:on
}
/**
* Parse a given page
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param format - 'wiki' or 'html'
* @return the map with the queried properties
*/
@SuppressWarnings("unchecked")
public CompletableFuture<Map<String, Object>> parse(String title, String format)
{
logger.debug("Performing parse format=" + format + " for page \"" + title + "\"...");
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(PARAMETER_ACTION, ACTION_PARSE);
parameters.put(PARAMETER_FORMAT, FORMAT_JSON);
parameters.put(PARAMETER_ACTION_PARSE_PAGE, title);
parameters.put(PARAMETER_ACTION_PARSE_PROP, format);
parameters.put("disablelimitreport", true);
parameters.put("disableeditsection", true);
parameters.put("disabletoc", true);
//@formatter:off
return CompletableFuture.supplyAsync(API.doPost(parameters, EnumContentType.text))
.thenApply(PARSER_JSON_OBJECT)
.thenApply(jsonObject -> {
if(jsonObject.containsKey("parse"))
{
Map<String, Object> result = (Map<String, Object>) jsonObject.get("parse");
int id = (int) result.get("pageid");
logger.debug(" Page existing with id " + id);
return result;
}
else
{
logger.debug(" Page not existing");
return null;
}
})
.exceptionally((ex) -> {
logger.debug(" " + "Failed (" + ex + ")");
return null;
});
//@formatter:on
}
/**
* Get the content of the page with the given title
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @return the content
*/
public CompletableFuture<String> getContent(String title)
{
return getContent(title, FORMAT_WIKI);
}
/**
* Get the content of the page with the given title
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @param format - 'wiki' or 'html'
* @return the content
*/
@SuppressWarnings("unchecked")
public CompletableFuture<String> getContent(String title, String format)
{
String formatProp;
if(FORMAT_HTML.equalsIgnoreCase(format))
formatProp = PARAMETER_ACTION_PARSE_PROP_TEXT;
else if(FORMAT_WIKI.equalsIgnoreCase(format))
formatProp = PARAMETER_ACTION_PARSE_PROP_WIKI;
else
throw new IllegalArgumentException("format must be either 'wiki' or 'html'");
//@formatter:off
return parse(title, formatProp)
.thenApply(properties -> {
// logger.debug(properties);
return (String) ((Map<String, Object>) properties.get(formatProp)).get("*");
});
//@formatter:on
}
/**
* Get the timestamp of the page with the given title
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @return the timestamp
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public CompletableFuture<String> getTimestamp(String title)
{
//@formatter:off
return queryRevisionProperties(title, "timestamp")
.thenApply(properties -> {
if(properties.containsKey("missing"))
return null;
List<?> revisions = (List) properties.get("revisions");
return (String) ((Map<String, Object>) revisions.get(revisions.size() - 1)).get("timestamp");
});
//@formatter:on
}
/**
* Get a token for the page with the given title
*
* @see <a href="https://www.karopapier.de/api/">https://www.karopapier.de/api/</a>
* @param title - the title of the page
* @return the token
*/
public CompletableFuture<String> getToken(String title, String action)
{
//@formatter:off
return query(title, PARAMETER_ACTION_QUERY_PROP_IN, PARAMETER_ACTION_QUERY_INTOKEN, action)
.thenApply(properties -> {
return (String) properties.get(action + "token");
});
//@formatter:on
}
/**
* Provide the answer to the given captcha question.<br>
* Currently 4 captcha questions are known, which are hardcoded here.
*
* @param question - the question
* @return the answer
*/
private static String getCaptchaAnswer(String question)
{
if("Was steht im Forum hinter uralten Threads?".equals(question))
return "saualt";
if("Wer is hier an allem Schuld? (wer hat's programmiert?)".equals(question))
return "Didi";
if("Wie heisst der Bot (weiblich), der staendig im Chat rumlabert?".equals(question))
return "Botrix";
if("Was erscheint im Chat2.0 fuer ein Bildchen vor den spielegeilen?".equals(question))
return "Spiegelei";
return "";
}
}
|
46427_8 | /**
* Syncnapsis Framework - Copyright (c) 2012-2014 ultimate
*
* 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 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 MECHANTABILITY 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 Plublic License along with this program;
* if not, see <http://www.gnu.org/licenses/>.
*/
package com.syncnapsis.enums;
import com.syncnapsis.constants.ApplicationBaseConstants;
/**
* Enum f�r die Spezifizierung des Alters eines News-Objekts. Bei der Suche nach
* News kann ein EnumNewsAge-Objekt �bergeben werden und es werden alle News
* zur�ckgeliefert, die neuer sind als das spezifizierte Alter. Die Aufl�sung
* der Enum-Werte als Zeitangeben geschiet �ber die Tabelle Parameter und das
* Namens-Pattern Constants.PARAM_NEWS_MAXAGE = "news.%L.maxAge"
*
* @author ultimate
*/
public enum EnumNewsAge
{
/**
* Alters-Interval 1 (k�rzester Wert)
*/
length1,
/**
* Alters-Interval 2 (2. k�rzester Wert)
*/
length2,
/**
* Alters-Interval 3
*/
length3,
/**
* Alters-Interval 4
*/
length4,
/**
* Alters-Interval 5
*/
length5,
/**
* Alters-Interval 6
*/
length6,
/**
* Alters-Interval 7
*/
length7,
/**
* Alters-Interval 8 (2. l�ngster Wert)
*/
length8,
/**
* Alters-Interval 9 (l�ngster Wert)
*/
length9;
/**
* Wandelt dieses Enum in einen Primary-Key f�r die Verwendung mit der
* Parameter-Tabelle um. Es wird das Namens-Pattern
* Constants.PARAM_NEWS_MAXAGE = "news.%L.maxAge" verwendet.
*
* @return der Parameter-Key zu diesem Enum zu diesem Enum
*/
public String getParameterKey()
{
return ApplicationBaseConstants.PARAM_NEWS_MAXAGE.getName().replace("%L", this.toString());
}
}
| ultimate/syncnapsis | syncnapsis-dev/syncnapsis-dev-archive/src/main/java/com/syncnapsis/enums/EnumNewsAge.java | 718 | /**
* Alters-Interval 7
*/ | block_comment | nl | /**
* Syncnapsis Framework - Copyright (c) 2012-2014 ultimate
*
* 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 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 MECHANTABILITY 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 Plublic License along with this program;
* if not, see <http://www.gnu.org/licenses/>.
*/
package com.syncnapsis.enums;
import com.syncnapsis.constants.ApplicationBaseConstants;
/**
* Enum f�r die Spezifizierung des Alters eines News-Objekts. Bei der Suche nach
* News kann ein EnumNewsAge-Objekt �bergeben werden und es werden alle News
* zur�ckgeliefert, die neuer sind als das spezifizierte Alter. Die Aufl�sung
* der Enum-Werte als Zeitangeben geschiet �ber die Tabelle Parameter und das
* Namens-Pattern Constants.PARAM_NEWS_MAXAGE = "news.%L.maxAge"
*
* @author ultimate
*/
public enum EnumNewsAge
{
/**
* Alters-Interval 1 (k�rzester Wert)
*/
length1,
/**
* Alters-Interval 2 (2. k�rzester Wert)
*/
length2,
/**
* Alters-Interval 3
*/
length3,
/**
* Alters-Interval 4
*/
length4,
/**
* Alters-Interval 5
*/
length5,
/**
* Alters-Interval 6
*/
length6,
/**
* Alters-Interval 7
<SUF>*/
length7,
/**
* Alters-Interval 8 (2. l�ngster Wert)
*/
length8,
/**
* Alters-Interval 9 (l�ngster Wert)
*/
length9;
/**
* Wandelt dieses Enum in einen Primary-Key f�r die Verwendung mit der
* Parameter-Tabelle um. Es wird das Namens-Pattern
* Constants.PARAM_NEWS_MAXAGE = "news.%L.maxAge" verwendet.
*
* @return der Parameter-Key zu diesem Enum zu diesem Enum
*/
public String getParameterKey()
{
return ApplicationBaseConstants.PARAM_NEWS_MAXAGE.getName().replace("%L", this.toString());
}
}
|
10051_3 | /*
* Copyright 2007 Pieter De Rycke
*
* This file is part of JMTP.
*
* JTMP 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 any later version.
*
* JMTP 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 LesserGeneral Public
* License along with JMTP. If not, see <http://www.gnu.org/licenses/>.
*/
package jmtp;
import java.math.BigInteger;
import java.util.Date;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.Guid;
import be.derycke.pieter.com.OleDate;
/**
*
* @author Pieter De Rycke
*/
class PortableDeviceObjectImplWin32 implements PortableDeviceObject {
protected PortableDeviceContentImplWin32 content;
protected PortableDevicePropertiesImplWin32 properties;
protected PortableDeviceKeyCollectionImplWin32 keyCollection;
protected PortableDeviceValuesImplWin32 values;
protected String objectID;
PortableDeviceObjectImplWin32(String objectID,
PortableDeviceContentImplWin32 content,
PortableDevicePropertiesImplWin32 properties) {
this.objectID = objectID;
this.content = content;
this.properties = properties;
try {
this.keyCollection = new PortableDeviceKeyCollectionImplWin32();
this.values = new PortableDeviceValuesImplWin32();
}
catch (COMException e) {
e.printStackTrace();
}
}
/**
* Een String property opvragen.
* @param key
* @return
*/
protected String retrieveStringValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getStringValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return null;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -> de string werd niet ingesteld
}
}
}
protected void changeStringValue(PropertyKey key, String value) {
try {
values.clear();
values.setStringValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected long retrieveLongValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getUnsignedIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return -1;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return -1;
}
}
}
protected void changeLongValue(PropertyKey key, long value) {
try {
values.clear();
values.setUnsignedIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected Date retrieveDateValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return new OleDate(properties.getValues(objectID, keyCollection).getFloatValue(key));
}
catch(COMException e) {
return null;
}
}
protected void changeDateValue(PropertyKey key, Date value) {
try {
values.clear();
values.setFloateValue(key, (float)new OleDate(value).toDouble());
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {}
}
protected boolean retrieveBooleanValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getBoolValue(key);
}
catch(COMException e) {
return false;
}
}
protected Guid retrieveGuidValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getGuidValue(key);
}
catch(COMException e) {
return null;
}
}
protected BigInteger retrieveBigIntegerValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getUnsignedLargeIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return new BigInteger("-1");
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -> de string werd niet ingesteld
}
}
}
protected void changeBigIntegerValue(PropertyKey key, BigInteger value) {
try {
values.clear();
values.setUnsignedLargeIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
public String getID() {
return objectID;
}
public String getName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_NAME);
}
public String getOriginalFileName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME);
}
public boolean canDelete() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_CAN_DELETE);
}
public boolean isHidden() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISHIDDEN);
}
public boolean isSystemObject() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISSYSTEM);
}
public Date getDateModified() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_MODIFIED);
}
public Date getDateCreated() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_CREATED);
}
public Date getDateAuthored() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_AUTHORED);
}
public PortableDeviceObject getParent() {
String parentID = retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID);
if(parentID != null)
return WPDImplWin32.convertToPortableDeviceObject(parentID, content, properties);
else
return null;
}
public BigInteger getSize() {
return retrieveBigIntegerValue(Win32WPDDefines.WPD_OBJECT_SIZE);
}
public String getPersistentUniqueIdentifier() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PERSISTENT_UNIQUE_ID);
}
public boolean isDrmProtected() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_IS_DRM_PROTECTED);
}
public String getSyncID() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID);
}
//TODO slechts tijdelijk de guids geven -> enum aanmaken
public Guid getFormat() {
return retrieveGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT);
}
public void setSyncID(String value) {
changeStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID, value);
}
public void delete() {
try {
PortableDevicePropVariantCollectionImplWin32 collection =
new PortableDevicePropVariantCollectionImplWin32();
collection.add(new PropVariant(this.objectID));
this.content.delete(Win32WPDDefines.PORTABLE_DEVICE_DELETE_NO_RECURSION, collection);
}
catch(COMException e) {
//TODO -> misschien een exception gooien?
e.printStackTrace();
}
}
@Override
public String toString() {
return objectID;
}
public boolean equals(Object o) {
if(o instanceof PortableDeviceObjectImplWin32) {
PortableDeviceObjectImplWin32 object = (PortableDeviceObjectImplWin32)o;
return object.objectID.equals(this.objectID);
}
else
return false;
}
}
| ultrah/jMTPe | source/java/src/jmtp/PortableDeviceObjectImplWin32.java | 2,931 | //comexception -> de string werd niet ingesteld | line_comment | nl | /*
* Copyright 2007 Pieter De Rycke
*
* This file is part of JMTP.
*
* JTMP 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 any later version.
*
* JMTP 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 LesserGeneral Public
* License along with JMTP. If not, see <http://www.gnu.org/licenses/>.
*/
package jmtp;
import java.math.BigInteger;
import java.util.Date;
import be.derycke.pieter.com.COMException;
import be.derycke.pieter.com.Guid;
import be.derycke.pieter.com.OleDate;
/**
*
* @author Pieter De Rycke
*/
class PortableDeviceObjectImplWin32 implements PortableDeviceObject {
protected PortableDeviceContentImplWin32 content;
protected PortableDevicePropertiesImplWin32 properties;
protected PortableDeviceKeyCollectionImplWin32 keyCollection;
protected PortableDeviceValuesImplWin32 values;
protected String objectID;
PortableDeviceObjectImplWin32(String objectID,
PortableDeviceContentImplWin32 content,
PortableDevicePropertiesImplWin32 properties) {
this.objectID = objectID;
this.content = content;
this.properties = properties;
try {
this.keyCollection = new PortableDeviceKeyCollectionImplWin32();
this.values = new PortableDeviceValuesImplWin32();
}
catch (COMException e) {
e.printStackTrace();
}
}
/**
* Een String property opvragen.
* @param key
* @return
*/
protected String retrieveStringValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getStringValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return null;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -><SUF>
}
}
}
protected void changeStringValue(PropertyKey key, String value) {
try {
values.clear();
values.setStringValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected long retrieveLongValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getUnsignedIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return -1;
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return -1;
}
}
}
protected void changeLongValue(PropertyKey key, long value) {
try {
values.clear();
values.setUnsignedIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
protected Date retrieveDateValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return new OleDate(properties.getValues(objectID, keyCollection).getFloatValue(key));
}
catch(COMException e) {
return null;
}
}
protected void changeDateValue(PropertyKey key, Date value) {
try {
values.clear();
values.setFloateValue(key, (float)new OleDate(value).toDouble());
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {}
}
protected boolean retrieveBooleanValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getBoolValue(key);
}
catch(COMException e) {
return false;
}
}
protected Guid retrieveGuidValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).getGuidValue(key);
}
catch(COMException e) {
return null;
}
}
protected BigInteger retrieveBigIntegerValue(PropertyKey key) {
try {
keyCollection.clear();
keyCollection.add(key);
return properties.getValues(objectID, keyCollection).
getUnsignedLargeIntegerValue(key);
}
catch(COMException e) {
if(e.getHresult() == Win32WPDDefines.ERROR_NOT_FOUND)
return new BigInteger("-1");
else if(e.getHresult() == Win32WPDDefines.ERROR_NOT_SUPPORTED)
throw new UnsupportedOperationException("Couldn't retrieve the specified property.");
else {
e.printStackTrace();
return null; //comexception -> de string werd niet ingesteld
}
}
}
protected void changeBigIntegerValue(PropertyKey key, BigInteger value) {
try {
values.clear();
values.setUnsignedLargeIntegerValue(key, value);
PortableDeviceValuesImplWin32 results = properties.setValues(objectID, values);
if(results.count() > 0
&& results.getErrorValue(key).getHresult() != COMException.S_OK) {
throw new UnsupportedOperationException("Couldn't change the property.");
}
}
catch(COMException e) {
e.printStackTrace();
}
}
public String getID() {
return objectID;
}
public String getName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_NAME);
}
public String getOriginalFileName() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_ORIGINAL_FILE_NAME);
}
public boolean canDelete() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_CAN_DELETE);
}
public boolean isHidden() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISHIDDEN);
}
public boolean isSystemObject() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_ISSYSTEM);
}
public Date getDateModified() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_MODIFIED);
}
public Date getDateCreated() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_CREATED);
}
public Date getDateAuthored() {
return retrieveDateValue(Win32WPDDefines.WPD_OBJECT_DATE_AUTHORED);
}
public PortableDeviceObject getParent() {
String parentID = retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PARENT_ID);
if(parentID != null)
return WPDImplWin32.convertToPortableDeviceObject(parentID, content, properties);
else
return null;
}
public BigInteger getSize() {
return retrieveBigIntegerValue(Win32WPDDefines.WPD_OBJECT_SIZE);
}
public String getPersistentUniqueIdentifier() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_PERSISTENT_UNIQUE_ID);
}
public boolean isDrmProtected() {
return retrieveBooleanValue(Win32WPDDefines.WPD_OBJECT_IS_DRM_PROTECTED);
}
public String getSyncID() {
return retrieveStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID);
}
//TODO slechts tijdelijk de guids geven -> enum aanmaken
public Guid getFormat() {
return retrieveGuidValue(Win32WPDDefines.WPD_OBJECT_FORMAT);
}
public void setSyncID(String value) {
changeStringValue(Win32WPDDefines.WPD_OBJECT_SYNC_ID, value);
}
public void delete() {
try {
PortableDevicePropVariantCollectionImplWin32 collection =
new PortableDevicePropVariantCollectionImplWin32();
collection.add(new PropVariant(this.objectID));
this.content.delete(Win32WPDDefines.PORTABLE_DEVICE_DELETE_NO_RECURSION, collection);
}
catch(COMException e) {
//TODO -> misschien een exception gooien?
e.printStackTrace();
}
}
@Override
public String toString() {
return objectID;
}
public boolean equals(Object o) {
if(o instanceof PortableDeviceObjectImplWin32) {
PortableDeviceObjectImplWin32 object = (PortableDeviceObjectImplWin32)o;
return object.objectID.equals(this.objectID);
}
else
return false;
}
}
|
101752_66 | package com.baselet.element.elementnew.plot.drawer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import com.baselet.control.SharedUtils;
import com.baselet.control.basics.geom.Dimension;
import com.baselet.control.basics.geom.Point;
import com.baselet.control.enums.AlignHorizontal;
import com.baselet.diagram.draw.DrawHandler;
import com.baselet.diagram.draw.helper.ColorOwn;
import com.baselet.diagram.draw.helper.ColorOwn.Transparency;
import com.baselet.diagram.draw.helper.theme.Theme;
import com.baselet.diagram.draw.helper.theme.ThemeFactory;
public class PlotDrawHandler {
// Enumerations
public enum Position {
LEFT, UP, DOWN, RIGHT
}
// Plot specific settings
private String[] title;
private String[] desc;
private Double[][] values;
private TreeSet<Double> valuesSorted;
private TreeSet<Double> valuesShownOnAxisSorted;
// private Double[][] valuesMinMaxCorrected; // if all values are >0 or all values are <0 the distance from 0 to the first real value will be subtracted
protected DrawHandler base;
private Double minVal = null;
private Double maxVal = null;
private List<String> colors;
private final Canvas canvas;
private final AxisConfig axisConfig;
public PlotDrawHandler(DrawHandler baseDrawHandler, Dimension size) {
base = baseDrawHandler;
// drawLegend = false;
axisConfig = new AxisConfig();
canvas = new Canvas(size);
}
// Legend Settings
// private boolean drawLegend;
// private Rectangle legendPos;
// /**
// * Abstracts the axis drawing from the type of variables on the axis (description or values)
// * Methods called from this method don't know if they handle a description or value axis
// * @param xAxis if true this is the method call for the x-axis
// * @param valuesSorted the sorted list of values
// */
// private void abstractValueDescFromAxisAndDraw(boolean xAxis) {
// int segmentDisp, lastDrawnSegmentDisp;
//
// if /* thisIsDescAxis */ ((xAxis && axisConfig.isxDescription()) || (!xAxis && !axisConfig.isxDescription())) {
// // if (axisConfig.drawDescriptionAxis()) drawAxisLine(xAxis);
// if (true) {
// lastDrawnSegmentDisp = -axisConfig.getDescSegment()/2;
// for (int i = 0; i < desc.length; i++) {
// segmentDisp = (i * axisConfig.getDescSegment()) + (axisConfig.getDescSegment()/2);
// String value;
// if (xAxis) value = desc[i];
// else value = desc[desc.length-i-1]; // yAxis is drawn from bottom to top, therefore invert computation direction
// // axisConfig.activateDescriptionAxis();
// lastDrawnSegmentDisp = drawMarkerTextIfThereIsEnoughSpace(xAxis, segmentDisp, lastDrawnSegmentDisp, value);
// }
// }
// }
// else /* thisIsValueAxis */ {
// // if (axisConfig.drawValueAxis()) drawAxisLine(xAxis);
// if (true) {
// Double[] valuesToDisplay;
// if (axisConfig.drawValueAxisMarkersAll()) {
// if (axisConfig.getValueSegment() < 1) valuesToDisplay = Utils.createDoubleArrayFromTo(minVal, maxVal, Math.ceil(1/axisConfig.getValueSegment()));
// else valuesToDisplay = Utils.createDoubleArrayFromTo(minVal, maxVal);
// }
// else valuesToDisplay = valuesSorted;
//
// lastDrawnSegmentDisp = (int) (valuesToDisplay[0] * axisConfig.getValueSegment() - 100); // Start at the lowest possible number
// for (Double v : valuesToDisplay) {
// segmentDisp = (int) calculateValuePos(v, axisConfig.getValueSegment());
// // valueStringToDisplay is the String representation of the value (".0" should not be displayed)
// String valueStringToDisplay = (Math.round(v) == v) ? String.valueOf(Math.round(v)) : String.valueOf(v);
// if (axisConfig.drawValueAxisMarkersAll()) {
// int oldLength = valueStringToDisplay.length();
// if (oldLength > 2) {
// valueStringToDisplay = valueStringToDisplay.substring(0, 2);
// for (int i = 0; i < oldLength-2; i++) valueStringToDisplay += "0";
// }
// }
// // if (value == 0) continue; // 0 is not displayed because it would overlap with the arrow end
// // axisConfig.activateValueAxis();
// lastDrawnSegmentDisp = drawMarkerTextIfThereIsEnoughSpace(xAxis, segmentDisp, lastDrawnSegmentDisp, valueStringToDisplay);
// }
// }
// }
// }
//
// /**
// * Draws text descriptions of axes only if there is enough space for it.
// */
// private int drawMarkerTextIfThereIsEnoughSpace(boolean xAxis, int segmentDisp, int lastDrawnSegmentDisp, String valueAsString) {
// boolean drawMarker = false;
// // If text should be displayed markers where there would be no space for the text are not drawn
// // if (axisConfig.drawActiveAxisMarkerText()) {
// int textSpaceNeeded;
// if (xAxis) textSpaceNeeded = base.textWidth(valueAsString);
// else textSpaceNeeded = base.textHeight();
// if ((segmentDisp - lastDrawnSegmentDisp) >= textSpaceNeeded) {
// drawMarker = true;
// lastDrawnSegmentDisp = segmentDisp;
// }
// // }
// else drawMarker = true;
//
// if (drawMarker) drawAxisMarker(xAxis, segmentDisp, valueAsString);
// return lastDrawnSegmentDisp;
// }
// //TODO isnt working properly now
// public void enableLegend(Position position) {
// this.drawLegend = true;
// this.legendPos = getLegendPosition(position);
// }
//
// public void disableLegend() {
// this.drawLegend = false;
// }
//
// private void drawLegend() {
// base.drawRectangle(legendPos.x, legendPos.y, legendPos.width, legendPos.height);
// }
//
// private Rectangle getLegendPosition(Position position) {
// // Calculate size of the legend
// final Rectangle innerLegendBorder = new Rectangle(10, 10, 10, 10);
// int legendWidth = innerLegendBorder.x + innerLegendBorder.width;
// int legendHeight = innerLegendBorder.y + innerLegendBorder.height;
// final int legendSpace = 10;
//
// int textWidth;
// for (String v : desc) {
// legendHeight += base.textHeight();
// textWidth = base.textWidth(v) + innerLegendBorder.x + innerLegendBorder.width;
// if (textWidth > legendWidth) legendWidth = textWidth;
// }
//
// // The outerBorder of the plot must be adjusted to free space for the legend
// int borderX = canvas.getOuterLeftPos();
// int borderY = canvas.getOuterUpPos();
// int borderW = canvas.getOuterRightBorderWidth();
// int borderH = canvas.getOuterDownBorderHeight();
//
// if (position == Position.LEFT) borderX += legendWidth + legendSpace;
// else if (position == Position.RIGHT) borderW += legendWidth + legendSpace;
// else if (position == Position.UP) borderY += legendHeight + legendSpace;
// else if (position == Position.DOWN) borderH += legendHeight + legendSpace;
//
// canvas.setBorder(borderX, borderY, borderW, borderH, AxisConfig.ARROW_DISTANCE);
//
// // Calculate and return the position of the legend rectangle
// final int x, y;
// if (position == Position.LEFT || position == Position.RIGHT) {
// y = (canvas.getInnerDownPos() - legendHeight) / 2;
// if (position == Position.LEFT) {
// x = 1;
// } else {
// x = canvas.getInnerRightPos() - legendWidth - legendSpace/2;
// }
// } else {
// x = (canvas.getInnerRightPos() - legendWidth) / 2;
// if (position == Position.UP) {
// y = 1;
// } else {
// y = canvas.getInnerDownPos() - legendHeight - legendSpace/2;
// }
// }
// return new Rectangle(x, y, legendWidth, legendHeight);
// }
public final void drawPlotAndDescValueAxis(boolean xIsDescription, boolean drawBars, boolean drawLines, boolean drawPoints) {
axisConfig.setxIsDescription(xIsDescription);
setupAxis();
calculateAdditionalSpaceForYAxisTextWidth();
// log.debug("yIsDescription: " + yIsDescription + ", descSegment: " + axisConfig.getDescSegment() + ", valueSegment: " + axisConfig.getValueSegment());
// log.debug("valueRange: " + valueRange + ", barsCount: " + elementCount + ", SourceAxisPos/DescAxisPos: " + axisConfig.getDescAxisPos() + ", BarStart/ValueAxisPos: " + axisConfig.getValueAxisPos());
if (drawBars) {
drawBars(xIsDescription, values, axisConfig.getDescAxisPos(), axisConfig.getValueAxisPos(), axisConfig.getValueSegment(), axisConfig.getDescSegment(), colors);
}
if (drawLines) {
drawLineOrPoints(xIsDescription, values, axisConfig.getDescAxisPos(), axisConfig.getValueAxisPos(), axisConfig.getValueSegment(), axisConfig.getDescSegment(), colors, true);
}
if (drawPoints) {
drawLineOrPoints(xIsDescription, values, axisConfig.getDescAxisPos(), axisConfig.getValueAxisPos(), axisConfig.getValueSegment(), axisConfig.getDescSegment(), colors, false);
}
if (axisConfig.showAxis()) {
drawAxis(xIsDescription, axisConfig.getDescAxisPos(), axisConfig.getValueAxisPos(), axisConfig.getValueSegment(), axisConfig.getDescSegment());
}
}
private void setupAxis() {
final Double valueRange = Math.max(1.0, maxVal - minVal); // The range is >=1 (otherwise nothing will be drawn)
Double negativeRange = 0.0;
if (minVal > 0) {
negativeRange = 0.0;
}
if (minVal < 0) {
if (maxVal < 0) {
negativeRange = valueRange;
}
else {
negativeRange = -minVal;
}
}
int elementCount = desc.length; // Amount of bars/lines/...
for (Double[] vArray : values) {
if (vArray.length > elementCount) {
elementCount = vArray.length;
}
}
// Calculate some necessary variables to draw the bars (these variables abstract from horizontal/vertical to a relative point of view)
if (axisConfig.isxDescription()) {
axisConfig.setDescSegment(canvas.getInnerHorizontalDrawspace() / elementCount);
axisConfig.setValueSegment(canvas.getInnerVerticalDrawspace() / valueRange);
axisConfig.setDescAxisPos((int) (canvas.getInnerDownPos() - axisConfig.getValueSegment() * negativeRange));
axisConfig.setValueAxisPos(canvas.getInnerLeftPos());
}
else {
axisConfig.setDescSegment(canvas.getInnerVerticalDrawspace() / elementCount);
axisConfig.setValueSegment(canvas.getInnerHorizontalDrawspace() / valueRange);
axisConfig.setDescAxisPos((int) (canvas.getInnerLeftPos() + axisConfig.getValueSegment() * negativeRange));
axisConfig.setValueAxisPos(canvas.getInnerUpPos());
}
}
private final void drawAxis(boolean xIsDescription, int sourceAxisPos, int valueAxisPos, Double valueSegment, int descSegment) {
List<Integer> xpoints = new ArrayList<Integer>();
List<String> xtext = new ArrayList<String>();
List<Integer> ypoints = new ArrayList<Integer>();
List<String> ytext = new ArrayList<String>();
int lineIterator = valueAxisPos + descSegment / 2;
for (String d : desc) {
if (xIsDescription) {
xpoints.add(lineIterator);
xtext.add(d);
}
else {
ypoints.add(lineIterator);
ytext.add(d);
}
lineIterator += descSegment;
}
for (Double v : valuesShownOnAxisSorted) {
int linePos = (int) calculateValuePos(v, valueSegment);
if (xIsDescription) {
ypoints.add(sourceAxisPos - linePos);
ytext.add(String.valueOf(v));
}
else {
xpoints.add(sourceAxisPos + linePos);
xtext.add(String.valueOf(v));
}
}
drawGraylines(xpoints, ypoints);
ColorOwn axisColor;
if (ThemeFactory.getActiveThemeEnum() == ThemeFactory.THEMES.DARK) {
axisColor = ThemeFactory.getCurrentTheme().getColor(Theme.PredefinedColors.WHITE).transparency(Transparency.FOREGROUND);
}
else {
axisColor = ThemeFactory.getCurrentTheme().getColor(Theme.PredefinedColors.BLACK).transparency(Transparency.FOREGROUND);
}
base.setForegroundColor(axisColor);
drawAxisLine();
drawMarkers(xpoints, ypoints);
drawMarkerTexts(xpoints, xtext, ypoints, ytext);
}
/**
* Method to draw one line (which one is specified by the boolean xAxis variable)
* @param xAxis
* @param drawArrows
*/
private void drawAxisLine() {
if (axisConfig.drawXAxis()) {
final int x1 = canvas.getInnerLeftPos();
final int x2 = canvas.getInnerRightPos();
final int y = axisConfig.getxAxisPos();
base.drawLine(x1, y, x2, y);
}
if (axisConfig.drawYAxis()) {
final int x = axisConfig.getyAxisPos();
final int y1 = canvas.getInnerUpPos();
final int y2 = canvas.getInnerDownPos();
base.drawLine(x, y1, x, y2);
}
}
private void drawGraylines(List<Integer> xpoints, List<Integer> ypoints) {
ColorOwn grayLines;
if (ThemeFactory.getActiveThemeEnum() == ThemeFactory.THEMES.DARK) {
grayLines = ThemeFactory.getCurrentTheme().getColor(Theme.PredefinedColors.WHITE).transparency(Transparency.BACKGROUND);
}
else {
grayLines = ThemeFactory.getCurrentTheme().getColor(Theme.PredefinedColors.BLACK).transparency(Transparency.SELECTION_BACKGROUND);
}
base.setForegroundColor(grayLines);
boolean drawVerticalGraylines = axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkerGrayline() || !axisConfig.isxDescription() && axisConfig.drawValueAxisMarkerGrayline();
boolean drawHorizontalGraylines = !axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkerGrayline() || axisConfig.isxDescription() && axisConfig.drawValueAxisMarkerGrayline();
if (drawVerticalGraylines) {
for (Integer x : xpoints) {
base.drawLine(x, canvas.getInnerUpPos(), x, canvas.getInnerDownPos());
}
}
if (drawHorizontalGraylines) {
for (Integer y : ypoints) {
base.drawLine(canvas.getInnerLeftPos(), y, canvas.getInnerRightPos(), y);
}
}
}
private void drawMarkers(List<Integer> xpoints, List<Integer> ypoints) {
boolean drawVerticalMarkers = axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkers() || !axisConfig.isxDescription() && axisConfig.drawValueAxisMarkers();
boolean drawHorizontalMarkers = !axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkers() || axisConfig.isxDescription() && axisConfig.drawValueAxisMarkers();
if (drawVerticalMarkers) {
for (Integer x : xpoints) {
base.drawLine(x, axisConfig.getxAxisPos(), x, axisConfig.getxAxisPos() + AxisConfig.ARROW_SIZE);
}
}
if (drawHorizontalMarkers) {
for (Integer y : ypoints) {
base.drawLine(axisConfig.getyAxisPos() - AxisConfig.ARROW_SIZE, y, axisConfig.getyAxisPos(), y);
}
}
}
private void drawMarkerTexts(List<Integer> xpoints, List<String> xtext, List<Integer> ypoints, List<String> ytext) {
boolean drawVerticalMarkerTexts = axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkerText() || !axisConfig.isxDescription() && axisConfig.drawValueAxisMarkerText();
boolean drawHorizontalMarkerTexts = !axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkerText() || axisConfig.isxDescription() && axisConfig.drawValueAxisMarkerText();
if (drawVerticalMarkerTexts) {
for (int i = 0; i < xpoints.size(); i++) {
base.print(xtext.get(i), xpoints.get(i), axisConfig.getxAxisPos() + AxisConfig.ARROW_DISTANCE, AlignHorizontal.CENTER);
}
}
if (drawHorizontalMarkerTexts) {
for (int i = 0; i < ypoints.size(); i++) {
base.print(ytext.get(i), axisConfig.getyAxisPos() - 8, (int) (ypoints.get(i) + base.textHeightMax() / 2), AlignHorizontal.RIGHT);
}
}
}
private final void drawLineOrPoints(boolean xIsDescription, Double[][] values, int sourceAxisPos, int valueAxisPos, Double valueSegment, int descSegment, List<String> colors, boolean line) {
Theme currentTheme = ThemeFactory.getCurrentTheme();
int cIndex = 0;
for (int valueIndex = 0; valueIndex < values.length; valueIndex++) {
Double[] vArray = values[valueIndex];
int actualValPos;
int lineIterator = valueAxisPos + descSegment / 2;
List<Point> points = new ArrayList<Point>();
for (Double v : vArray) {
actualValPos = (int) calculateValuePos(v, valueSegment);
if (xIsDescription) {
points.add(new Point(lineIterator, sourceAxisPos - actualValPos));
}
else {
points.add(new Point(sourceAxisPos + actualValPos, lineIterator));
}
lineIterator += descSegment;
}
if (cIndex >= colors.size()) {
cIndex = 0; // Restart with first color if all colors in the array has been used
}
base.setForegroundColor(currentTheme.forStringOrNull(colors.get(cIndex), Transparency.FOREGROUND));
base.setBackgroundColor(currentTheme.forStringOrNull(colors.get(cIndex), Transparency.FOREGROUND));
if (line) {
for (int i = 0; i < points.size() - 1; i++) {
Point point1 = points.get(i);
Point point2 = points.get(i + 1);
base.drawLine(point1.x, point1.y, point2.x, point2.y);
}
}
else {
for (Point point : points) {
base.drawCircle(point.x, point.y, 2);
}
}
// print titleCol
base.setForegroundColor(currentTheme.forStringOrNull(colors.get(cIndex), Transparency.FOREGROUND).darken(75));
base.print(title[valueIndex], points.get(points.size() - 1).x, points.get(points.size() - 1).y, AlignHorizontal.CENTER);
cIndex++;
}
base.resetColorSettings();
}
private final void drawBars(boolean xIsDescription, Double[][] values, int sourceAxisPos, int valueAxisPos, Double valueSegment, int descSegment, List<String> colors) {
int barLength;
int valueRowAmount = values.length;
for (int vIndex = 0; vIndex < valueRowAmount; vIndex++) {
int cIndex = 0;
int subBarIterator = valueAxisPos;
for (Double v : values[vIndex]) {
if (cIndex >= colors.size()) {
cIndex = 0; // Restart with first color if all colors in the array has been used
}
base.setForegroundColor(ThemeFactory.getCurrentTheme().getColor(Theme.PredefinedColors.TRANSPARENT));
base.setBackgroundColorAndKeepTransparency(colors.get(cIndex));
barLength = (int) calculateValuePos(v, valueSegment);
int barWidth = 0;
int ownvar = vIndex * (int) Math.round((double) descSegment / valueRowAmount);
// calculate last bar width, fixing rounding errors
if (vIndex == valueRowAmount - 1) {
barWidth = subBarIterator + descSegment - (subBarIterator + ownvar);
}
else {
barWidth = (int) Math.round((double) descSegment / valueRowAmount);
}
if (xIsDescription) {
if (barLength > 0) {
base.drawRectangle(subBarIterator + ownvar, sourceAxisPos - barLength, barWidth, barLength);
}
else {
base.drawRectangle(subBarIterator + ownvar, sourceAxisPos, barWidth, -barLength);
}
}
else {
if (barLength > 0) {
base.drawRectangle(sourceAxisPos, subBarIterator + ownvar, barLength, barWidth);
}
else {
base.drawRectangle(sourceAxisPos + barLength, subBarIterator + ownvar, -barLength, barWidth);
}
}
subBarIterator += descSegment;
cIndex++;
}
}
base.resetColorSettings();
}
public final void drawPiePlot() {
Double valueSum = 0.0;
for (Double v : values[0]) {
valueSum += Math.abs(v);
}
final Point ulCorner;
final int diameter;
int height = canvas.getInnerVerticalDrawspace();
int width = canvas.getInnerHorizontalDrawspace();
diameter = height > width ? width : height;
ulCorner = new Point(canvas.getInnerLeftPos(), canvas.getInnerUpPos());
drawPieArcs(values[0], desc, ulCorner, diameter, valueSum, colors);
}
private final void drawPieArcs(Double[] values, String[] desc, Point ulCorner, int diameter, Double valueSum, List<String> colors) {
Theme currentTheme = ThemeFactory.getCurrentTheme();
int cIndex = 0;
Double arcAngle = 0D;
Double startAngle = 0D;
for (int i = 0; i < values.length; i++) {
if (cIndex >= colors.size()) {
cIndex = 0; // Restart with first color if all colors in the array has been used
}
ColorOwn currentFg = base.getForegroundColor();
base.setForegroundColor(currentTheme.getColor(Theme.PredefinedColors.TRANSPARENT));
base.setBackgroundColorAndKeepTransparency(colors.get(cIndex));
arcAngle = i < values.length - 1 ? Math.round(360.0 / valueSum * Math.abs(values[i])) : 360 - startAngle;
// System.out.println("val: "+values[i]+" winkel: "+arcAngle);
int height = canvas.getInnerVerticalDrawspace();
int width = canvas.getInnerHorizontalDrawspace();
base.drawArc(ulCorner.x + width / 2.0 - diameter / 2.0, ulCorner.y + height / 2.0 - diameter / 2.0, diameter, diameter, startAngle.floatValue(), arcAngle.floatValue(), false);
base.setForegroundColor(currentFg);
double radians = (360 - startAngle + (360 - arcAngle / 2)) * Math.PI / 180.0;
int value_x = (int) (diameter / 2.0 * Math.cos(radians) + ulCorner.x + diameter / 2.0 + width / 2.0 - diameter / 2.0);
int value_y = (int) (diameter / 2.0 * Math.sin(radians) + ulCorner.y + diameter / 2.0 + height / 2.0 - diameter / 2.0);
ColorOwn colorDesc;
if (ThemeFactory.getActiveThemeEnum() == ThemeFactory.THEMES.DARK) {
colorDesc = currentTheme.forStringOrNull(colors.get(cIndex), Transparency.FOREGROUND).darken(25);
}
else {
colorDesc = currentTheme.forStringOrNull(colors.get(cIndex), Transparency.FOREGROUND).darken(75);
}
base.setForegroundColor(colorDesc);
base.print(desc[i], value_x, value_y, AlignHorizontal.CENTER);
// System.out.println("value_x: "+value_x+" / value_y:"+value_y);
startAngle += arcAngle;
cIndex++;
}
base.resetColorSettings();
}
private void calculateAdditionalSpaceForYAxisTextWidth() {
double maxWidth = 0;
double valueWidth;
if (axisConfig.isxDescription()) { // y-axis contains values
if (axisConfig.drawValueAxisMarkerText()) {
for (Double v : valuesShownOnAxisSorted) {
valueWidth = base.textWidth(String.valueOf(v));
if (valueWidth > maxWidth) {
maxWidth = valueWidth;
}
}
}
}
else { // y-axis contains description
if (axisConfig.drawDescriptionAxisMarkerText()) {
for (String d : desc) {
valueWidth = base.textWidth(d);
if (valueWidth > maxWidth) {
maxWidth = valueWidth;
}
}
}
}
double adjustValue = maxWidth + canvas.getOuterLeftPos() - (axisConfig.getyAxisPos() - canvas.getInnerLeftPos()) - 5;
if (adjustValue > canvas.getOuterLeftPos()) {
canvas.setBorderX((int) adjustValue);
setupAxis();
// If the y-axis is not exactly over the innerleft-border, it will be displaced by the last setupAxis() call and therefore the additional space for it must be recalculated again
if (axisConfig.getyAxisPos() - canvas.getInnerLeftPos() != 0) {
adjustValue = maxWidth + canvas.getOuterLeftPos() - (axisConfig.getyAxisPos() - canvas.getInnerLeftPos()) - 5;
if (adjustValue > canvas.getOuterLeftPos()) {
canvas.setBorderX((int) adjustValue);
setupAxis();
}
}
}
}
/**
* Calculated value * valueSegment but account for displacements of values if all values are positive or negativ (= positive minVal or negative maxVal)
*/
public double calculateValuePos(double value, double valueSegment) {
if (value > 0 && minVal > 0) {
value -= minVal;
}
else if (value < 0 && maxVal < 0) {
value -= maxVal;
}
return value * valueSegment;
}
public void setValues(String[] desc, String[] title, Double[][] values, List<String> colors) {
this.desc = SharedUtils.cloneArray(desc);
this.title = SharedUtils.cloneArray(title);
this.colors = new ArrayList<String>(colors);
this.values = SharedUtils.cloneArray(values);
valuesSorted = new TreeSet<Double>();
for (Double[] vArray : values) {
for (Double v : vArray) {
valuesSorted.add(v);
}
}
valuesShownOnAxisSorted = axisConfig.setValueAxisList(valuesSorted);
minVal = minRealOrShownValue();
maxVal = maxRealOrShownValue();
}
public void setMinValue(Double minVal) throws IOException {
Double limit = Math.min(minRealOrShownValue(), maxVal);
if (minVal > limit) {
throw new IOException("minValue must be <= " + limit);
}
else {
this.minVal = minVal;
}
}
public void setMaxValue(Double maxVal) throws IOException {
Double limit = Math.max(maxRealOrShownValue(), minVal);
if (maxVal < limit) {
throw new IOException("maxValue must be >= " + limit);
}
else {
this.maxVal = maxVal;
}
}
private double minRealOrShownValue() {
if (valuesShownOnAxisSorted.isEmpty()) {
return valuesSorted.first();
}
else {
return Math.min(valuesSorted.first(), valuesShownOnAxisSorted.first());
}
}
private double maxRealOrShownValue() {
if (valuesShownOnAxisSorted.isEmpty()) {
return valuesSorted.last();
}
else {
return Math.max(valuesSorted.last(), valuesShownOnAxisSorted.last());
}
}
public Canvas getCanvas() {
return canvas;
}
public AxisConfig getAxisConfig() {
return axisConfig;
}
}
| umlet/umlet | umlet-elements/src/main/java/com/baselet/element/elementnew/plot/drawer/PlotDrawHandler.java | 8,058 | // legendHeight += base.textHeight(); | line_comment | nl | package com.baselet.element.elementnew.plot.drawer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import com.baselet.control.SharedUtils;
import com.baselet.control.basics.geom.Dimension;
import com.baselet.control.basics.geom.Point;
import com.baselet.control.enums.AlignHorizontal;
import com.baselet.diagram.draw.DrawHandler;
import com.baselet.diagram.draw.helper.ColorOwn;
import com.baselet.diagram.draw.helper.ColorOwn.Transparency;
import com.baselet.diagram.draw.helper.theme.Theme;
import com.baselet.diagram.draw.helper.theme.ThemeFactory;
public class PlotDrawHandler {
// Enumerations
public enum Position {
LEFT, UP, DOWN, RIGHT
}
// Plot specific settings
private String[] title;
private String[] desc;
private Double[][] values;
private TreeSet<Double> valuesSorted;
private TreeSet<Double> valuesShownOnAxisSorted;
// private Double[][] valuesMinMaxCorrected; // if all values are >0 or all values are <0 the distance from 0 to the first real value will be subtracted
protected DrawHandler base;
private Double minVal = null;
private Double maxVal = null;
private List<String> colors;
private final Canvas canvas;
private final AxisConfig axisConfig;
public PlotDrawHandler(DrawHandler baseDrawHandler, Dimension size) {
base = baseDrawHandler;
// drawLegend = false;
axisConfig = new AxisConfig();
canvas = new Canvas(size);
}
// Legend Settings
// private boolean drawLegend;
// private Rectangle legendPos;
// /**
// * Abstracts the axis drawing from the type of variables on the axis (description or values)
// * Methods called from this method don't know if they handle a description or value axis
// * @param xAxis if true this is the method call for the x-axis
// * @param valuesSorted the sorted list of values
// */
// private void abstractValueDescFromAxisAndDraw(boolean xAxis) {
// int segmentDisp, lastDrawnSegmentDisp;
//
// if /* thisIsDescAxis */ ((xAxis && axisConfig.isxDescription()) || (!xAxis && !axisConfig.isxDescription())) {
// // if (axisConfig.drawDescriptionAxis()) drawAxisLine(xAxis);
// if (true) {
// lastDrawnSegmentDisp = -axisConfig.getDescSegment()/2;
// for (int i = 0; i < desc.length; i++) {
// segmentDisp = (i * axisConfig.getDescSegment()) + (axisConfig.getDescSegment()/2);
// String value;
// if (xAxis) value = desc[i];
// else value = desc[desc.length-i-1]; // yAxis is drawn from bottom to top, therefore invert computation direction
// // axisConfig.activateDescriptionAxis();
// lastDrawnSegmentDisp = drawMarkerTextIfThereIsEnoughSpace(xAxis, segmentDisp, lastDrawnSegmentDisp, value);
// }
// }
// }
// else /* thisIsValueAxis */ {
// // if (axisConfig.drawValueAxis()) drawAxisLine(xAxis);
// if (true) {
// Double[] valuesToDisplay;
// if (axisConfig.drawValueAxisMarkersAll()) {
// if (axisConfig.getValueSegment() < 1) valuesToDisplay = Utils.createDoubleArrayFromTo(minVal, maxVal, Math.ceil(1/axisConfig.getValueSegment()));
// else valuesToDisplay = Utils.createDoubleArrayFromTo(minVal, maxVal);
// }
// else valuesToDisplay = valuesSorted;
//
// lastDrawnSegmentDisp = (int) (valuesToDisplay[0] * axisConfig.getValueSegment() - 100); // Start at the lowest possible number
// for (Double v : valuesToDisplay) {
// segmentDisp = (int) calculateValuePos(v, axisConfig.getValueSegment());
// // valueStringToDisplay is the String representation of the value (".0" should not be displayed)
// String valueStringToDisplay = (Math.round(v) == v) ? String.valueOf(Math.round(v)) : String.valueOf(v);
// if (axisConfig.drawValueAxisMarkersAll()) {
// int oldLength = valueStringToDisplay.length();
// if (oldLength > 2) {
// valueStringToDisplay = valueStringToDisplay.substring(0, 2);
// for (int i = 0; i < oldLength-2; i++) valueStringToDisplay += "0";
// }
// }
// // if (value == 0) continue; // 0 is not displayed because it would overlap with the arrow end
// // axisConfig.activateValueAxis();
// lastDrawnSegmentDisp = drawMarkerTextIfThereIsEnoughSpace(xAxis, segmentDisp, lastDrawnSegmentDisp, valueStringToDisplay);
// }
// }
// }
// }
//
// /**
// * Draws text descriptions of axes only if there is enough space for it.
// */
// private int drawMarkerTextIfThereIsEnoughSpace(boolean xAxis, int segmentDisp, int lastDrawnSegmentDisp, String valueAsString) {
// boolean drawMarker = false;
// // If text should be displayed markers where there would be no space for the text are not drawn
// // if (axisConfig.drawActiveAxisMarkerText()) {
// int textSpaceNeeded;
// if (xAxis) textSpaceNeeded = base.textWidth(valueAsString);
// else textSpaceNeeded = base.textHeight();
// if ((segmentDisp - lastDrawnSegmentDisp) >= textSpaceNeeded) {
// drawMarker = true;
// lastDrawnSegmentDisp = segmentDisp;
// }
// // }
// else drawMarker = true;
//
// if (drawMarker) drawAxisMarker(xAxis, segmentDisp, valueAsString);
// return lastDrawnSegmentDisp;
// }
// //TODO isnt working properly now
// public void enableLegend(Position position) {
// this.drawLegend = true;
// this.legendPos = getLegendPosition(position);
// }
//
// public void disableLegend() {
// this.drawLegend = false;
// }
//
// private void drawLegend() {
// base.drawRectangle(legendPos.x, legendPos.y, legendPos.width, legendPos.height);
// }
//
// private Rectangle getLegendPosition(Position position) {
// // Calculate size of the legend
// final Rectangle innerLegendBorder = new Rectangle(10, 10, 10, 10);
// int legendWidth = innerLegendBorder.x + innerLegendBorder.width;
// int legendHeight = innerLegendBorder.y + innerLegendBorder.height;
// final int legendSpace = 10;
//
// int textWidth;
// for (String v : desc) {
// legendHeight +=<SUF>
// textWidth = base.textWidth(v) + innerLegendBorder.x + innerLegendBorder.width;
// if (textWidth > legendWidth) legendWidth = textWidth;
// }
//
// // The outerBorder of the plot must be adjusted to free space for the legend
// int borderX = canvas.getOuterLeftPos();
// int borderY = canvas.getOuterUpPos();
// int borderW = canvas.getOuterRightBorderWidth();
// int borderH = canvas.getOuterDownBorderHeight();
//
// if (position == Position.LEFT) borderX += legendWidth + legendSpace;
// else if (position == Position.RIGHT) borderW += legendWidth + legendSpace;
// else if (position == Position.UP) borderY += legendHeight + legendSpace;
// else if (position == Position.DOWN) borderH += legendHeight + legendSpace;
//
// canvas.setBorder(borderX, borderY, borderW, borderH, AxisConfig.ARROW_DISTANCE);
//
// // Calculate and return the position of the legend rectangle
// final int x, y;
// if (position == Position.LEFT || position == Position.RIGHT) {
// y = (canvas.getInnerDownPos() - legendHeight) / 2;
// if (position == Position.LEFT) {
// x = 1;
// } else {
// x = canvas.getInnerRightPos() - legendWidth - legendSpace/2;
// }
// } else {
// x = (canvas.getInnerRightPos() - legendWidth) / 2;
// if (position == Position.UP) {
// y = 1;
// } else {
// y = canvas.getInnerDownPos() - legendHeight - legendSpace/2;
// }
// }
// return new Rectangle(x, y, legendWidth, legendHeight);
// }
public final void drawPlotAndDescValueAxis(boolean xIsDescription, boolean drawBars, boolean drawLines, boolean drawPoints) {
axisConfig.setxIsDescription(xIsDescription);
setupAxis();
calculateAdditionalSpaceForYAxisTextWidth();
// log.debug("yIsDescription: " + yIsDescription + ", descSegment: " + axisConfig.getDescSegment() + ", valueSegment: " + axisConfig.getValueSegment());
// log.debug("valueRange: " + valueRange + ", barsCount: " + elementCount + ", SourceAxisPos/DescAxisPos: " + axisConfig.getDescAxisPos() + ", BarStart/ValueAxisPos: " + axisConfig.getValueAxisPos());
if (drawBars) {
drawBars(xIsDescription, values, axisConfig.getDescAxisPos(), axisConfig.getValueAxisPos(), axisConfig.getValueSegment(), axisConfig.getDescSegment(), colors);
}
if (drawLines) {
drawLineOrPoints(xIsDescription, values, axisConfig.getDescAxisPos(), axisConfig.getValueAxisPos(), axisConfig.getValueSegment(), axisConfig.getDescSegment(), colors, true);
}
if (drawPoints) {
drawLineOrPoints(xIsDescription, values, axisConfig.getDescAxisPos(), axisConfig.getValueAxisPos(), axisConfig.getValueSegment(), axisConfig.getDescSegment(), colors, false);
}
if (axisConfig.showAxis()) {
drawAxis(xIsDescription, axisConfig.getDescAxisPos(), axisConfig.getValueAxisPos(), axisConfig.getValueSegment(), axisConfig.getDescSegment());
}
}
private void setupAxis() {
final Double valueRange = Math.max(1.0, maxVal - minVal); // The range is >=1 (otherwise nothing will be drawn)
Double negativeRange = 0.0;
if (minVal > 0) {
negativeRange = 0.0;
}
if (minVal < 0) {
if (maxVal < 0) {
negativeRange = valueRange;
}
else {
negativeRange = -minVal;
}
}
int elementCount = desc.length; // Amount of bars/lines/...
for (Double[] vArray : values) {
if (vArray.length > elementCount) {
elementCount = vArray.length;
}
}
// Calculate some necessary variables to draw the bars (these variables abstract from horizontal/vertical to a relative point of view)
if (axisConfig.isxDescription()) {
axisConfig.setDescSegment(canvas.getInnerHorizontalDrawspace() / elementCount);
axisConfig.setValueSegment(canvas.getInnerVerticalDrawspace() / valueRange);
axisConfig.setDescAxisPos((int) (canvas.getInnerDownPos() - axisConfig.getValueSegment() * negativeRange));
axisConfig.setValueAxisPos(canvas.getInnerLeftPos());
}
else {
axisConfig.setDescSegment(canvas.getInnerVerticalDrawspace() / elementCount);
axisConfig.setValueSegment(canvas.getInnerHorizontalDrawspace() / valueRange);
axisConfig.setDescAxisPos((int) (canvas.getInnerLeftPos() + axisConfig.getValueSegment() * negativeRange));
axisConfig.setValueAxisPos(canvas.getInnerUpPos());
}
}
private final void drawAxis(boolean xIsDescription, int sourceAxisPos, int valueAxisPos, Double valueSegment, int descSegment) {
List<Integer> xpoints = new ArrayList<Integer>();
List<String> xtext = new ArrayList<String>();
List<Integer> ypoints = new ArrayList<Integer>();
List<String> ytext = new ArrayList<String>();
int lineIterator = valueAxisPos + descSegment / 2;
for (String d : desc) {
if (xIsDescription) {
xpoints.add(lineIterator);
xtext.add(d);
}
else {
ypoints.add(lineIterator);
ytext.add(d);
}
lineIterator += descSegment;
}
for (Double v : valuesShownOnAxisSorted) {
int linePos = (int) calculateValuePos(v, valueSegment);
if (xIsDescription) {
ypoints.add(sourceAxisPos - linePos);
ytext.add(String.valueOf(v));
}
else {
xpoints.add(sourceAxisPos + linePos);
xtext.add(String.valueOf(v));
}
}
drawGraylines(xpoints, ypoints);
ColorOwn axisColor;
if (ThemeFactory.getActiveThemeEnum() == ThemeFactory.THEMES.DARK) {
axisColor = ThemeFactory.getCurrentTheme().getColor(Theme.PredefinedColors.WHITE).transparency(Transparency.FOREGROUND);
}
else {
axisColor = ThemeFactory.getCurrentTheme().getColor(Theme.PredefinedColors.BLACK).transparency(Transparency.FOREGROUND);
}
base.setForegroundColor(axisColor);
drawAxisLine();
drawMarkers(xpoints, ypoints);
drawMarkerTexts(xpoints, xtext, ypoints, ytext);
}
/**
* Method to draw one line (which one is specified by the boolean xAxis variable)
* @param xAxis
* @param drawArrows
*/
private void drawAxisLine() {
if (axisConfig.drawXAxis()) {
final int x1 = canvas.getInnerLeftPos();
final int x2 = canvas.getInnerRightPos();
final int y = axisConfig.getxAxisPos();
base.drawLine(x1, y, x2, y);
}
if (axisConfig.drawYAxis()) {
final int x = axisConfig.getyAxisPos();
final int y1 = canvas.getInnerUpPos();
final int y2 = canvas.getInnerDownPos();
base.drawLine(x, y1, x, y2);
}
}
private void drawGraylines(List<Integer> xpoints, List<Integer> ypoints) {
ColorOwn grayLines;
if (ThemeFactory.getActiveThemeEnum() == ThemeFactory.THEMES.DARK) {
grayLines = ThemeFactory.getCurrentTheme().getColor(Theme.PredefinedColors.WHITE).transparency(Transparency.BACKGROUND);
}
else {
grayLines = ThemeFactory.getCurrentTheme().getColor(Theme.PredefinedColors.BLACK).transparency(Transparency.SELECTION_BACKGROUND);
}
base.setForegroundColor(grayLines);
boolean drawVerticalGraylines = axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkerGrayline() || !axisConfig.isxDescription() && axisConfig.drawValueAxisMarkerGrayline();
boolean drawHorizontalGraylines = !axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkerGrayline() || axisConfig.isxDescription() && axisConfig.drawValueAxisMarkerGrayline();
if (drawVerticalGraylines) {
for (Integer x : xpoints) {
base.drawLine(x, canvas.getInnerUpPos(), x, canvas.getInnerDownPos());
}
}
if (drawHorizontalGraylines) {
for (Integer y : ypoints) {
base.drawLine(canvas.getInnerLeftPos(), y, canvas.getInnerRightPos(), y);
}
}
}
private void drawMarkers(List<Integer> xpoints, List<Integer> ypoints) {
boolean drawVerticalMarkers = axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkers() || !axisConfig.isxDescription() && axisConfig.drawValueAxisMarkers();
boolean drawHorizontalMarkers = !axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkers() || axisConfig.isxDescription() && axisConfig.drawValueAxisMarkers();
if (drawVerticalMarkers) {
for (Integer x : xpoints) {
base.drawLine(x, axisConfig.getxAxisPos(), x, axisConfig.getxAxisPos() + AxisConfig.ARROW_SIZE);
}
}
if (drawHorizontalMarkers) {
for (Integer y : ypoints) {
base.drawLine(axisConfig.getyAxisPos() - AxisConfig.ARROW_SIZE, y, axisConfig.getyAxisPos(), y);
}
}
}
private void drawMarkerTexts(List<Integer> xpoints, List<String> xtext, List<Integer> ypoints, List<String> ytext) {
boolean drawVerticalMarkerTexts = axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkerText() || !axisConfig.isxDescription() && axisConfig.drawValueAxisMarkerText();
boolean drawHorizontalMarkerTexts = !axisConfig.isxDescription() && axisConfig.drawDescriptionAxisMarkerText() || axisConfig.isxDescription() && axisConfig.drawValueAxisMarkerText();
if (drawVerticalMarkerTexts) {
for (int i = 0; i < xpoints.size(); i++) {
base.print(xtext.get(i), xpoints.get(i), axisConfig.getxAxisPos() + AxisConfig.ARROW_DISTANCE, AlignHorizontal.CENTER);
}
}
if (drawHorizontalMarkerTexts) {
for (int i = 0; i < ypoints.size(); i++) {
base.print(ytext.get(i), axisConfig.getyAxisPos() - 8, (int) (ypoints.get(i) + base.textHeightMax() / 2), AlignHorizontal.RIGHT);
}
}
}
private final void drawLineOrPoints(boolean xIsDescription, Double[][] values, int sourceAxisPos, int valueAxisPos, Double valueSegment, int descSegment, List<String> colors, boolean line) {
Theme currentTheme = ThemeFactory.getCurrentTheme();
int cIndex = 0;
for (int valueIndex = 0; valueIndex < values.length; valueIndex++) {
Double[] vArray = values[valueIndex];
int actualValPos;
int lineIterator = valueAxisPos + descSegment / 2;
List<Point> points = new ArrayList<Point>();
for (Double v : vArray) {
actualValPos = (int) calculateValuePos(v, valueSegment);
if (xIsDescription) {
points.add(new Point(lineIterator, sourceAxisPos - actualValPos));
}
else {
points.add(new Point(sourceAxisPos + actualValPos, lineIterator));
}
lineIterator += descSegment;
}
if (cIndex >= colors.size()) {
cIndex = 0; // Restart with first color if all colors in the array has been used
}
base.setForegroundColor(currentTheme.forStringOrNull(colors.get(cIndex), Transparency.FOREGROUND));
base.setBackgroundColor(currentTheme.forStringOrNull(colors.get(cIndex), Transparency.FOREGROUND));
if (line) {
for (int i = 0; i < points.size() - 1; i++) {
Point point1 = points.get(i);
Point point2 = points.get(i + 1);
base.drawLine(point1.x, point1.y, point2.x, point2.y);
}
}
else {
for (Point point : points) {
base.drawCircle(point.x, point.y, 2);
}
}
// print titleCol
base.setForegroundColor(currentTheme.forStringOrNull(colors.get(cIndex), Transparency.FOREGROUND).darken(75));
base.print(title[valueIndex], points.get(points.size() - 1).x, points.get(points.size() - 1).y, AlignHorizontal.CENTER);
cIndex++;
}
base.resetColorSettings();
}
private final void drawBars(boolean xIsDescription, Double[][] values, int sourceAxisPos, int valueAxisPos, Double valueSegment, int descSegment, List<String> colors) {
int barLength;
int valueRowAmount = values.length;
for (int vIndex = 0; vIndex < valueRowAmount; vIndex++) {
int cIndex = 0;
int subBarIterator = valueAxisPos;
for (Double v : values[vIndex]) {
if (cIndex >= colors.size()) {
cIndex = 0; // Restart with first color if all colors in the array has been used
}
base.setForegroundColor(ThemeFactory.getCurrentTheme().getColor(Theme.PredefinedColors.TRANSPARENT));
base.setBackgroundColorAndKeepTransparency(colors.get(cIndex));
barLength = (int) calculateValuePos(v, valueSegment);
int barWidth = 0;
int ownvar = vIndex * (int) Math.round((double) descSegment / valueRowAmount);
// calculate last bar width, fixing rounding errors
if (vIndex == valueRowAmount - 1) {
barWidth = subBarIterator + descSegment - (subBarIterator + ownvar);
}
else {
barWidth = (int) Math.round((double) descSegment / valueRowAmount);
}
if (xIsDescription) {
if (barLength > 0) {
base.drawRectangle(subBarIterator + ownvar, sourceAxisPos - barLength, barWidth, barLength);
}
else {
base.drawRectangle(subBarIterator + ownvar, sourceAxisPos, barWidth, -barLength);
}
}
else {
if (barLength > 0) {
base.drawRectangle(sourceAxisPos, subBarIterator + ownvar, barLength, barWidth);
}
else {
base.drawRectangle(sourceAxisPos + barLength, subBarIterator + ownvar, -barLength, barWidth);
}
}
subBarIterator += descSegment;
cIndex++;
}
}
base.resetColorSettings();
}
public final void drawPiePlot() {
Double valueSum = 0.0;
for (Double v : values[0]) {
valueSum += Math.abs(v);
}
final Point ulCorner;
final int diameter;
int height = canvas.getInnerVerticalDrawspace();
int width = canvas.getInnerHorizontalDrawspace();
diameter = height > width ? width : height;
ulCorner = new Point(canvas.getInnerLeftPos(), canvas.getInnerUpPos());
drawPieArcs(values[0], desc, ulCorner, diameter, valueSum, colors);
}
private final void drawPieArcs(Double[] values, String[] desc, Point ulCorner, int diameter, Double valueSum, List<String> colors) {
Theme currentTheme = ThemeFactory.getCurrentTheme();
int cIndex = 0;
Double arcAngle = 0D;
Double startAngle = 0D;
for (int i = 0; i < values.length; i++) {
if (cIndex >= colors.size()) {
cIndex = 0; // Restart with first color if all colors in the array has been used
}
ColorOwn currentFg = base.getForegroundColor();
base.setForegroundColor(currentTheme.getColor(Theme.PredefinedColors.TRANSPARENT));
base.setBackgroundColorAndKeepTransparency(colors.get(cIndex));
arcAngle = i < values.length - 1 ? Math.round(360.0 / valueSum * Math.abs(values[i])) : 360 - startAngle;
// System.out.println("val: "+values[i]+" winkel: "+arcAngle);
int height = canvas.getInnerVerticalDrawspace();
int width = canvas.getInnerHorizontalDrawspace();
base.drawArc(ulCorner.x + width / 2.0 - diameter / 2.0, ulCorner.y + height / 2.0 - diameter / 2.0, diameter, diameter, startAngle.floatValue(), arcAngle.floatValue(), false);
base.setForegroundColor(currentFg);
double radians = (360 - startAngle + (360 - arcAngle / 2)) * Math.PI / 180.0;
int value_x = (int) (diameter / 2.0 * Math.cos(radians) + ulCorner.x + diameter / 2.0 + width / 2.0 - diameter / 2.0);
int value_y = (int) (diameter / 2.0 * Math.sin(radians) + ulCorner.y + diameter / 2.0 + height / 2.0 - diameter / 2.0);
ColorOwn colorDesc;
if (ThemeFactory.getActiveThemeEnum() == ThemeFactory.THEMES.DARK) {
colorDesc = currentTheme.forStringOrNull(colors.get(cIndex), Transparency.FOREGROUND).darken(25);
}
else {
colorDesc = currentTheme.forStringOrNull(colors.get(cIndex), Transparency.FOREGROUND).darken(75);
}
base.setForegroundColor(colorDesc);
base.print(desc[i], value_x, value_y, AlignHorizontal.CENTER);
// System.out.println("value_x: "+value_x+" / value_y:"+value_y);
startAngle += arcAngle;
cIndex++;
}
base.resetColorSettings();
}
private void calculateAdditionalSpaceForYAxisTextWidth() {
double maxWidth = 0;
double valueWidth;
if (axisConfig.isxDescription()) { // y-axis contains values
if (axisConfig.drawValueAxisMarkerText()) {
for (Double v : valuesShownOnAxisSorted) {
valueWidth = base.textWidth(String.valueOf(v));
if (valueWidth > maxWidth) {
maxWidth = valueWidth;
}
}
}
}
else { // y-axis contains description
if (axisConfig.drawDescriptionAxisMarkerText()) {
for (String d : desc) {
valueWidth = base.textWidth(d);
if (valueWidth > maxWidth) {
maxWidth = valueWidth;
}
}
}
}
double adjustValue = maxWidth + canvas.getOuterLeftPos() - (axisConfig.getyAxisPos() - canvas.getInnerLeftPos()) - 5;
if (adjustValue > canvas.getOuterLeftPos()) {
canvas.setBorderX((int) adjustValue);
setupAxis();
// If the y-axis is not exactly over the innerleft-border, it will be displaced by the last setupAxis() call and therefore the additional space for it must be recalculated again
if (axisConfig.getyAxisPos() - canvas.getInnerLeftPos() != 0) {
adjustValue = maxWidth + canvas.getOuterLeftPos() - (axisConfig.getyAxisPos() - canvas.getInnerLeftPos()) - 5;
if (adjustValue > canvas.getOuterLeftPos()) {
canvas.setBorderX((int) adjustValue);
setupAxis();
}
}
}
}
/**
* Calculated value * valueSegment but account for displacements of values if all values are positive or negativ (= positive minVal or negative maxVal)
*/
public double calculateValuePos(double value, double valueSegment) {
if (value > 0 && minVal > 0) {
value -= minVal;
}
else if (value < 0 && maxVal < 0) {
value -= maxVal;
}
return value * valueSegment;
}
public void setValues(String[] desc, String[] title, Double[][] values, List<String> colors) {
this.desc = SharedUtils.cloneArray(desc);
this.title = SharedUtils.cloneArray(title);
this.colors = new ArrayList<String>(colors);
this.values = SharedUtils.cloneArray(values);
valuesSorted = new TreeSet<Double>();
for (Double[] vArray : values) {
for (Double v : vArray) {
valuesSorted.add(v);
}
}
valuesShownOnAxisSorted = axisConfig.setValueAxisList(valuesSorted);
minVal = minRealOrShownValue();
maxVal = maxRealOrShownValue();
}
public void setMinValue(Double minVal) throws IOException {
Double limit = Math.min(minRealOrShownValue(), maxVal);
if (minVal > limit) {
throw new IOException("minValue must be <= " + limit);
}
else {
this.minVal = minVal;
}
}
public void setMaxValue(Double maxVal) throws IOException {
Double limit = Math.max(maxRealOrShownValue(), minVal);
if (maxVal < limit) {
throw new IOException("maxValue must be >= " + limit);
}
else {
this.maxVal = maxVal;
}
}
private double minRealOrShownValue() {
if (valuesShownOnAxisSorted.isEmpty()) {
return valuesSorted.first();
}
else {
return Math.min(valuesSorted.first(), valuesShownOnAxisSorted.first());
}
}
private double maxRealOrShownValue() {
if (valuesShownOnAxisSorted.isEmpty()) {
return valuesSorted.last();
}
else {
return Math.max(valuesSorted.last(), valuesShownOnAxisSorted.last());
}
}
public Canvas getCanvas() {
return canvas;
}
public AxisConfig getAxisConfig() {
return axisConfig;
}
}
|
71727_17 | /*******************************************************************************
* This file is part of Umbra.
*
* Umbra 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.
*
* Umbra 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 Umbra. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (c) 2011 Vasile Jureschi <[email protected]>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
*
* http://www.gnu.org/licenses/gpl-3.0.html
*
* Contributors:
* Vasile Jureschi <[email protected]> - initial API and implementation
* Yen-Liang, Shen - Simplified Chinese and Traditional Chinese translations
******************************************************************************/
package org.unchiujar.umbra2.io;
import android.location.Location;
import android.location.LocationManager;
import com.google.android.gms.maps.model.LatLng;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unchiujar.umbra2.location.ApproximateLocation;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
/**
* Imports GPX file.
*
* @author Leif Hendrik Wilden
* @author Steffen Horlacher
* @author Rodrigo Damazio
* @author Vasile Jureschi
*/
public class GpxImporter extends DefaultHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GpxImporter.class);
// GPX tag names and attributes
private static final String TAG_ALTITUDE = "ele";
private static final String TAG_DESCRIPTION = "desc";
private static final String TAG_NAME = "name";
private static final String TAG_TIME = "time";
private static final String TAG_TRACK = "trk";
private static final String TAG_TRACK_POINT = "trkpt";
// <wpt lat="51.31488000" lon="6.714700000">
private static final String TAG_WAYPOINT = "wpt";
private static final Object TAG_TRACK_SEGMENT = "trkseg";
private static final String ATT_LAT = "lat";
private static final String ATT_LON = "lon";
// The SAX locator to get the current line information
private Locator locator;
// The current element content
private String content;
// True if if we're inside a track's xml element
private boolean isInTrackElement = false;
// The current child depth for the current track
private int trackChildDepth = 0;
// The current location
private Location location;
// The last location in the current segment
private Location lastLocationInSegment;
private static List<ApproximateLocation> locations = new LinkedList<ApproximateLocation>();
/**
* Reads GPS tracks from a GPX file and writes tracks and their coordinates to the database.
*
* @param inputStream the input stream for the GPX file
*/
public static List<ApproximateLocation> importGPXFile(InputStream inputStream) throws ParserConfigurationException,
SAXException, IOException {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
GpxImporter gpxImporter = new GpxImporter();
long start = System.currentTimeMillis();
saxParser.parse(inputStream, gpxImporter);
long end = System.currentTimeMillis();
LOGGER.debug("Total import time: " + (end - start) + "ms");
return locations;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String newContent = new String(ch, start, length);
if (content == null) {
content = newContent;
} else {
/*
* In 99% of the cases, a single call to this method will be made for each sequence of
* characters we're interested in, so we'll rarely be concatenating strings, thus not
* justifying the use of a StringBuilder.
*/
content += newContent;
}
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if (isInTrackElement) {
trackChildDepth++;
if (localName.equals(TAG_TRACK)) {
throw new SAXException(
createErrorMessage("Invalid GPX. Already inside a track."));
} else if (localName.equals(TAG_TRACK_SEGMENT)) {
onTrackSegmentElementStart();
} else if (localName.equals(TAG_TRACK_POINT)) {
onTrackPointElementStart(attributes);
}
} else if (localName.equals(TAG_TRACK)) {
isInTrackElement = true;
trackChildDepth = 0;
onTrackElementStart();
} else if (localName.equals(TAG_WAYPOINT)) {
LOGGER.debug("Waypoint element found with attributes {}", attributes);
onWaypointStart(attributes);
}
}
private void onWaypointStart(Attributes attributes) throws SAXException {
String latitude = attributes.getValue(ATT_LAT);
String longitude = attributes.getValue(ATT_LON);
if (latitude == null || longitude == null) {
throw new SAXException(
createErrorMessage("Point with no longitude or latitude."));
}
double latitudeValue;
double longitudeValue;
try {
latitudeValue = Double.parseDouble(latitude);
longitudeValue = Double.parseDouble(longitude);
} catch (NumberFormatException e) {
throw new SAXException(
createErrorMessage("Unable to parse latitude/longitude: "
+ latitude + "/" + longitude), e
);
}
location = createNewLocation(latitudeValue, longitudeValue, -1L);
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
LOGGER.debug("End element is {}, uri {}", localName, uri);
if (localName.equals(TAG_WAYPOINT)) {
onWaypointEnd();
return;
}
if (!isInTrackElement) {
content = null;
return;
}
if (localName.equals(TAG_TRACK)) {
onTrackElementEnd();
isInTrackElement = false;
trackChildDepth = 0;
} else if (localName.equals(TAG_NAME)) {
// we are only interested in the first level name element
if (trackChildDepth == 1) {
onNameElementEnd();
}
} else if (localName.equals(TAG_DESCRIPTION)) {
// we are only interested in the first level description element
if (trackChildDepth == 1) {
onDescriptionElementEnd();
}
} else if (localName.equals(TAG_TRACK_SEGMENT)) {
onTrackSegmentElementEnd();
} else if (localName.equals(TAG_TRACK_POINT)) {
onTrackPointElementEnd();
} else if (localName.equals(TAG_ALTITUDE)) {
onAltitudeElementEnd();
} else if (localName.equals(TAG_TIME)) {
onTimeElementEnd();
}
trackChildDepth--;
// reset element content
content = null;
}
private void onWaypointEnd() throws SAXException {
LOGGER.debug("Waypoint done.");
persistLocation();
}
private void persistLocation() throws SAXException {
LOGGER.debug("Saving location {}", location);
if (!isValidLocation(location)) {
throw new SAXException(
createErrorMessage("Invalid location detected: " + location));
}
// insert into cache
locations.add(new ApproximateLocation(location));
lastLocationInSegment = location;
location = null;
}
@Override
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
/**
* On track element start.
*/
private void onTrackElementStart() {
}
/**
* On track element end.
*/
private void onTrackElementEnd() {
}
/**
* On name element end.
*/
private void onNameElementEnd() {
// NO-OP
}
/**
* On description element end.
*/
private void onDescriptionElementEnd() {
// NO-OP
}
/**
* On track segment start.
*/
private void onTrackSegmentElementStart() {
location = null;
lastLocationInSegment = null;
}
/**
* On track segment element end.
*/
private void onTrackSegmentElementEnd() {
// Nothing needs to be done
}
/**
* On track point element start.
*
* @param attributes the attributes
*/
private void onTrackPointElementStart(Attributes attributes)
throws SAXException {
if (location != null) {
throw new SAXException(
createErrorMessage("Found a track point inside another one."));
}
String latitude = attributes.getValue(ATT_LAT);
String longitude = attributes.getValue(ATT_LON);
if (latitude == null || longitude == null) {
throw new SAXException(
createErrorMessage("Point with no longitude or latitude."));
}
double latitudeValue;
double longitudeValue;
try {
latitudeValue = Double.parseDouble(latitude);
longitudeValue = Double.parseDouble(longitude);
} catch (NumberFormatException e) {
throw new SAXException(
createErrorMessage("Unable to parse latitude/longitude: "
+ latitude + "/" + longitude), e
);
}
location = createNewLocation(latitudeValue, longitudeValue, -1L);
}
/**
* On track point element end.
*/
private void onTrackPointElementEnd() throws SAXException {
persistLocation();
}
/**
* On altitude element end.
*/
private void onAltitudeElementEnd() throws SAXException {
if (location == null || content == null) {
return;
}
try {
location.setAltitude(Double.parseDouble(content));
} catch (NumberFormatException e) {
throw new SAXException(
createErrorMessage("Unable to parse altitude: " + content),
e);
}
}
/**
* On time element end. Sets location time and doing additional calculations as this is the last
* value required for the location. Also sets the start time for the trip statistics builder as
* there is no start time in the track root element.
*/
private void onTimeElementEnd() throws SAXException {
if (location == null || content == null) {
return;
}
// Parse the time
long time;
try {
time = StringUtils.getTime(content.trim());
} catch (IllegalArgumentException e) {
throw new SAXException(createErrorMessage("Unable to parse time: "
+ content), e);
}
location.setTime(time);
// Calculate derived attributes from previous point
if (lastLocationInSegment != null
&& lastLocationInSegment.getTime() != 0) {
long timeDifference = time - lastLocationInSegment.getTime();
// check for negative time change
if (timeDifference <= 0) {
LOGGER.warn("Time difference not positive.");
} else {
/*
* We don't have a speed and bearing in GPX, make something up from the last two
* points. GPS points tend to have some inherent imprecision, speed and bearing will
* likely be off, so the statistics for things like max speed will also be off.
*/
float speed = lastLocationInSegment.distanceTo(location)
* 1000.0f / timeDifference;
location.setSpeed(speed);
}
location.setBearing(lastLocationInSegment.bearingTo(location));
}
}
/**
* Creates a new location
*
* @param latitude location latitude
* @param longitude location longitude
* @param time location time
*/
private Location createNewLocation(double latitude, double longitude,
long time) {
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLatitude(latitude);
loc.setLongitude(longitude);
loc.setAltitude(0.0f);
loc.setTime(time);
loc.removeAccuracy();
loc.removeBearing();
loc.removeSpeed();
return loc;
}
/**
* Creates an error message.
*
* @param message the message
*/
private String createErrorMessage(String message) {
return String.format(Locale.US,
"Parsing error at line: %d column: %d. %s",
locator.getLineNumber(), locator.getColumnNumber(), message);
}
// =================== utils
/**
* Test if a given GeoPoint is valid, i.e. within physical bounds.
*
* @param latLng the point to be tested
* @return true, if it is a physical location on earth.
*/
public static boolean isValidGeoPoint(LatLng latLng) {
return Math.abs(latLng.latitude) < 90
&& Math.abs(latLng.longitude) <= 180;
}
/**
* Checks if a given location is a valid (i.e. physically possible) location on Earth. Note: The
* special separator locations (which have latitude = 100) will not qualify as valid. Neither
* will locations with lat=0 and lng=0 as these are most likely "bad" measurements which often
* cause trouble.
*
* @param location the location to test
* @return true if the location is a valid location.
*/
public static boolean isValidLocation(Location location) {
return location != null && Math.abs(location.getLatitude()) <= 90
&& Math.abs(location.getLongitude()) <= 180;
}
public List<ApproximateLocation> getLocations() {
return locations;
}
}
| unchiujar/Umbra | src/main/java/org/unchiujar/umbra2/io/GpxImporter.java | 4,038 | /**
* On track element end.
*/ | block_comment | nl | /*******************************************************************************
* This file is part of Umbra.
*
* Umbra 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.
*
* Umbra 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 Umbra. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (c) 2011 Vasile Jureschi <[email protected]>.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
*
* http://www.gnu.org/licenses/gpl-3.0.html
*
* Contributors:
* Vasile Jureschi <[email protected]> - initial API and implementation
* Yen-Liang, Shen - Simplified Chinese and Traditional Chinese translations
******************************************************************************/
package org.unchiujar.umbra2.io;
import android.location.Location;
import android.location.LocationManager;
import com.google.android.gms.maps.model.LatLng;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unchiujar.umbra2.location.ApproximateLocation;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
/**
* Imports GPX file.
*
* @author Leif Hendrik Wilden
* @author Steffen Horlacher
* @author Rodrigo Damazio
* @author Vasile Jureschi
*/
public class GpxImporter extends DefaultHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GpxImporter.class);
// GPX tag names and attributes
private static final String TAG_ALTITUDE = "ele";
private static final String TAG_DESCRIPTION = "desc";
private static final String TAG_NAME = "name";
private static final String TAG_TIME = "time";
private static final String TAG_TRACK = "trk";
private static final String TAG_TRACK_POINT = "trkpt";
// <wpt lat="51.31488000" lon="6.714700000">
private static final String TAG_WAYPOINT = "wpt";
private static final Object TAG_TRACK_SEGMENT = "trkseg";
private static final String ATT_LAT = "lat";
private static final String ATT_LON = "lon";
// The SAX locator to get the current line information
private Locator locator;
// The current element content
private String content;
// True if if we're inside a track's xml element
private boolean isInTrackElement = false;
// The current child depth for the current track
private int trackChildDepth = 0;
// The current location
private Location location;
// The last location in the current segment
private Location lastLocationInSegment;
private static List<ApproximateLocation> locations = new LinkedList<ApproximateLocation>();
/**
* Reads GPS tracks from a GPX file and writes tracks and their coordinates to the database.
*
* @param inputStream the input stream for the GPX file
*/
public static List<ApproximateLocation> importGPXFile(InputStream inputStream) throws ParserConfigurationException,
SAXException, IOException {
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
SAXParser saxParser = saxParserFactory.newSAXParser();
GpxImporter gpxImporter = new GpxImporter();
long start = System.currentTimeMillis();
saxParser.parse(inputStream, gpxImporter);
long end = System.currentTimeMillis();
LOGGER.debug("Total import time: " + (end - start) + "ms");
return locations;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
String newContent = new String(ch, start, length);
if (content == null) {
content = newContent;
} else {
/*
* In 99% of the cases, a single call to this method will be made for each sequence of
* characters we're interested in, so we'll rarely be concatenating strings, thus not
* justifying the use of a StringBuilder.
*/
content += newContent;
}
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
if (isInTrackElement) {
trackChildDepth++;
if (localName.equals(TAG_TRACK)) {
throw new SAXException(
createErrorMessage("Invalid GPX. Already inside a track."));
} else if (localName.equals(TAG_TRACK_SEGMENT)) {
onTrackSegmentElementStart();
} else if (localName.equals(TAG_TRACK_POINT)) {
onTrackPointElementStart(attributes);
}
} else if (localName.equals(TAG_TRACK)) {
isInTrackElement = true;
trackChildDepth = 0;
onTrackElementStart();
} else if (localName.equals(TAG_WAYPOINT)) {
LOGGER.debug("Waypoint element found with attributes {}", attributes);
onWaypointStart(attributes);
}
}
private void onWaypointStart(Attributes attributes) throws SAXException {
String latitude = attributes.getValue(ATT_LAT);
String longitude = attributes.getValue(ATT_LON);
if (latitude == null || longitude == null) {
throw new SAXException(
createErrorMessage("Point with no longitude or latitude."));
}
double latitudeValue;
double longitudeValue;
try {
latitudeValue = Double.parseDouble(latitude);
longitudeValue = Double.parseDouble(longitude);
} catch (NumberFormatException e) {
throw new SAXException(
createErrorMessage("Unable to parse latitude/longitude: "
+ latitude + "/" + longitude), e
);
}
location = createNewLocation(latitudeValue, longitudeValue, -1L);
}
@Override
public void endElement(String uri, String localName, String name)
throws SAXException {
LOGGER.debug("End element is {}, uri {}", localName, uri);
if (localName.equals(TAG_WAYPOINT)) {
onWaypointEnd();
return;
}
if (!isInTrackElement) {
content = null;
return;
}
if (localName.equals(TAG_TRACK)) {
onTrackElementEnd();
isInTrackElement = false;
trackChildDepth = 0;
} else if (localName.equals(TAG_NAME)) {
// we are only interested in the first level name element
if (trackChildDepth == 1) {
onNameElementEnd();
}
} else if (localName.equals(TAG_DESCRIPTION)) {
// we are only interested in the first level description element
if (trackChildDepth == 1) {
onDescriptionElementEnd();
}
} else if (localName.equals(TAG_TRACK_SEGMENT)) {
onTrackSegmentElementEnd();
} else if (localName.equals(TAG_TRACK_POINT)) {
onTrackPointElementEnd();
} else if (localName.equals(TAG_ALTITUDE)) {
onAltitudeElementEnd();
} else if (localName.equals(TAG_TIME)) {
onTimeElementEnd();
}
trackChildDepth--;
// reset element content
content = null;
}
private void onWaypointEnd() throws SAXException {
LOGGER.debug("Waypoint done.");
persistLocation();
}
private void persistLocation() throws SAXException {
LOGGER.debug("Saving location {}", location);
if (!isValidLocation(location)) {
throw new SAXException(
createErrorMessage("Invalid location detected: " + location));
}
// insert into cache
locations.add(new ApproximateLocation(location));
lastLocationInSegment = location;
location = null;
}
@Override
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
/**
* On track element start.
*/
private void onTrackElementStart() {
}
/**
* On track element<SUF>*/
private void onTrackElementEnd() {
}
/**
* On name element end.
*/
private void onNameElementEnd() {
// NO-OP
}
/**
* On description element end.
*/
private void onDescriptionElementEnd() {
// NO-OP
}
/**
* On track segment start.
*/
private void onTrackSegmentElementStart() {
location = null;
lastLocationInSegment = null;
}
/**
* On track segment element end.
*/
private void onTrackSegmentElementEnd() {
// Nothing needs to be done
}
/**
* On track point element start.
*
* @param attributes the attributes
*/
private void onTrackPointElementStart(Attributes attributes)
throws SAXException {
if (location != null) {
throw new SAXException(
createErrorMessage("Found a track point inside another one."));
}
String latitude = attributes.getValue(ATT_LAT);
String longitude = attributes.getValue(ATT_LON);
if (latitude == null || longitude == null) {
throw new SAXException(
createErrorMessage("Point with no longitude or latitude."));
}
double latitudeValue;
double longitudeValue;
try {
latitudeValue = Double.parseDouble(latitude);
longitudeValue = Double.parseDouble(longitude);
} catch (NumberFormatException e) {
throw new SAXException(
createErrorMessage("Unable to parse latitude/longitude: "
+ latitude + "/" + longitude), e
);
}
location = createNewLocation(latitudeValue, longitudeValue, -1L);
}
/**
* On track point element end.
*/
private void onTrackPointElementEnd() throws SAXException {
persistLocation();
}
/**
* On altitude element end.
*/
private void onAltitudeElementEnd() throws SAXException {
if (location == null || content == null) {
return;
}
try {
location.setAltitude(Double.parseDouble(content));
} catch (NumberFormatException e) {
throw new SAXException(
createErrorMessage("Unable to parse altitude: " + content),
e);
}
}
/**
* On time element end. Sets location time and doing additional calculations as this is the last
* value required for the location. Also sets the start time for the trip statistics builder as
* there is no start time in the track root element.
*/
private void onTimeElementEnd() throws SAXException {
if (location == null || content == null) {
return;
}
// Parse the time
long time;
try {
time = StringUtils.getTime(content.trim());
} catch (IllegalArgumentException e) {
throw new SAXException(createErrorMessage("Unable to parse time: "
+ content), e);
}
location.setTime(time);
// Calculate derived attributes from previous point
if (lastLocationInSegment != null
&& lastLocationInSegment.getTime() != 0) {
long timeDifference = time - lastLocationInSegment.getTime();
// check for negative time change
if (timeDifference <= 0) {
LOGGER.warn("Time difference not positive.");
} else {
/*
* We don't have a speed and bearing in GPX, make something up from the last two
* points. GPS points tend to have some inherent imprecision, speed and bearing will
* likely be off, so the statistics for things like max speed will also be off.
*/
float speed = lastLocationInSegment.distanceTo(location)
* 1000.0f / timeDifference;
location.setSpeed(speed);
}
location.setBearing(lastLocationInSegment.bearingTo(location));
}
}
/**
* Creates a new location
*
* @param latitude location latitude
* @param longitude location longitude
* @param time location time
*/
private Location createNewLocation(double latitude, double longitude,
long time) {
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLatitude(latitude);
loc.setLongitude(longitude);
loc.setAltitude(0.0f);
loc.setTime(time);
loc.removeAccuracy();
loc.removeBearing();
loc.removeSpeed();
return loc;
}
/**
* Creates an error message.
*
* @param message the message
*/
private String createErrorMessage(String message) {
return String.format(Locale.US,
"Parsing error at line: %d column: %d. %s",
locator.getLineNumber(), locator.getColumnNumber(), message);
}
// =================== utils
/**
* Test if a given GeoPoint is valid, i.e. within physical bounds.
*
* @param latLng the point to be tested
* @return true, if it is a physical location on earth.
*/
public static boolean isValidGeoPoint(LatLng latLng) {
return Math.abs(latLng.latitude) < 90
&& Math.abs(latLng.longitude) <= 180;
}
/**
* Checks if a given location is a valid (i.e. physically possible) location on Earth. Note: The
* special separator locations (which have latitude = 100) will not qualify as valid. Neither
* will locations with lat=0 and lng=0 as these are most likely "bad" measurements which often
* cause trouble.
*
* @param location the location to test
* @return true if the location is a valid location.
*/
public static boolean isValidLocation(Location location) {
return location != null && Math.abs(location.getLatitude()) <= 90
&& Math.abs(location.getLongitude()) <= 180;
}
public List<ApproximateLocation> getLocations() {
return locations;
}
}
|