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
153113_18
/* * Copyright (c) 2010, 2024, Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * - Neither the name of Oracle Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY 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 com.javafx.experiments.shape3d; import java.util.Arrays; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ArrayChangeListener; import javafx.collections.ObservableFloatArray; import javafx.scene.Parent; import javafx.scene.paint.Material; import javafx.scene.shape.CullFace; import javafx.scene.shape.DrawMode; import javafx.scene.shape.MeshView; import javafx.scene.shape.TriangleMesh; import com.javafx.experiments.shape3d.SubdivisionMesh.BoundaryMode; import com.javafx.experiments.shape3d.SubdivisionMesh.MapBorderMode; /** * A MeshView node for Polygon Meshes */ public class PolygonMeshView extends Parent { private static final boolean DEBUG = false; private final MeshView meshView = new MeshView(); private TriangleMesh triangleMesh = new TriangleMesh(); // this is null if no subdivision is happening (i.e. subdivisionLevel = 0); private SubdivisionMesh subdivisionMesh; private final ArrayChangeListener<ObservableFloatArray> meshPointsListener = (t, bln, i, i1) -> { pointsDirty = true; updateMesh(); }; private final ArrayChangeListener<ObservableFloatArray> meshTexCoordListener = (t, bln, i, i1) -> { texCoordsDirty = true; updateMesh(); }; private boolean pointsDirty = true; private boolean pointsSizeDirty = true; private boolean texCoordsDirty = true; private boolean facesDirty = true; // ========================================================================= // PROPERTIES /** * Specifies the 3D mesh data of this {@code MeshView}. * * @defaultValue null */ private ObjectProperty<PolygonMesh> meshProperty; public PolygonMesh getMesh() { return meshProperty().get(); } public void setMesh(PolygonMesh mesh) { meshProperty().set(mesh);} public ObjectProperty<PolygonMesh> meshProperty() { if (meshProperty == null) { meshProperty = new SimpleObjectProperty<PolygonMesh>(); meshProperty.addListener((observable, oldValue, newValue) -> { if (oldValue != null) { oldValue.getPoints().removeListener(meshPointsListener); oldValue.getPoints().removeListener(meshTexCoordListener); } meshProperty.set(newValue); pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = true; updateMesh(); if (newValue != null) { newValue.getPoints().addListener(meshPointsListener); newValue.getTexCoords().addListener(meshTexCoordListener); } }); } return meshProperty; } /** * Defines the drawMode this {@code Shape3D}. * * @defaultValue DrawMode.FILL */ private ObjectProperty<DrawMode> drawMode; public final void setDrawMode(DrawMode value) { drawModeProperty().set(value); } public final DrawMode getDrawMode() { return drawMode == null ? DrawMode.FILL : drawMode.get(); } public final ObjectProperty<DrawMode> drawModeProperty() { if (drawMode == null) { drawMode = new SimpleObjectProperty<DrawMode>(PolygonMeshView.this, "drawMode", DrawMode.FILL) { @Override protected void invalidated() { meshView.setDrawMode(get()); pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = true; updateMesh(); } }; } return drawMode; } /** * Defines the drawMode this {@code Shape3D}. * * @defaultValue CullFace.BACK */ private ObjectProperty<CullFace> cullFace; public final void setCullFace(CullFace value) { cullFaceProperty().set(value); } public final CullFace getCullFace() { return cullFace == null ? CullFace.BACK : cullFace.get(); } public final ObjectProperty<CullFace> cullFaceProperty() { if (cullFace == null) { cullFace = new SimpleObjectProperty<CullFace>(PolygonMeshView.this, "cullFace", CullFace.BACK) { @Override protected void invalidated() { meshView.setCullFace(get()); } }; } return cullFace; } /** * Defines the material this {@code Shape3D}. * The default material is null. If {@code Material} is null, a PhongMaterial * with a diffuse color of Color.LIGHTGRAY is used for rendering. * * @defaultValue null */ private ObjectProperty<Material> materialProperty = new SimpleObjectProperty<Material>(); public Material getMaterial() { return materialProperty.get(); } public void setMaterial(Material material) { materialProperty.set(material); } public ObjectProperty<Material> materialProperty() { return materialProperty; } /** * Number of iterations of Catmull Clark subdivision to apply to the mesh * * @defaultValue 0 */ private SimpleIntegerProperty subdivisionLevelProperty; public void setSubdivisionLevel(int subdivisionLevel) { subdivisionLevelProperty().set(subdivisionLevel); } public int getSubdivisionLevel() { return subdivisionLevelProperty == null ? 0 : subdivisionLevelProperty.get(); } public SimpleIntegerProperty subdivisionLevelProperty() { if (subdivisionLevelProperty == null) { subdivisionLevelProperty = new SimpleIntegerProperty(getSubdivisionLevel()) { @Override protected void invalidated() { // create SubdivisionMesh if subdivisionLevel is greater than 0 if ((getSubdivisionLevel() > 0) && (subdivisionMesh == null)) { subdivisionMesh = new SubdivisionMesh(getMesh(), getSubdivisionLevel(), getBoundaryMode(), getMapBorderMode()); subdivisionMesh.getOriginalMesh().getPoints().addListener((t, bln, i, i1) -> subdivisionMesh.update()); setMesh(subdivisionMesh); } if (subdivisionMesh != null) { subdivisionMesh.setSubdivisionLevel(getSubdivisionLevel()); subdivisionMesh.update(); } pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = true; updateMesh(); } }; } return subdivisionLevelProperty; } /** * Texture mapping boundary rule for Catmull Clark subdivision applied to the mesh * * @defaultValue BoundaryMode.CREASE_EDGES */ private SimpleObjectProperty<BoundaryMode> boundaryMode; public void setBoundaryMode(BoundaryMode boundaryMode) { boundaryModeProperty().set(boundaryMode); } public BoundaryMode getBoundaryMode() { return boundaryMode == null ? BoundaryMode.CREASE_EDGES : boundaryMode.get(); } public SimpleObjectProperty<BoundaryMode> boundaryModeProperty() { if (boundaryMode == null) { boundaryMode = new SimpleObjectProperty<BoundaryMode>(getBoundaryMode()) { @Override protected void invalidated() { if (subdivisionMesh != null) { subdivisionMesh.setBoundaryMode(getBoundaryMode()); subdivisionMesh.update(); } pointsDirty = true; updateMesh(); } }; } return boundaryMode; } /** * Texture mapping smoothness option for Catmull Clark subdivision applied to the mesh * * @defaultValue MapBorderMode.NOT_SMOOTH */ private SimpleObjectProperty<MapBorderMode> mapBorderMode; public void setMapBorderMode(MapBorderMode mapBorderMode) { mapBorderModeProperty().set(mapBorderMode); } public MapBorderMode getMapBorderMode() { return mapBorderMode == null ? MapBorderMode.NOT_SMOOTH : mapBorderMode.get(); } public SimpleObjectProperty<MapBorderMode> mapBorderModeProperty() { if (mapBorderMode == null) { mapBorderMode = new SimpleObjectProperty<MapBorderMode>(getMapBorderMode()) { @Override protected void invalidated() { if (subdivisionMesh != null) { subdivisionMesh.setMapBorderMode(getMapBorderMode()); subdivisionMesh.update(); } texCoordsDirty = true; updateMesh(); } }; } return mapBorderMode; } // ========================================================================= // CONSTRUCTORS public PolygonMeshView() { meshView.materialProperty().bind(materialProperty()); getChildren().add(meshView); } public PolygonMeshView(PolygonMesh mesh) { this(); setMesh(mesh); } // ========================================================================= // PRIVATE METHODS private void updateMesh() { PolygonMesh pmesh = getMesh(); if (pmesh == null || pmesh.faces == null) { triangleMesh = new TriangleMesh(); meshView.setMesh(triangleMesh); return; } final int pointElementSize = triangleMesh.getPointElementSize(); final int faceElementSize = triangleMesh.getFaceElementSize(); final boolean isWireframe = getDrawMode() == DrawMode.LINE; if (DEBUG) System.out.println("UPDATE MESH -- "+(isWireframe?"WIREFRAME":"SOLID")); final int numOfPoints = pmesh.getPoints().size() / pointElementSize; if (DEBUG) System.out.println("numOfPoints = " + numOfPoints); if(isWireframe) { // The current triangleMesh implementation gives buggy behavior when the size of faces are shrunken // Create a new TriangleMesh as a work around // [JIRA] (RT-31178) if (texCoordsDirty || facesDirty || pointsSizeDirty) { triangleMesh = new TriangleMesh(); pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = true; // to fill in the new triangle mesh } if (facesDirty) { facesDirty = false; // create faces for each edge int [] facesArray = new int [pmesh.getNumEdgesInFaces() * faceElementSize]; int facesInd = 0; int pointsInd = pmesh.getPoints().size(); for(int[] face: pmesh.faces) { if (DEBUG) System.out.println("face.length = " + (face.length/2)+" -- "+Arrays.toString(face)); int lastPointIndex = face[face.length-2]; if (DEBUG) System.out.println(" lastPointIndex = " + lastPointIndex); for (int p=0;p<face.length;p+=2) { int pointIndex = face[p]; if (DEBUG) System.out.println(" connecting point["+lastPointIndex+"] to point[" + pointIndex+"]"); facesArray[facesInd++] = lastPointIndex; facesArray[facesInd++] = 0; facesArray[facesInd++] = pointIndex; facesArray[facesInd++] = 0; facesArray[facesInd++] = pointsInd / pointElementSize; facesArray[facesInd++] = 0; if (DEBUG) System.out.println(" facesInd = " + facesInd); pointsInd += pointElementSize; lastPointIndex = pointIndex; } } triangleMesh.getFaces().setAll(facesArray); triangleMesh.getFaceSmoothingGroups().clear(); } if (texCoordsDirty) { texCoordsDirty = false; // set simple texCoords for wireframe triangleMesh.getTexCoords().setAll(0,0); } if (pointsDirty) { pointsDirty = false; // create points and copy over points to the first part of the array float [] pointsArray = new float [pmesh.getPoints().size() + pmesh.getNumEdgesInFaces()*3]; pmesh.getPoints().copyTo(0, pointsArray, 0, pmesh.getPoints().size()); // add point for each edge int pointsInd = pmesh.getPoints().size(); for(int[] face: pmesh.faces) { int lastPointIndex = face[face.length-2]; for (int p=0;p<face.length;p+=2) { int pointIndex = face[p]; // get start and end point final float x1 = pointsArray[lastPointIndex * pointElementSize]; final float y1 = pointsArray[lastPointIndex * pointElementSize + 1]; final float z1 = pointsArray[lastPointIndex * pointElementSize + 2]; final float x2 = pointsArray[pointIndex * pointElementSize]; final float y2 = pointsArray[pointIndex * pointElementSize + 1]; final float z2 = pointsArray[pointIndex * pointElementSize + 2]; final float distance = Math.abs(distanceBetweenPoints(x1,y1,z1,x2,y2,z2)); final float offset = distance/1000; // add new point pointsArray[pointsInd++] = x2 + offset; pointsArray[pointsInd++] = y2 + offset; pointsArray[pointsInd++] = z2 + offset; lastPointIndex = pointIndex; } } triangleMesh.getPoints().setAll(pointsArray); } } else { // The current triangleMesh implementation gives buggy behavior when the size of faces are shrunken // Create a new TriangleMesh as a work around // [JIRA] (RT-31178) if (texCoordsDirty || facesDirty || pointsSizeDirty) { triangleMesh = new TriangleMesh(); pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = true; // to fill in the new triangle mesh } if (facesDirty) { facesDirty = false; // create faces and break into triangles final int numOfFacesBefore = pmesh.faces.length; final int numOfFacesAfter = pmesh.getNumEdgesInFaces() - 2*numOfFacesBefore; int [] facesArray = new int [numOfFacesAfter * faceElementSize]; int [] smoothingGroupsArray = new int [numOfFacesAfter]; int facesInd = 0; for(int f = 0; f < pmesh.faces.length; f++) { int[] face = pmesh.faces[f]; int currentSmoothGroup = pmesh.getFaceSmoothingGroups().get(f); if (DEBUG) System.out.println("face.length = " + face.length+" -- "+Arrays.toString(face)); int firstPointIndex = face[0]; int firstTexIndex = face[1]; int lastPointIndex = face[2]; int lastTexIndex = face[3]; for (int p=4;p<face.length;p+=2) { int pointIndex = face[p]; int texIndex = face[p+1]; facesArray[facesInd * faceElementSize] = firstPointIndex; facesArray[facesInd * faceElementSize + 1] = firstTexIndex; facesArray[facesInd * faceElementSize + 2] = lastPointIndex; facesArray[facesInd * faceElementSize + 3] = lastTexIndex; facesArray[facesInd * faceElementSize + 4] = pointIndex; facesArray[facesInd * faceElementSize + 5] = texIndex; smoothingGroupsArray[facesInd] = currentSmoothGroup; facesInd++; lastPointIndex = pointIndex; lastTexIndex = texIndex; } } triangleMesh.getFaces().setAll(facesArray); triangleMesh.getFaceSmoothingGroups().setAll(smoothingGroupsArray); } if (texCoordsDirty) { texCoordsDirty = false; triangleMesh.getTexCoords().setAll(pmesh.getTexCoords()); } if (pointsDirty) { pointsDirty = false; triangleMesh.getPoints().setAll(pmesh.getPoints()); } } if (DEBUG) System.out.println("CREATING TRIANGLE MESH"); if (DEBUG) System.out.println(" points = "+Arrays.toString(((TriangleMesh) meshView.getMesh()).getPoints().toArray(null))); if (DEBUG) System.out.println(" texCoords = "+Arrays.toString(((TriangleMesh) meshView.getMesh()).getTexCoords().toArray(null))); if (DEBUG) System.out.println(" faces = "+Arrays.toString(((TriangleMesh) meshView.getMesh()).getFaces().toArray(null))); if (meshView.getMesh() != triangleMesh) { meshView.setMesh(triangleMesh); } pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = false; } private float distanceBetweenPoints(float x1, float y1, float z1, float x2, float y2, float z2) { return (float)Math.sqrt( Math.pow(z2 - z1,2) + Math.pow(x2 - x1,2) + Math.pow(y2 - y1,2)); } }
openjdk/jfx
apps/samples/3DViewer/src/main/java/com/javafx/experiments/shape3d/PolygonMeshView.java
5,163
// get start and end point
line_comment
nl
/* * Copyright (c) 2010, 2024, Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * - Neither the name of Oracle Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY 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 com.javafx.experiments.shape3d; import java.util.Arrays; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ArrayChangeListener; import javafx.collections.ObservableFloatArray; import javafx.scene.Parent; import javafx.scene.paint.Material; import javafx.scene.shape.CullFace; import javafx.scene.shape.DrawMode; import javafx.scene.shape.MeshView; import javafx.scene.shape.TriangleMesh; import com.javafx.experiments.shape3d.SubdivisionMesh.BoundaryMode; import com.javafx.experiments.shape3d.SubdivisionMesh.MapBorderMode; /** * A MeshView node for Polygon Meshes */ public class PolygonMeshView extends Parent { private static final boolean DEBUG = false; private final MeshView meshView = new MeshView(); private TriangleMesh triangleMesh = new TriangleMesh(); // this is null if no subdivision is happening (i.e. subdivisionLevel = 0); private SubdivisionMesh subdivisionMesh; private final ArrayChangeListener<ObservableFloatArray> meshPointsListener = (t, bln, i, i1) -> { pointsDirty = true; updateMesh(); }; private final ArrayChangeListener<ObservableFloatArray> meshTexCoordListener = (t, bln, i, i1) -> { texCoordsDirty = true; updateMesh(); }; private boolean pointsDirty = true; private boolean pointsSizeDirty = true; private boolean texCoordsDirty = true; private boolean facesDirty = true; // ========================================================================= // PROPERTIES /** * Specifies the 3D mesh data of this {@code MeshView}. * * @defaultValue null */ private ObjectProperty<PolygonMesh> meshProperty; public PolygonMesh getMesh() { return meshProperty().get(); } public void setMesh(PolygonMesh mesh) { meshProperty().set(mesh);} public ObjectProperty<PolygonMesh> meshProperty() { if (meshProperty == null) { meshProperty = new SimpleObjectProperty<PolygonMesh>(); meshProperty.addListener((observable, oldValue, newValue) -> { if (oldValue != null) { oldValue.getPoints().removeListener(meshPointsListener); oldValue.getPoints().removeListener(meshTexCoordListener); } meshProperty.set(newValue); pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = true; updateMesh(); if (newValue != null) { newValue.getPoints().addListener(meshPointsListener); newValue.getTexCoords().addListener(meshTexCoordListener); } }); } return meshProperty; } /** * Defines the drawMode this {@code Shape3D}. * * @defaultValue DrawMode.FILL */ private ObjectProperty<DrawMode> drawMode; public final void setDrawMode(DrawMode value) { drawModeProperty().set(value); } public final DrawMode getDrawMode() { return drawMode == null ? DrawMode.FILL : drawMode.get(); } public final ObjectProperty<DrawMode> drawModeProperty() { if (drawMode == null) { drawMode = new SimpleObjectProperty<DrawMode>(PolygonMeshView.this, "drawMode", DrawMode.FILL) { @Override protected void invalidated() { meshView.setDrawMode(get()); pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = true; updateMesh(); } }; } return drawMode; } /** * Defines the drawMode this {@code Shape3D}. * * @defaultValue CullFace.BACK */ private ObjectProperty<CullFace> cullFace; public final void setCullFace(CullFace value) { cullFaceProperty().set(value); } public final CullFace getCullFace() { return cullFace == null ? CullFace.BACK : cullFace.get(); } public final ObjectProperty<CullFace> cullFaceProperty() { if (cullFace == null) { cullFace = new SimpleObjectProperty<CullFace>(PolygonMeshView.this, "cullFace", CullFace.BACK) { @Override protected void invalidated() { meshView.setCullFace(get()); } }; } return cullFace; } /** * Defines the material this {@code Shape3D}. * The default material is null. If {@code Material} is null, a PhongMaterial * with a diffuse color of Color.LIGHTGRAY is used for rendering. * * @defaultValue null */ private ObjectProperty<Material> materialProperty = new SimpleObjectProperty<Material>(); public Material getMaterial() { return materialProperty.get(); } public void setMaterial(Material material) { materialProperty.set(material); } public ObjectProperty<Material> materialProperty() { return materialProperty; } /** * Number of iterations of Catmull Clark subdivision to apply to the mesh * * @defaultValue 0 */ private SimpleIntegerProperty subdivisionLevelProperty; public void setSubdivisionLevel(int subdivisionLevel) { subdivisionLevelProperty().set(subdivisionLevel); } public int getSubdivisionLevel() { return subdivisionLevelProperty == null ? 0 : subdivisionLevelProperty.get(); } public SimpleIntegerProperty subdivisionLevelProperty() { if (subdivisionLevelProperty == null) { subdivisionLevelProperty = new SimpleIntegerProperty(getSubdivisionLevel()) { @Override protected void invalidated() { // create SubdivisionMesh if subdivisionLevel is greater than 0 if ((getSubdivisionLevel() > 0) && (subdivisionMesh == null)) { subdivisionMesh = new SubdivisionMesh(getMesh(), getSubdivisionLevel(), getBoundaryMode(), getMapBorderMode()); subdivisionMesh.getOriginalMesh().getPoints().addListener((t, bln, i, i1) -> subdivisionMesh.update()); setMesh(subdivisionMesh); } if (subdivisionMesh != null) { subdivisionMesh.setSubdivisionLevel(getSubdivisionLevel()); subdivisionMesh.update(); } pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = true; updateMesh(); } }; } return subdivisionLevelProperty; } /** * Texture mapping boundary rule for Catmull Clark subdivision applied to the mesh * * @defaultValue BoundaryMode.CREASE_EDGES */ private SimpleObjectProperty<BoundaryMode> boundaryMode; public void setBoundaryMode(BoundaryMode boundaryMode) { boundaryModeProperty().set(boundaryMode); } public BoundaryMode getBoundaryMode() { return boundaryMode == null ? BoundaryMode.CREASE_EDGES : boundaryMode.get(); } public SimpleObjectProperty<BoundaryMode> boundaryModeProperty() { if (boundaryMode == null) { boundaryMode = new SimpleObjectProperty<BoundaryMode>(getBoundaryMode()) { @Override protected void invalidated() { if (subdivisionMesh != null) { subdivisionMesh.setBoundaryMode(getBoundaryMode()); subdivisionMesh.update(); } pointsDirty = true; updateMesh(); } }; } return boundaryMode; } /** * Texture mapping smoothness option for Catmull Clark subdivision applied to the mesh * * @defaultValue MapBorderMode.NOT_SMOOTH */ private SimpleObjectProperty<MapBorderMode> mapBorderMode; public void setMapBorderMode(MapBorderMode mapBorderMode) { mapBorderModeProperty().set(mapBorderMode); } public MapBorderMode getMapBorderMode() { return mapBorderMode == null ? MapBorderMode.NOT_SMOOTH : mapBorderMode.get(); } public SimpleObjectProperty<MapBorderMode> mapBorderModeProperty() { if (mapBorderMode == null) { mapBorderMode = new SimpleObjectProperty<MapBorderMode>(getMapBorderMode()) { @Override protected void invalidated() { if (subdivisionMesh != null) { subdivisionMesh.setMapBorderMode(getMapBorderMode()); subdivisionMesh.update(); } texCoordsDirty = true; updateMesh(); } }; } return mapBorderMode; } // ========================================================================= // CONSTRUCTORS public PolygonMeshView() { meshView.materialProperty().bind(materialProperty()); getChildren().add(meshView); } public PolygonMeshView(PolygonMesh mesh) { this(); setMesh(mesh); } // ========================================================================= // PRIVATE METHODS private void updateMesh() { PolygonMesh pmesh = getMesh(); if (pmesh == null || pmesh.faces == null) { triangleMesh = new TriangleMesh(); meshView.setMesh(triangleMesh); return; } final int pointElementSize = triangleMesh.getPointElementSize(); final int faceElementSize = triangleMesh.getFaceElementSize(); final boolean isWireframe = getDrawMode() == DrawMode.LINE; if (DEBUG) System.out.println("UPDATE MESH -- "+(isWireframe?"WIREFRAME":"SOLID")); final int numOfPoints = pmesh.getPoints().size() / pointElementSize; if (DEBUG) System.out.println("numOfPoints = " + numOfPoints); if(isWireframe) { // The current triangleMesh implementation gives buggy behavior when the size of faces are shrunken // Create a new TriangleMesh as a work around // [JIRA] (RT-31178) if (texCoordsDirty || facesDirty || pointsSizeDirty) { triangleMesh = new TriangleMesh(); pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = true; // to fill in the new triangle mesh } if (facesDirty) { facesDirty = false; // create faces for each edge int [] facesArray = new int [pmesh.getNumEdgesInFaces() * faceElementSize]; int facesInd = 0; int pointsInd = pmesh.getPoints().size(); for(int[] face: pmesh.faces) { if (DEBUG) System.out.println("face.length = " + (face.length/2)+" -- "+Arrays.toString(face)); int lastPointIndex = face[face.length-2]; if (DEBUG) System.out.println(" lastPointIndex = " + lastPointIndex); for (int p=0;p<face.length;p+=2) { int pointIndex = face[p]; if (DEBUG) System.out.println(" connecting point["+lastPointIndex+"] to point[" + pointIndex+"]"); facesArray[facesInd++] = lastPointIndex; facesArray[facesInd++] = 0; facesArray[facesInd++] = pointIndex; facesArray[facesInd++] = 0; facesArray[facesInd++] = pointsInd / pointElementSize; facesArray[facesInd++] = 0; if (DEBUG) System.out.println(" facesInd = " + facesInd); pointsInd += pointElementSize; lastPointIndex = pointIndex; } } triangleMesh.getFaces().setAll(facesArray); triangleMesh.getFaceSmoothingGroups().clear(); } if (texCoordsDirty) { texCoordsDirty = false; // set simple texCoords for wireframe triangleMesh.getTexCoords().setAll(0,0); } if (pointsDirty) { pointsDirty = false; // create points and copy over points to the first part of the array float [] pointsArray = new float [pmesh.getPoints().size() + pmesh.getNumEdgesInFaces()*3]; pmesh.getPoints().copyTo(0, pointsArray, 0, pmesh.getPoints().size()); // add point for each edge int pointsInd = pmesh.getPoints().size(); for(int[] face: pmesh.faces) { int lastPointIndex = face[face.length-2]; for (int p=0;p<face.length;p+=2) { int pointIndex = face[p]; // get start<SUF> final float x1 = pointsArray[lastPointIndex * pointElementSize]; final float y1 = pointsArray[lastPointIndex * pointElementSize + 1]; final float z1 = pointsArray[lastPointIndex * pointElementSize + 2]; final float x2 = pointsArray[pointIndex * pointElementSize]; final float y2 = pointsArray[pointIndex * pointElementSize + 1]; final float z2 = pointsArray[pointIndex * pointElementSize + 2]; final float distance = Math.abs(distanceBetweenPoints(x1,y1,z1,x2,y2,z2)); final float offset = distance/1000; // add new point pointsArray[pointsInd++] = x2 + offset; pointsArray[pointsInd++] = y2 + offset; pointsArray[pointsInd++] = z2 + offset; lastPointIndex = pointIndex; } } triangleMesh.getPoints().setAll(pointsArray); } } else { // The current triangleMesh implementation gives buggy behavior when the size of faces are shrunken // Create a new TriangleMesh as a work around // [JIRA] (RT-31178) if (texCoordsDirty || facesDirty || pointsSizeDirty) { triangleMesh = new TriangleMesh(); pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = true; // to fill in the new triangle mesh } if (facesDirty) { facesDirty = false; // create faces and break into triangles final int numOfFacesBefore = pmesh.faces.length; final int numOfFacesAfter = pmesh.getNumEdgesInFaces() - 2*numOfFacesBefore; int [] facesArray = new int [numOfFacesAfter * faceElementSize]; int [] smoothingGroupsArray = new int [numOfFacesAfter]; int facesInd = 0; for(int f = 0; f < pmesh.faces.length; f++) { int[] face = pmesh.faces[f]; int currentSmoothGroup = pmesh.getFaceSmoothingGroups().get(f); if (DEBUG) System.out.println("face.length = " + face.length+" -- "+Arrays.toString(face)); int firstPointIndex = face[0]; int firstTexIndex = face[1]; int lastPointIndex = face[2]; int lastTexIndex = face[3]; for (int p=4;p<face.length;p+=2) { int pointIndex = face[p]; int texIndex = face[p+1]; facesArray[facesInd * faceElementSize] = firstPointIndex; facesArray[facesInd * faceElementSize + 1] = firstTexIndex; facesArray[facesInd * faceElementSize + 2] = lastPointIndex; facesArray[facesInd * faceElementSize + 3] = lastTexIndex; facesArray[facesInd * faceElementSize + 4] = pointIndex; facesArray[facesInd * faceElementSize + 5] = texIndex; smoothingGroupsArray[facesInd] = currentSmoothGroup; facesInd++; lastPointIndex = pointIndex; lastTexIndex = texIndex; } } triangleMesh.getFaces().setAll(facesArray); triangleMesh.getFaceSmoothingGroups().setAll(smoothingGroupsArray); } if (texCoordsDirty) { texCoordsDirty = false; triangleMesh.getTexCoords().setAll(pmesh.getTexCoords()); } if (pointsDirty) { pointsDirty = false; triangleMesh.getPoints().setAll(pmesh.getPoints()); } } if (DEBUG) System.out.println("CREATING TRIANGLE MESH"); if (DEBUG) System.out.println(" points = "+Arrays.toString(((TriangleMesh) meshView.getMesh()).getPoints().toArray(null))); if (DEBUG) System.out.println(" texCoords = "+Arrays.toString(((TriangleMesh) meshView.getMesh()).getTexCoords().toArray(null))); if (DEBUG) System.out.println(" faces = "+Arrays.toString(((TriangleMesh) meshView.getMesh()).getFaces().toArray(null))); if (meshView.getMesh() != triangleMesh) { meshView.setMesh(triangleMesh); } pointsDirty = pointsSizeDirty = texCoordsDirty = facesDirty = false; } private float distanceBetweenPoints(float x1, float y1, float z1, float x2, float y2, float z2) { return (float)Math.sqrt( Math.pow(z2 - z1,2) + Math.pow(x2 - x1,2) + Math.pow(y2 - y1,2)); } }
9368_16
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * 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. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import org.locationtech.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. //String name = worldFileName(); InputStream is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List<String> lines = FileUtil.getContents(is); if (is != null) { is.close(); } double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = lines.get(i); tags[i] = Double.parseDouble(line); } setEnvelope(tags); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { super.readRasterfile(); try { // Get access to the tags and geokeys. // First, try to get the TIFF directory Object dir = src.getProperty("tiff.directory"); if (dir instanceof GeoTIFFDirectory) { parseGeoTIFFDirectory((GeoTIFFDirectory)dir); // still with us? must have succeeded return; } } catch (Exception e) { e.printStackTrace(); } // Embedded geotiff tags have not been found. // Try to find a world file. try { parseWorldFile(); // still with us? must have succeeded return; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Neither geotiff tags nor valid worldfile found for file '"+fileName+"'.\n" + MSG_GENERAL); } }
openjump-gis/openjump
src/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
2,186
// setCoorModel_tiepointLT(new Coordinate(0, 0));
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * 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. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import java.awt.geom.AffineTransform; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.geotiff.image.jai.GeoTIFFDescriptor; import org.geotiff.image.jai.GeoTIFFDirectory; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFField; import org.locationtech.jts.geom.Coordinate; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoTIFFRaster extends GeoReferencedRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; boolean hoPatch = false; /** * Called by Java2XML */ public GeoTIFFRaster(String imageFileLocation) throws Exception { super(imageFileLocation); fileName = imageFileLocation; registerWithJAI(); readRasterfile(); } private void registerWithJAI() { // Register the GeoTIFF descriptor with JAI. GeoTIFFDescriptor.register(); } private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception { // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new Exception( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0,5)); // setCoorModel_tiepointLT(new Coordinate(0,<SUF> // setAffineTransformation(new AffineTransform(tags)); setEnvelope(tags); } else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new Exception("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); } } /** * @return filename of the tiff worldfile */ private String worldFileName() { int posDot = fileName.lastIndexOf('.'); if (posDot == -1) { posDot = fileName.length(); } return fileName.substring(0, posDot) + ".tfw"; } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. //String name = worldFileName(); InputStream is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List<String> lines = FileUtil.getContents(is); if (is != null) { is.close(); } double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = lines.get(i); tags[i] = Double.parseDouble(line); } setEnvelope(tags); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); setAffineTransformation(new AffineTransform(tags)); } protected void readRasterfile() throws Exception { super.readRasterfile(); try { // Get access to the tags and geokeys. // First, try to get the TIFF directory Object dir = src.getProperty("tiff.directory"); if (dir instanceof GeoTIFFDirectory) { parseGeoTIFFDirectory((GeoTIFFDirectory)dir); // still with us? must have succeeded return; } } catch (Exception e) { e.printStackTrace(); } // Embedded geotiff tags have not been found. // Try to find a world file. try { parseWorldFile(); // still with us? must have succeeded return; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Neither geotiff tags nor valid worldfile found for file '"+fileName+"'.\n" + MSG_GENERAL); } }
213137_18
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * 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. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; Envelope envModel_image; Envelope envModel_image_backup; Coordinate coorRasterTiff_tiepointLT; Coordinate coorModel_tiepointLT; private double dblModelUnitsPerRasterUnit_X; private double dblModelUnitsPerRasterUnit_Y; // boolean hoPatch = false; /** * Called by Java2XML * * @throws ReferencedImageException */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); fileName = imageFileLocation; readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem acessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new // Coordinate(-0.5, // -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); Logger.debug("gtiff trans: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else { // Get the number of modeltiepoints // int numModelTiePoints = fieldModelTiePoints.getCount() / 6; // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } Logger.debug("gtiff tiepoints found."); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { // if (!GDALUtilities.isGDALAvailable()) // throw new // ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper // left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper // left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("wf: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri; try { uri = new URI(imageFileLocation); } catch (URISyntaxException e) { throw new ReferencedImageException(e); } // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } //if (false) try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } double[] tags = new double[6]; tags[0] = 1; // pixel size in x // direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the // y-direction tags[4] = 0; // x-coordinate of the // center of the upper // left pixel tags[5] = 0; // y-coordinate of the // center of the upper // left pixel setEnvelope(tags); Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(this.getClass().getName() + ".no-geo-reference-found"); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); AffineTransform transform = new AffineTransform(tags); double scaleX = Math.abs(transform.getScaleX()); double scaleY = Math.abs(transform.getScaleY()); setDblModelUnitsPerRasterUnit_X(scaleX); setDblModelUnitsPerRasterUnit_Y(scaleY); Point2D rasterLT = new Point2D.Double(src.getMinX(), src.getMinY()); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); setCoorRasterTiff_tiepointLT(new Coordinate(rasterLT.getX(), rasterLT.getY())); setCoorModel_tiepointLT(new Coordinate(modelLT.getX(), modelLT.getY())); setEnvelope(); } void setEnvelope() { Coordinate coorRaster_imageLB = new Coordinate(coorRasterTiff_tiepointLT.x, src.getHeight(), 0); Coordinate coorRaster_imageRT = new Coordinate(src.getWidth(), 0, 0); Coordinate coorModel_imageLB = rasterToModelSpace(coorRaster_imageLB); Coordinate coorModel_imageRT = rasterToModelSpace(coorRaster_imageRT); envModel_image = new Envelope(coorModel_imageLB, coorModel_imageRT); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = coorModel_tiepointLT.x + (coorRaster.x - coorRasterTiff_tiepointLT.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = coorModel_tiepointLT.y - (coorRaster.y + coorRasterTiff_tiepointLT.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @param coordinate */ private void setCoorModel_tiepointLT(Coordinate coordinate) { coorModel_tiepointLT = coordinate; // setEnvelope(); } /** * @param coordinate */ private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { coorRasterTiff_tiepointLT = coordinate; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_X(double d) { dblModelUnitsPerRasterUnit_X = d; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_Y(double d) { dblModelUnitsPerRasterUnit_Y = d; // setEnvelope(); } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { return coorModel_tiepointLT; } /** * @return coordinate of left-top corner in the raster coordinate system */ public Coordinate getCoorRasterTiff_tiepointLT() { return coorRasterTiff_tiepointLT; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); setDblModelUnitsPerRasterUnit_X(xUnit); double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); setDblModelUnitsPerRasterUnit_Y(yUnit); // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
openjump-gis/openjump-migration
src/com/vividsolutions/jump/workbench/imagery/geoimg/GeoReferencedRaster.java
5,475
// int numModelTiePoints = fieldModelTiePoints.getCount() / 6;
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geoimg; /* * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI * for visualizing and manipulating spatial features with geometry and attributes. * * Copyright (C) 2003 Vivid Solutions * * 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. * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ import it.geosolutions.imageio.core.CoreCommonImageMetadata; import it.geosolutions.imageio.gdalframework.GDALImageReaderSpi; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.List; import javax.imageio.ImageReader; import javax.imageio.metadata.IIOMetadata; import javax.imageio.spi.ImageReaderSpi; import javax.media.jai.RenderedOp; import org.libtiff.jai.codec.XTIFF; import org.libtiff.jai.codec.XTIFFDirectory; import org.libtiff.jai.codec.XTIFFField; import com.sun.media.jai.codec.SeekableStream; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Envelope; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import com.vividsolutions.jump.feature.Feature; import com.vividsolutions.jump.util.FileUtil; import com.vividsolutions.jump.workbench.JUMPWorkbench; import com.vividsolutions.jump.workbench.Logger; import com.vividsolutions.jump.workbench.imagery.ReferencedImageException; import com.vividsolutions.jump.workbench.imagery.graphic.WorldFile; public class GeoReferencedRaster extends GeoRaster { private final String MSG_GENERAL = "This is not a valid GeoTIFF file."; String fileName; Envelope envModel_image; Envelope envModel_image_backup; Coordinate coorRasterTiff_tiepointLT; Coordinate coorModel_tiepointLT; private double dblModelUnitsPerRasterUnit_X; private double dblModelUnitsPerRasterUnit_Y; // boolean hoPatch = false; /** * Called by Java2XML * * @throws ReferencedImageException */ public GeoReferencedRaster(String location) throws ReferencedImageException { this(location, null); } public GeoReferencedRaster(String location, Object reader) throws ReferencedImageException { super(location, reader); fileName = imageFileLocation; readRasterfile(); } private void parseGeoTIFFDirectory(URI uri) throws ReferencedImageException { XTIFFDirectory dir = null; InputStream input = null; ReferencedImageException re = null; try { input = createInputStream(uri); SeekableStream ss = SeekableStream.wrapInputStream(input, true); dir = XTIFFDirectory.create(ss, 0); } catch (IllegalArgumentException e) { re = new ReferencedImageException("probably no tiff image: " + e.getMessage()); } catch (IOException e) { re = new ReferencedImageException("problem acessing tiff image: " + e.getMessage()); } finally { // clean up disposeInput(input); if (re != null) throw re; } // Find the ModelTiePoints field XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS); if (fieldModelTiePoints == null) { // try to read geotransform (tranformation matrix) information, // if tiepoints are not used to georeference this image. // These parameters are the same as those in a tfw file. XTIFFField fieldModelGeoTransform = dir .getField(XTIFF.TIFFTAG_GEO_TRANS_MATRIX); if (fieldModelGeoTransform == null) { throw new ReferencedImageException( "Missing tiepoints-tag and tranformation matrix-tag parameters in file.\n" + MSG_GENERAL); } double[] tags = new double[6]; tags[0] = fieldModelGeoTransform.getAsDouble(0); // pixel size in x // direction tags[1] = fieldModelGeoTransform.getAsDouble(1); // rotation about y-axis tags[2] = fieldModelGeoTransform.getAsDouble(4); // rotation about x-axis tags[3] = fieldModelGeoTransform.getAsDouble(5); // pixel size in the // y-direction tags[4] = fieldModelGeoTransform.getAsDouble(3); // x-coordinate of the // center of the upper // left pixel tags[5] = fieldModelGeoTransform.getAsDouble(7); // y-coordinate of the // center of the upper // left pixel // setCoorRasterTiff_tiepointLT(new // Coordinate(-0.5, // -0,5)); // setCoorModel_tiepointLT(new Coordinate(0, 0)); // setAffineTransformation(new AffineTransform(tags)); Logger.debug("gtiff trans: " + Arrays.toString(tags)); setEnvelope(tags); } // use the tiepoints as defined else { // Get the number of modeltiepoints // int numModelTiePoints<SUF> // ToDo: alleen numModelTiePoints == 1 ondersteunen. // Map the modeltiepoints from raster to model space // Read the tiepoints setCoorRasterTiff_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0)); setCoorModel_tiepointLT(new Coordinate( fieldModelTiePoints.getAsDouble(3), fieldModelTiePoints.getAsDouble(4), 0)); setEnvelope(); // Find the ModelPixelScale field XTIFFField fieldModelPixelScale = dir .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE); if (fieldModelPixelScale == null) { // TODO: fieldModelTiePoints may contains GCP that could be exploited to // georeference the image throw new ReferencedImageException("Missing pixelscale-tag in file." + "\n" + MSG_GENERAL); } Logger.debug("gtiff tiepoints found."); setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0)); setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1)); setEnvelope(); } } private void parseGDALMetaData(URI uri) throws ReferencedImageException { // if (!GDALUtilities.isGDALAvailable()) // throw new // ReferencedImageException("no gdal metadata available because gdal is not properly loaded."); // gdal geo info List<ImageReaderSpi> readers; Exception ex = null; Object input = null; try { readers = listValidImageIOReaders(uri, GDALImageReaderSpi.class); for (ImageReaderSpi readerSpi : readers) { input = createInput(uri, readerSpi); ImageReader reader = readerSpi.createReaderInstance(); IIOMetadata metadata = null; // try with file or stream try { reader.setInput(input); metadata = reader.getImageMetadata(0); } catch (IllegalArgumentException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } catch (RuntimeException e) { Logger.debug("fail " + readerSpi + "/" + input + " -> " + e); } finally { reader.dispose(); disposeInput(input); } if (!(metadata instanceof CoreCommonImageMetadata)) { Logger.info("Unexpected error! Metadata should be an instance of the expected class: GDALCommonIIOImageMetadata."); continue; } double[] geoTransform = ((CoreCommonImageMetadata) metadata) .getGeoTransformation(); Logger.debug("successfully retrieved gdal geo metadata: " + Arrays.toString(geoTransform)); // check transform array for validity if (geoTransform == null || (geoTransform.length != 6)) continue; // settle for the first result double[] tags = new double[6]; tags[0] = geoTransform[1]; // pixel size in x direction tags[1] = geoTransform[4]; // rotation about y-axis tags[2] = geoTransform[2]; // rotation about x-axis tags[3] = geoTransform[5]; // pixel size in the y-direction tags[4] = geoTransform[0]; // x-coordinate of the center of the upper // left pixel tags[5] = geoTransform[3]; // y-coordinate of the center of the upper // left pixel setEnvelope(tags); // still with us? must have succeeded return; } } catch (IOException e1) { ex = e1; } throw new ReferencedImageException("no gdal metadata retrieved.", ex); } private void parseWorldFile() throws IOException { // Get the name of the tiff worldfile. // String name = worldFileName(); InputStream is = null; try { is = WorldFile.find(fileName); // Read the tags from the tiff worldfile. List lines = FileUtil.getContents(is); double[] tags = new double[6]; for (int i = 0; i < 6; i++) { String line = (String) lines.get(i); tags[i] = Double.parseDouble(line); } Logger.debug("wf: " + Arrays.toString(tags)); setEnvelope(tags); } catch (IOException e) { throw e; } finally { FileUtil.close(is); } } protected void readRasterfile() throws ReferencedImageException { super.readRasterfile(); URI uri; try { uri = new URI(imageFileLocation); } catch (URISyntaxException e) { throw new ReferencedImageException(e); } // Try to find and parse world file. try { parseWorldFile(); // still with us? must have succeeded Logger.debug("Worldfile geo metadata fetched."); return; } catch (IOException e) { Logger.debug("Worldfile geo metadata unavailable: " + e.getMessage()); } //if (false) try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGDALMetaData(uri); // still with us? must have succeeded Logger.debug("GDAL geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("GDAL geo metadata unavailable: " + e.getMessage()); } try { // Get access to the tags and geokeys. // First, try to get the TIFF directory // Object dir = src.getProperty("tiff.directory"); parseGeoTIFFDirectory(uri); // still with us? must have succeeded Logger.debug("XTIFF geo metadata fetched."); return; } catch (ReferencedImageException e) { Logger.debug("XTIFF geo metadata unavailable: " + e.getMessage()); } double[] tags = new double[6]; tags[0] = 1; // pixel size in x // direction tags[1] = 0; // rotation about y-axis tags[2] = 0; // rotation about x-axis tags[3] = -1;// pixel size in the // y-direction tags[4] = 0; // x-coordinate of the // center of the upper // left pixel tags[5] = 0; // y-coordinate of the // center of the upper // left pixel setEnvelope(tags); Logger.info("No georeference found! Will use default 0,0 placement."); JUMPWorkbench.getInstance().getFrame() .warnUser(this.getClass().getName() + ".no-geo-reference-found"); } private void setEnvelope(double[] tags) { setCoorRasterTiff_tiepointLT(new Coordinate(-0.5, -0.5)); setCoorModel_tiepointLT(new Coordinate(0, 0)); AffineTransform transform = new AffineTransform(tags); double scaleX = Math.abs(transform.getScaleX()); double scaleY = Math.abs(transform.getScaleY()); setDblModelUnitsPerRasterUnit_X(scaleX); setDblModelUnitsPerRasterUnit_Y(scaleY); Point2D rasterLT = new Point2D.Double(src.getMinX(), src.getMinY()); Point2D modelLT = new Point2D.Double(); transform.transform(rasterLT, modelLT); setCoorRasterTiff_tiepointLT(new Coordinate(rasterLT.getX(), rasterLT.getY())); setCoorModel_tiepointLT(new Coordinate(modelLT.getX(), modelLT.getY())); setEnvelope(); } void setEnvelope() { Coordinate coorRaster_imageLB = new Coordinate(coorRasterTiff_tiepointLT.x, src.getHeight(), 0); Coordinate coorRaster_imageRT = new Coordinate(src.getWidth(), 0, 0); Coordinate coorModel_imageLB = rasterToModelSpace(coorRaster_imageLB); Coordinate coorModel_imageRT = rasterToModelSpace(coorRaster_imageRT); envModel_image = new Envelope(coorModel_imageLB, coorModel_imageRT); // backup original envelope envModel_image_backup = envModel_image; } /** * Convert a coordinate from rasterspace to modelspace. * * @param coorRaster * coordinate in rasterspace * @return coordinate in modelspace */ private Coordinate rasterToModelSpace(Coordinate coorRaster) { Coordinate coorModel = new Coordinate(); coorModel.x = coorModel_tiepointLT.x + (coorRaster.x - coorRasterTiff_tiepointLT.x) * dblModelUnitsPerRasterUnit_X; coorModel.y = coorModel_tiepointLT.y - (coorRaster.y + coorRasterTiff_tiepointLT.y) * dblModelUnitsPerRasterUnit_Y; coorModel.z = 0; return coorModel; } public Envelope getEnvelope() { return envModel_image; } public Envelope getOriginalEnvelope() { return envModel_image_backup; } /** * @param coordinate */ private void setCoorModel_tiepointLT(Coordinate coordinate) { coorModel_tiepointLT = coordinate; // setEnvelope(); } /** * @param coordinate */ private void setCoorRasterTiff_tiepointLT(Coordinate coordinate) { coorRasterTiff_tiepointLT = coordinate; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_X(double d) { dblModelUnitsPerRasterUnit_X = d; // setEnvelope(); } /** * @param d */ private void setDblModelUnitsPerRasterUnit_Y(double d) { dblModelUnitsPerRasterUnit_Y = d; // setEnvelope(); } /** * @return coordinate of left-top corner in the model coordinate system */ public Coordinate getCoorModel_tiepointLT() { return coorModel_tiepointLT; } /** * @return coordinate of left-top corner in the raster coordinate system */ public Coordinate getCoorRasterTiff_tiepointLT() { return coorRasterTiff_tiepointLT; } /** * @return number of model units per raster unit along X axis */ public double getDblModelUnitsPerRasterUnit_X() { return dblModelUnitsPerRasterUnit_X; } /** * @return number of model units per raster unit along Y axis */ public double getDblModelUnitsPerRasterUnit_Y() { return dblModelUnitsPerRasterUnit_Y; } public Envelope getEnvelope(Feature f) throws ReferencedImageException { // geometry might be modified, if so let's rereference our image ;) Geometry g; if (f instanceof Feature && (g = f.getGeometry()) != null) { Geometry rasterEnv = (new GeometryFactory()) .toGeometry(getOriginalEnvelope()); if (!rasterEnv.equals(g)) { Envelope envGeom = g.getEnvelopeInternal(); // set new scale values RenderedOp img = super.getImage(); double xUnit = Math.abs(envGeom.getWidth() / img.getWidth()); setDblModelUnitsPerRasterUnit_X(xUnit); double yUnit = Math.abs(envGeom.getHeight() / img.getHeight()); setDblModelUnitsPerRasterUnit_Y(yUnit); // assign&return new envelope return envModel_image = new Envelope(envGeom); } } return getOriginalEnvelope(); } }
55455_15
/********************************************************************** * Author Collin Finck * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, * see <http://www.gnu.org/licenses/>. * * [email protected] * www.jverein.de **********************************************************************/ package de.jost_net.JVerein.server; import java.rmi.RemoteException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import de.jost_net.JVerein.Einstellungen; import de.willuhn.datasource.rmi.DBIterator; import de.willuhn.datasource.rmi.DBObject; import de.willuhn.datasource.rmi.ObjectNotFoundException; /** * Cache fuer oft geladene Fachobjekte. */ class Cache { private final static de.willuhn.jameica.system.Settings settings = new de.willuhn.jameica.system.Settings( Cache.class); private static int timeout = 0; // Enthaelt alle Caches. private final static Map<Class<?>, Cache> caches = new HashMap<>(); // Der konkrete Cache private Map<String, DBObject> data = new HashMap<>(); private Class<? extends DBObject> type = null; private long validTo = 0; static { settings.setStoreWhenRead(false); // Das Timeout betraegt nur 10 Sekunden. Mehr brauchen wir nicht. // Es geht ja nur darum, dass z.Bsp. beim Laden der Umsaetze die // immer wieder gleichen zugeordneten Konten oder Umsatz-Kategorien // nicht dauernd neu geladen sondern kurz zwischengespeichert werden // Das Timeout generell wird benoetigt, wenn mehrere Hibiscus-Instanzen // sich eine Datenbank teilen. Andernfalls wuerde Hibiscus die // Aenderungen der anderen nicht mitkriegen timeout = settings.getInt("timeout.seconds", 10); } /** * ct. */ private Cache() { touch(); } /** * Aktualisiert das Verfallsdatum des Caches. */ private void touch() { this.validTo = System.currentTimeMillis() + (timeout * 1000); } /** * Liefert den Cache fuer den genannten Typ. * * @param type * der Typ. * @param init * true, wenn der Cache bei der Erzeugung automatisch befuellt werden * soll. * @return der Cache. * @throws RemoteException */ static Cache get(Class<? extends DBObject> type, boolean init) throws RemoteException { Cache cache = caches.get(type); if (cache != null) { if (cache.validTo < System.currentTimeMillis()) { caches.remove(type); cache = null; // Cache wegwerfen } else { cache.touch(); // Verfallsdatum aktualisieren } } // Cache erzeugen und mit Daten fuellen if (cache == null) { cache = new Cache(); cache.type = type; if (init) { // Daten in den Cache laden DBIterator<?> list = Einstellungen.getDBService().createList(type); while (list.hasNext()) { DBObject o = (DBObject) list.next(); cache.data.put(o.getID(), o); } } caches.put(type, cache); } return cache; } /** * Liefert ein Objekt aus dem Cache. * * @param id * die ID des Objektes. * @return das Objekt oder NULL, wenn es nicht existiert. * @throws RemoteException */ DBObject get(Object id) throws RemoteException { if (id == null) return null; String s = id.toString(); DBObject value = data.get(s); if (value == null) { // Noch nicht im Cache. Vielleicht koennen wir es noch laden try { value = Einstellungen.getDBService().createObject(type, s); put(value); // tun wir gleich in den Cache } catch (ObjectNotFoundException one) { // Objekt existiert nicht mehr } } return value; } /** * Speichert ein Objekt im Cache. * * @param object * das zu speichernde Objekt. * @throws RemoteException */ void put(DBObject object) throws RemoteException { if (object == null) return; data.put(object.getID(), object); } /** * Entfernt ein Objekt aus dem Cache. * * @param object * das zu entfernende Objekt. * @throws RemoteException */ void remove(DBObject object) throws RemoteException { if (object == null) return; data.remove(object.getID()); } /** * Liefert alle Werte aus dem Cache. * * @return Liste der Werte aus dem Cache. */ Collection<DBObject> values() { return data.values(); } }
openjverein/jverein
src/de/jost_net/JVerein/server/Cache.java
1,638
// Daten in den Cache laden
line_comment
nl
/********************************************************************** * Author Collin Finck * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, * see <http://www.gnu.org/licenses/>. * * [email protected] * www.jverein.de **********************************************************************/ package de.jost_net.JVerein.server; import java.rmi.RemoteException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import de.jost_net.JVerein.Einstellungen; import de.willuhn.datasource.rmi.DBIterator; import de.willuhn.datasource.rmi.DBObject; import de.willuhn.datasource.rmi.ObjectNotFoundException; /** * Cache fuer oft geladene Fachobjekte. */ class Cache { private final static de.willuhn.jameica.system.Settings settings = new de.willuhn.jameica.system.Settings( Cache.class); private static int timeout = 0; // Enthaelt alle Caches. private final static Map<Class<?>, Cache> caches = new HashMap<>(); // Der konkrete Cache private Map<String, DBObject> data = new HashMap<>(); private Class<? extends DBObject> type = null; private long validTo = 0; static { settings.setStoreWhenRead(false); // Das Timeout betraegt nur 10 Sekunden. Mehr brauchen wir nicht. // Es geht ja nur darum, dass z.Bsp. beim Laden der Umsaetze die // immer wieder gleichen zugeordneten Konten oder Umsatz-Kategorien // nicht dauernd neu geladen sondern kurz zwischengespeichert werden // Das Timeout generell wird benoetigt, wenn mehrere Hibiscus-Instanzen // sich eine Datenbank teilen. Andernfalls wuerde Hibiscus die // Aenderungen der anderen nicht mitkriegen timeout = settings.getInt("timeout.seconds", 10); } /** * ct. */ private Cache() { touch(); } /** * Aktualisiert das Verfallsdatum des Caches. */ private void touch() { this.validTo = System.currentTimeMillis() + (timeout * 1000); } /** * Liefert den Cache fuer den genannten Typ. * * @param type * der Typ. * @param init * true, wenn der Cache bei der Erzeugung automatisch befuellt werden * soll. * @return der Cache. * @throws RemoteException */ static Cache get(Class<? extends DBObject> type, boolean init) throws RemoteException { Cache cache = caches.get(type); if (cache != null) { if (cache.validTo < System.currentTimeMillis()) { caches.remove(type); cache = null; // Cache wegwerfen } else { cache.touch(); // Verfallsdatum aktualisieren } } // Cache erzeugen und mit Daten fuellen if (cache == null) { cache = new Cache(); cache.type = type; if (init) { // Daten in<SUF> DBIterator<?> list = Einstellungen.getDBService().createList(type); while (list.hasNext()) { DBObject o = (DBObject) list.next(); cache.data.put(o.getID(), o); } } caches.put(type, cache); } return cache; } /** * Liefert ein Objekt aus dem Cache. * * @param id * die ID des Objektes. * @return das Objekt oder NULL, wenn es nicht existiert. * @throws RemoteException */ DBObject get(Object id) throws RemoteException { if (id == null) return null; String s = id.toString(); DBObject value = data.get(s); if (value == null) { // Noch nicht im Cache. Vielleicht koennen wir es noch laden try { value = Einstellungen.getDBService().createObject(type, s); put(value); // tun wir gleich in den Cache } catch (ObjectNotFoundException one) { // Objekt existiert nicht mehr } } return value; } /** * Speichert ein Objekt im Cache. * * @param object * das zu speichernde Objekt. * @throws RemoteException */ void put(DBObject object) throws RemoteException { if (object == null) return; data.put(object.getID(), object); } /** * Entfernt ein Objekt aus dem Cache. * * @param object * das zu entfernende Objekt. * @throws RemoteException */ void remove(DBObject object) throws RemoteException { if (object == null) return; data.remove(object.getID()); } /** * Liefert alle Werte aus dem Cache. * * @return Liste der Werte aus dem Cache. */ Collection<DBObject> values() { return data.values(); } }
74245_1
/* * This file is part of the OpenLink Software Virtuoso Open-Source (VOS) * project. * * Copyright (C) 1998-2013 OpenLink Software * * This project 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; only version 2 of the License, dated June 1991. * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * */ package testsuite; import java.sql.*; import javax.sql.*; import java.util.*; import javax.naming.*; import virtuoso.jdbc4.*; public class TestDataSource { public static Context ctx; public static DataSource registerConnection () throws Exception { VirtuosoDataSource ds = new VirtuosoDataSource (); ds.setDescription ("test datasource"); ds.setServerName ("localhost"); ds.setPortNumber (1111); ds.setUser ("dba"); ds.setPassword ("dba"); ds.setDatabaseName ("DS1"); // ctx.bind ("jdbc/virt_ds1", ds); return ds; } public static void main(String args[]) { VirtuosoDataSource ds; try { /* Hashtable env = new Hashtable(); env.put (Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); env.put(Context.PROVIDER_URL, "file:///home/kgeorge/jndi"); ctx = new InitialContext(env); */ System.out.println("----------------------- Test of datasource ---------------------"); System.out.print("Register connection jdbc/virt_ds1"); // registerConnection (); ds = (VirtuosoDataSource) registerConnection (); System.out.println(" PASSED"); System.out.print("Establish connection through jdbc/virt_ds1 datasource"); // VirtuosoDataSource ds = (VirtuosoDataSource) ctx.lookup ("jdbc/virt_ds1"); Connection c = ds.getConnection (); System.out.println(" PASSED"); System.exit (0); } catch(Exception e) { System.out.println(" FAILED"); e.printStackTrace(); System.exit(-1); } } }
openlink/virtuoso-opensource
libsrc/JDBCDriverType4/testsuite_4.0/TestDataSource.java
772
// ctx.bind ("jdbc/virt_ds1", ds);
line_comment
nl
/* * This file is part of the OpenLink Software Virtuoso Open-Source (VOS) * project. * * Copyright (C) 1998-2013 OpenLink Software * * This project 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; only version 2 of the License, dated June 1991. * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * */ package testsuite; import java.sql.*; import javax.sql.*; import java.util.*; import javax.naming.*; import virtuoso.jdbc4.*; public class TestDataSource { public static Context ctx; public static DataSource registerConnection () throws Exception { VirtuosoDataSource ds = new VirtuosoDataSource (); ds.setDescription ("test datasource"); ds.setServerName ("localhost"); ds.setPortNumber (1111); ds.setUser ("dba"); ds.setPassword ("dba"); ds.setDatabaseName ("DS1"); // ctx.bind ("jdbc/virt_ds1",<SUF> return ds; } public static void main(String args[]) { VirtuosoDataSource ds; try { /* Hashtable env = new Hashtable(); env.put (Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); env.put(Context.PROVIDER_URL, "file:///home/kgeorge/jndi"); ctx = new InitialContext(env); */ System.out.println("----------------------- Test of datasource ---------------------"); System.out.print("Register connection jdbc/virt_ds1"); // registerConnection (); ds = (VirtuosoDataSource) registerConnection (); System.out.println(" PASSED"); System.out.print("Establish connection through jdbc/virt_ds1 datasource"); // VirtuosoDataSource ds = (VirtuosoDataSource) ctx.lookup ("jdbc/virt_ds1"); Connection c = ds.getConnection (); System.out.println(" PASSED"); System.exit (0); } catch(Exception e) { System.out.println(" FAILED"); e.printStackTrace(); System.exit(-1); } } }
80502_13
/** * 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/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.api.db; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.openmrs.Concept; import org.openmrs.ConceptAnswer; import org.openmrs.ConceptAttribute; import org.openmrs.ConceptAttributeType; import org.openmrs.ConceptClass; import org.openmrs.ConceptComplex; import org.openmrs.ConceptDatatype; import org.openmrs.ConceptDescription; import org.openmrs.ConceptMap; import org.openmrs.ConceptMapType; import org.openmrs.ConceptName; import org.openmrs.ConceptNameTag; import org.openmrs.ConceptNumeric; import org.openmrs.ConceptProposal; import org.openmrs.ConceptReferenceTerm; import org.openmrs.ConceptReferenceTermMap; import org.openmrs.ConceptSearchResult; import org.openmrs.ConceptSet; import org.openmrs.ConceptSource; import org.openmrs.ConceptStopWord; import org.openmrs.Drug; import org.openmrs.DrugIngredient; import org.openmrs.api.APIException; import org.openmrs.api.ConceptService; /** * Concept-related database functions * * @see ConceptService */ public interface ConceptDAO { /** * @see org.openmrs.api.ConceptService#saveConcept(org.openmrs.Concept) */ public Concept saveConcept(Concept concept) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConcept(org.openmrs.Concept) * <strong>Should</strong> purge concept */ public void purgeConcept(Concept concept) throws DAOException; /** * Get a ConceptComplex. The Concept.getDatatype() is "Complex" and the Concept.getHandler() is * the class name for the ComplexObsHandler key associated with this ConceptComplex. * * @param conceptId * @return the ConceptComplex */ public ConceptComplex getConceptComplex(Integer conceptId); /** * @see org.openmrs.api.ConceptService#purgeDrug(org.openmrs.Drug) */ public void purgeDrug(Drug drug) throws DAOException; /** * @see org.openmrs.api.ConceptService#saveDrug(org.openmrs.Drug) */ public Drug saveDrug(Drug drug) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConcept(java.lang.Integer) */ public Concept getConcept(Integer conceptId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptName(java.lang.Integer) * @param conceptNameId * @return The ConceptName matching the specified conceptNameId */ public ConceptName getConceptName(Integer conceptNameId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConcepts(java.lang.String, boolean, boolean) */ public List<Concept> getAllConcepts(String sortBy, boolean asc, boolean includeRetired) throws DAOException; /** * Returns a list of concepts based on the search criteria * * @param name * @param loc * @param searchOnPhrase This puts wildcard characters around the concept name search criteria * @return List&lt;Concept&gt; * @throws DAOException * <strong>Should</strong> not return concepts with matching names that are voided */ public List<Concept> getConcepts(String name, Locale loc, boolean searchOnPhrase, List<ConceptClass> classes, List<ConceptDatatype> datatypes) throws DAOException; /** * @see ConceptService#getConcepts(String, List, boolean, List, List, List, List, Concept, * Integer, Integer) * @throws DAOException * <strong>Should</strong> return correct results for concept with names that contains words with more weight * <strong>Should</strong> return correct results if a concept name contains same word more than once */ public List<ConceptSearchResult> getConcepts(String phrase, List<Locale> locales, boolean includeRetired, List<ConceptClass> requireClasses, List<ConceptClass> excludeClasses, List<ConceptDatatype> requireDatatypes, List<ConceptDatatype> excludeDatatypes, Concept answersToConcept, Integer start, Integer size) throws DAOException; public Integer getCountOfConcepts(String phrase, List<Locale> locales, boolean includeRetired, List<ConceptClass> requireClasses, List<ConceptClass> excludeClasses, List<ConceptDatatype> requireDatatypes, List<ConceptDatatype> excludeDatatypes, Concept answersToConcept) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptAnswer(java.lang.Integer) */ public ConceptAnswer getConceptAnswer(Integer conceptAnswerId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getDrug(java.lang.Integer) */ public Drug getDrug(Integer drugId) throws DAOException; /** * DAO for retrieving a list of drugs based on the following criteria * * @param drugName * @param concept * @param includeRetired * @return List&lt;Drug&gt; * @throws DAOException */ public List<Drug> getDrugs(String drugName, Concept concept, boolean includeRetired) throws DAOException; /** * @see org.openmrs.api.ConceptService#getDrugs(java.lang.String) */ public List<Drug> getDrugs(String phrase) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptClass(java.lang.Integer) */ public ConceptClass getConceptClass(Integer i) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptClassByName(java.lang.String) */ public List<ConceptClass> getConceptClasses(String name) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConceptClasses(boolean) */ public List<ConceptClass> getAllConceptClasses(boolean includeRetired) throws DAOException; /** * @see org.openmrs.api.ConceptService#saveConceptClass(org.openmrs.ConceptClass) */ public ConceptClass saveConceptClass(ConceptClass cc) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConceptClass(org.openmrs.ConceptClass) */ public void purgeConceptClass(ConceptClass cc) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConceptNameTag(org.openmrs.ConceptNameTag) */ public void deleteConceptNameTag(ConceptNameTag cnt) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConceptDatatypes(boolean) */ public List<ConceptDatatype> getAllConceptDatatypes(boolean includeRetired) throws DAOException; /** * @param name * @return the {@link ConceptDatatype} that matches <em>name</em> exactly or null if one does * not exist. * @throws DAOException */ public ConceptDatatype getConceptDatatypeByName(String name) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptDatatype(java.lang.Integer) */ public ConceptDatatype getConceptDatatype(Integer i) throws DAOException; /** * @see org.openmrs.api.ConceptService#saveConceptDatatype(org.openmrs.ConceptDatatype) */ public ConceptDatatype saveConceptDatatype(ConceptDatatype cd) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConceptDatatype(org.openmrs.ConceptDatatype) */ public void purgeConceptDatatype(ConceptDatatype cd) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptSetsByConcept(org.openmrs.Concept) */ public List<ConceptSet> getConceptSetsByConcept(Concept c) throws DAOException; /** * @see org.openmrs.api.ConceptService#getSetsContainingConcept(org.openmrs.Concept) */ public List<ConceptSet> getSetsContainingConcept(Concept concept) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptNumeric(java.lang.Integer) */ public ConceptNumeric getConceptNumeric(Integer conceptId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptsByAnswer(org.openmrs.Concept) * <strong>Should</strong> return concepts for the given answer concept */ public List<Concept> getConceptsByAnswer(Concept concept) throws DAOException; /** * @see org.openmrs.api.ConceptService#getPrevConcept(org.openmrs.Concept) */ public Concept getPrevConcept(Concept c) throws DAOException; /** * @see org.openmrs.api.ConceptService#getNextConcept(org.openmrs.Concept) */ public Concept getNextConcept(Concept c) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConceptProposals(boolean) */ public List<ConceptProposal> getAllConceptProposals(boolean includeComplete) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptProposal(java.lang.Integer) */ public ConceptProposal getConceptProposal(Integer i) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptProposals(java.lang.String) */ public List<ConceptProposal> getConceptProposals(String text) throws DAOException; /** * @see org.openmrs.api.ConceptService#getProposedConcepts(java.lang.String) */ public List<Concept> getProposedConcepts(String text) throws DAOException; /** * @see org.openmrs.api.ConceptService#saveConceptProposal(org.openmrs.ConceptProposal) */ public ConceptProposal saveConceptProposal(ConceptProposal cp) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConceptProposal(org.openmrs.ConceptProposal) */ public void purgeConceptProposal(ConceptProposal cp) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptsWithDrugsInFormulary() */ public List<Concept> getConceptsWithDrugsInFormulary() throws DAOException; public ConceptNameTag saveConceptNameTag(ConceptNameTag nameTag); public ConceptNameTag getConceptNameTag(Integer i); public ConceptNameTag getConceptNameTagByName(String name); /** * @see org.openmrs.api.ConceptService#getAllConceptNameTags() */ public List<ConceptNameTag> getAllConceptNameTags(); /** * @see org.openmrs.api.ConceptService#getConceptSource(java.lang.Integer) */ public ConceptSource getConceptSource(Integer conceptSourceId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConceptSources(boolean) */ public List<ConceptSource> getAllConceptSources(boolean includeRetired) throws DAOException; /** * @see org.openmrs.api.ConceptService#saveConceptSource(org.openmrs.ConceptSource) */ public ConceptSource saveConceptSource(ConceptSource conceptSource) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConceptSource(org.openmrs.ConceptSource) */ public ConceptSource deleteConceptSource(ConceptSource cs) throws DAOException; /** * @see org.openmrs.api.ConceptService#getLocalesOfConceptNames() */ public Set<Locale> getLocalesOfConceptNames(); /** * @see ConceptService#getMaxConceptId() */ public Integer getMaxConceptId(); /** * @see org.openmrs.api.ConceptService#conceptIterator() */ public Iterator<Concept> conceptIterator(); /** * @see org.openmrs.api.ConceptService#getConceptsByMapping(java.lang.String, java.lang.String) * * @deprecated As of 2.5.0, this method has been deprecated in favor of {@link #getConceptIdsByMapping(String, String, boolean)} */ @Deprecated public List<Concept> getConceptsByMapping(String code, String sourceName, boolean includeRetired); /** * @see org.openmrs.api.ConceptService#getConceptIdsByMapping(String, String, boolean) */ public List<Integer> getConceptIdsByMapping(String code, String sourceName, boolean includeRetired); /** * @param uuid * @return concept or null */ public Concept getConceptByUuid(String uuid); /** * @param uuid * @return concept class or null */ public ConceptClass getConceptClassByUuid(String uuid); public ConceptAnswer getConceptAnswerByUuid(String uuid); public ConceptName getConceptNameByUuid(String uuid); public ConceptSet getConceptSetByUuid(String uuid); public ConceptSource getConceptSourceByUuid(String uuid); /** * @param uuid * @return concept data type or null */ public ConceptDatatype getConceptDatatypeByUuid(String uuid); /** * @param uuid * @return concept numeric or null */ public ConceptNumeric getConceptNumericByUuid(String uuid); /** * @param uuid * @return concept proposal or null */ public ConceptProposal getConceptProposalByUuid(String uuid); /** * @param uuid * @return drug or null */ public Drug getDrugByUuid(String uuid); public DrugIngredient getDrugIngredientByUuid(String uuid); public Map<Integer, String> getConceptUuids(); public ConceptDescription getConceptDescriptionByUuid(String uuid); public ConceptNameTag getConceptNameTagByUuid(String uuid); /** * @see ConceptService#getConceptMappingsToSource(ConceptSource) */ public List<ConceptMap> getConceptMapsBySource(ConceptSource conceptSource) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptSourceByName(java.lang.String) */ public ConceptSource getConceptSourceByName(String conceptSourceName) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptSourceByUniqueId(java.lang.String) */ public ConceptSource getConceptSourceByUniqueId(String uniqueId); /** * @see org.openmrs.api.ConceptService#getConceptSourceByHL7Code(java.lang.String) */ public ConceptSource getConceptSourceByHL7Code(String hl7Code); /** * Gets the value of conceptDatatype currently saved in the database for the given concept, * bypassing any caches. This is used prior to saving an concept so that we can change the obs * if need be * * @param concept for which the conceptDatatype should be fetched * @return the conceptDatatype currently in the database for this concept * <strong>Should</strong> get saved conceptDatatype from database */ public ConceptDatatype getSavedConceptDatatype(Concept concept); /** * Gets the persisted copy of the conceptName currently saved in the database for the given * conceptName, bypassing any caches. This is used prior to saving an concept so that we can * change the obs if need be or avoid breaking any obs referencing it. * * @param conceptName ConceptName to fetch from the database * @return the persisted copy of the conceptName currently saved in the database for this * conceptName */ public ConceptName getSavedConceptName(ConceptName conceptName); /** * @see org.openmrs.api.ConceptService#saveConceptStopWord(org.openmrs.ConceptStopWord) */ public ConceptStopWord saveConceptStopWord(ConceptStopWord conceptStopWord) throws DAOException; /** * @see org.openmrs.api.ConceptService#deleteConceptStopWord(Integer) */ public void deleteConceptStopWord(Integer conceptStopWordId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptStopWords(java.util.Locale) */ public List<String> getConceptStopWords(Locale locale) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConceptStopWords() */ public List<ConceptStopWord> getAllConceptStopWords(); /** * @see ConceptService#getCountOfDrugs(String, Concept, boolean, boolean, boolean) */ public Long getCountOfDrugs(String drugName, Concept concept, boolean searchOnPhrase, boolean searchDrugConceptNames, boolean includeRetired) throws DAOException; /** * @see ConceptService#getDrugs(String, Concept, boolean, boolean, boolean, Integer, Integer) */ public List<Drug> getDrugs(String drugName, Concept concept, boolean searchOnPhrase, boolean searchDrugConceptNames, boolean includeRetired, Integer start, Integer length) throws DAOException; /** * @see ConceptService#getDrugsByIngredient(Concept) */ public List<Drug> getDrugsByIngredient(Concept ingredient); /** * @see ConceptService#getConceptMapTypes(boolean, boolean) */ public List<ConceptMapType> getConceptMapTypes(boolean includeRetired, boolean includeHidden) throws DAOException; /** * @see ConceptService#getConceptMapType(Integer) */ public ConceptMapType getConceptMapType(Integer conceptMapTypeId) throws DAOException; /** * @see ConceptService#getConceptMapTypeByUuid(String) */ public ConceptMapType getConceptMapTypeByUuid(String uuid) throws DAOException; /** * @see ConceptService#getConceptMapTypeByName(String) */ public ConceptMapType getConceptMapTypeByName(String name) throws DAOException; /** * @see ConceptService#saveConceptMapType(ConceptMapType) */ public ConceptMapType saveConceptMapType(ConceptMapType conceptMapType) throws DAOException; /** * @see ConceptService#purgeConceptMapType(ConceptMapType) */ public void deleteConceptMapType(ConceptMapType conceptMapType) throws DAOException; /** * @see ConceptService#getConceptReferenceTerms(boolean) */ public List<ConceptReferenceTerm> getConceptReferenceTerms(boolean includeRetired) throws DAOException; /** * @see ConceptService#getConceptReferenceTerm(Integer) */ public ConceptReferenceTerm getConceptReferenceTerm(Integer conceptReferenceTermId) throws DAOException; /** * @see ConceptService#getConceptReferenceTermByUuid(String) */ public ConceptReferenceTerm getConceptReferenceTermByUuid(String uuid) throws DAOException; public List<ConceptReferenceTerm> getConceptReferenceTermsBySource(ConceptSource conceptSource) throws DAOException; /** * @see ConceptService#getConceptReferenceTermByName(String, ConceptSource) */ public ConceptReferenceTerm getConceptReferenceTermByName(String name, ConceptSource conceptSource) throws DAOException; /** * @see ConceptService#getConceptReferenceTermByCode(String, ConceptSource) */ public ConceptReferenceTerm getConceptReferenceTermByCode(String code, ConceptSource conceptSource) throws DAOException; /** * @see ConceptService#getConceptReferenceTermByCode(String, ConceptSource, boolean) */ public List<ConceptReferenceTerm> getConceptReferenceTermByCode(String code, ConceptSource conceptSource, boolean includeRetired) throws DAOException; /** * @see ConceptService#saveConceptReferenceTerm(ConceptReferenceTerm) */ public ConceptReferenceTerm saveConceptReferenceTerm(ConceptReferenceTerm conceptReferenceTerm) throws DAOException; /** * @see ConceptService#purgeConceptReferenceTerm(ConceptReferenceTerm) */ public void deleteConceptReferenceTerm(ConceptReferenceTerm conceptReferenceTerm) throws DAOException; /** * @see ConceptService#getCountOfConceptReferenceTerms(String, ConceptSource, boolean) */ public Long getCountOfConceptReferenceTerms(String query, ConceptSource conceptSource, boolean includeRetired) throws DAOException; /** * @see ConceptService#getConceptReferenceTerms(String, ConceptSource, Integer, Integer, * boolean) */ public List<ConceptReferenceTerm> getConceptReferenceTerms(String query, ConceptSource conceptSource, Integer start, Integer length, boolean includeRetired) throws APIException; /** * @see ConceptService#getReferenceTermMappingsTo(ConceptReferenceTerm) */ public List<ConceptReferenceTermMap> getReferenceTermMappingsTo(ConceptReferenceTerm term) throws DAOException; /** * Checks if there are any {@link ConceptReferenceTermMap}s or {@link ConceptMap}s using the * specified term * * @param term * @return true if term is in use * @throws DAOException * <strong>Should</strong> return true if a term has a conceptMap or more using it * <strong>Should</strong> return true if a term has a conceptReferenceTermMap or more using it * <strong>Should</strong> return false if a term has no maps using it */ public boolean isConceptReferenceTermInUse(ConceptReferenceTerm term) throws DAOException; /** * Checks if there are any {@link ConceptReferenceTermMap}s or {@link ConceptMap}s using the * specified mapType * * @param mapType * @return true if map type is in use * @throws DAOException * <strong>Should</strong> return true if a mapType has a conceptMap or more using it * <strong>Should</strong> return true if a mapType has a conceptReferenceTermMap or more using it * <strong>Should</strong> return false if a mapType has no maps using it */ public boolean isConceptMapTypeInUse(ConceptMapType mapType) throws DAOException; /** * @see ConceptService#getConceptsByName(String, Locale, Boolean) */ public List<Concept> getConceptsByName(String name, Locale locale, Boolean exactLocal); /** * @see ConceptService#getConceptByName(String) */ public Concept getConceptByName(String name); /** * It is in the DAO, because it must be done in the MANUAL flush mode to prevent premature * flushes in {@link ConceptService#saveConcept(Concept)}. It will be removed in 1.10 when we * have a better way to manage flush modes. * * @see ConceptService#getDefaultConceptMapType() */ public ConceptMapType getDefaultConceptMapType() throws DAOException; /** * @see ConceptService#isConceptNameDuplicate(ConceptName) */ public boolean isConceptNameDuplicate(ConceptName name); /** * @see ConceptService#getDrugs(String, java.util.Locale, boolean, boolean) */ public List<Drug> getDrugs(String searchPhrase, Locale locale, boolean exactLocale, boolean includeRetired); /** * @see org.openmrs.api.ConceptService#getDrugsByMapping(String, ConceptSource, Collection, * boolean) */ public List<Drug> getDrugsByMapping(String code, ConceptSource conceptSource, Collection<ConceptMapType> withAnyOfTheseTypes, boolean includeRetired) throws DAOException; /** * @see org.openmrs.api.ConceptService#getDrugByMapping(String, org.openmrs.ConceptSource, java.util.Collection) */ Drug getDrugByMapping(String code, ConceptSource conceptSource, Collection<ConceptMapType> withAnyOfTheseTypesOrOrderOfPreference) throws DAOException; /** * @see ConceptService#getAllConceptAttributeTypes() */ List<ConceptAttributeType> getAllConceptAttributeTypes(); /** * @see ConceptService#saveConceptAttributeType(ConceptAttributeType) */ ConceptAttributeType saveConceptAttributeType(ConceptAttributeType conceptAttributeType); /** * @see ConceptService#getConceptAttributeType(Integer) */ ConceptAttributeType getConceptAttributeType(Integer id); /** * @see ConceptService#getConceptAttributeTypeByUuid(String) */ ConceptAttributeType getConceptAttributeTypeByUuid(String uuid); /** * @see ConceptService#purgeConceptAttributeType(ConceptAttributeType) */ public void deleteConceptAttributeType(ConceptAttributeType conceptAttributeType); /** * @see ConceptService#getConceptAttributeTypes(String) */ public List<ConceptAttributeType> getConceptAttributeTypes(String name); /** * @see ConceptService#getConceptAttributeTypeByName(String) */ public ConceptAttributeType getConceptAttributeTypeByName(String exactName); /** * @see ConceptService#getConceptAttributeByUuid(String) */ public ConceptAttribute getConceptAttributeByUuid(String uuid); /** * @see ConceptService#hasAnyConceptAttribute(ConceptAttributeType) */ public long getConceptAttributeCount(ConceptAttributeType conceptAttributeType); List<Concept> getConceptsByClass(ConceptClass conceptClass); }
openmrs/openmrs-core
api/src/main/java/org/openmrs/api/db/ConceptDAO.java
7,503
/** * @see org.openmrs.api.ConceptService#getDrug(java.lang.Integer) */
block_comment
nl
/** * 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/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs.api.db; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.openmrs.Concept; import org.openmrs.ConceptAnswer; import org.openmrs.ConceptAttribute; import org.openmrs.ConceptAttributeType; import org.openmrs.ConceptClass; import org.openmrs.ConceptComplex; import org.openmrs.ConceptDatatype; import org.openmrs.ConceptDescription; import org.openmrs.ConceptMap; import org.openmrs.ConceptMapType; import org.openmrs.ConceptName; import org.openmrs.ConceptNameTag; import org.openmrs.ConceptNumeric; import org.openmrs.ConceptProposal; import org.openmrs.ConceptReferenceTerm; import org.openmrs.ConceptReferenceTermMap; import org.openmrs.ConceptSearchResult; import org.openmrs.ConceptSet; import org.openmrs.ConceptSource; import org.openmrs.ConceptStopWord; import org.openmrs.Drug; import org.openmrs.DrugIngredient; import org.openmrs.api.APIException; import org.openmrs.api.ConceptService; /** * Concept-related database functions * * @see ConceptService */ public interface ConceptDAO { /** * @see org.openmrs.api.ConceptService#saveConcept(org.openmrs.Concept) */ public Concept saveConcept(Concept concept) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConcept(org.openmrs.Concept) * <strong>Should</strong> purge concept */ public void purgeConcept(Concept concept) throws DAOException; /** * Get a ConceptComplex. The Concept.getDatatype() is "Complex" and the Concept.getHandler() is * the class name for the ComplexObsHandler key associated with this ConceptComplex. * * @param conceptId * @return the ConceptComplex */ public ConceptComplex getConceptComplex(Integer conceptId); /** * @see org.openmrs.api.ConceptService#purgeDrug(org.openmrs.Drug) */ public void purgeDrug(Drug drug) throws DAOException; /** * @see org.openmrs.api.ConceptService#saveDrug(org.openmrs.Drug) */ public Drug saveDrug(Drug drug) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConcept(java.lang.Integer) */ public Concept getConcept(Integer conceptId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptName(java.lang.Integer) * @param conceptNameId * @return The ConceptName matching the specified conceptNameId */ public ConceptName getConceptName(Integer conceptNameId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConcepts(java.lang.String, boolean, boolean) */ public List<Concept> getAllConcepts(String sortBy, boolean asc, boolean includeRetired) throws DAOException; /** * Returns a list of concepts based on the search criteria * * @param name * @param loc * @param searchOnPhrase This puts wildcard characters around the concept name search criteria * @return List&lt;Concept&gt; * @throws DAOException * <strong>Should</strong> not return concepts with matching names that are voided */ public List<Concept> getConcepts(String name, Locale loc, boolean searchOnPhrase, List<ConceptClass> classes, List<ConceptDatatype> datatypes) throws DAOException; /** * @see ConceptService#getConcepts(String, List, boolean, List, List, List, List, Concept, * Integer, Integer) * @throws DAOException * <strong>Should</strong> return correct results for concept with names that contains words with more weight * <strong>Should</strong> return correct results if a concept name contains same word more than once */ public List<ConceptSearchResult> getConcepts(String phrase, List<Locale> locales, boolean includeRetired, List<ConceptClass> requireClasses, List<ConceptClass> excludeClasses, List<ConceptDatatype> requireDatatypes, List<ConceptDatatype> excludeDatatypes, Concept answersToConcept, Integer start, Integer size) throws DAOException; public Integer getCountOfConcepts(String phrase, List<Locale> locales, boolean includeRetired, List<ConceptClass> requireClasses, List<ConceptClass> excludeClasses, List<ConceptDatatype> requireDatatypes, List<ConceptDatatype> excludeDatatypes, Concept answersToConcept) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptAnswer(java.lang.Integer) */ public ConceptAnswer getConceptAnswer(Integer conceptAnswerId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getDrug(java.lang.Integer) <SUF>*/ public Drug getDrug(Integer drugId) throws DAOException; /** * DAO for retrieving a list of drugs based on the following criteria * * @param drugName * @param concept * @param includeRetired * @return List&lt;Drug&gt; * @throws DAOException */ public List<Drug> getDrugs(String drugName, Concept concept, boolean includeRetired) throws DAOException; /** * @see org.openmrs.api.ConceptService#getDrugs(java.lang.String) */ public List<Drug> getDrugs(String phrase) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptClass(java.lang.Integer) */ public ConceptClass getConceptClass(Integer i) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptClassByName(java.lang.String) */ public List<ConceptClass> getConceptClasses(String name) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConceptClasses(boolean) */ public List<ConceptClass> getAllConceptClasses(boolean includeRetired) throws DAOException; /** * @see org.openmrs.api.ConceptService#saveConceptClass(org.openmrs.ConceptClass) */ public ConceptClass saveConceptClass(ConceptClass cc) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConceptClass(org.openmrs.ConceptClass) */ public void purgeConceptClass(ConceptClass cc) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConceptNameTag(org.openmrs.ConceptNameTag) */ public void deleteConceptNameTag(ConceptNameTag cnt) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConceptDatatypes(boolean) */ public List<ConceptDatatype> getAllConceptDatatypes(boolean includeRetired) throws DAOException; /** * @param name * @return the {@link ConceptDatatype} that matches <em>name</em> exactly or null if one does * not exist. * @throws DAOException */ public ConceptDatatype getConceptDatatypeByName(String name) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptDatatype(java.lang.Integer) */ public ConceptDatatype getConceptDatatype(Integer i) throws DAOException; /** * @see org.openmrs.api.ConceptService#saveConceptDatatype(org.openmrs.ConceptDatatype) */ public ConceptDatatype saveConceptDatatype(ConceptDatatype cd) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConceptDatatype(org.openmrs.ConceptDatatype) */ public void purgeConceptDatatype(ConceptDatatype cd) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptSetsByConcept(org.openmrs.Concept) */ public List<ConceptSet> getConceptSetsByConcept(Concept c) throws DAOException; /** * @see org.openmrs.api.ConceptService#getSetsContainingConcept(org.openmrs.Concept) */ public List<ConceptSet> getSetsContainingConcept(Concept concept) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptNumeric(java.lang.Integer) */ public ConceptNumeric getConceptNumeric(Integer conceptId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptsByAnswer(org.openmrs.Concept) * <strong>Should</strong> return concepts for the given answer concept */ public List<Concept> getConceptsByAnswer(Concept concept) throws DAOException; /** * @see org.openmrs.api.ConceptService#getPrevConcept(org.openmrs.Concept) */ public Concept getPrevConcept(Concept c) throws DAOException; /** * @see org.openmrs.api.ConceptService#getNextConcept(org.openmrs.Concept) */ public Concept getNextConcept(Concept c) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConceptProposals(boolean) */ public List<ConceptProposal> getAllConceptProposals(boolean includeComplete) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptProposal(java.lang.Integer) */ public ConceptProposal getConceptProposal(Integer i) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptProposals(java.lang.String) */ public List<ConceptProposal> getConceptProposals(String text) throws DAOException; /** * @see org.openmrs.api.ConceptService#getProposedConcepts(java.lang.String) */ public List<Concept> getProposedConcepts(String text) throws DAOException; /** * @see org.openmrs.api.ConceptService#saveConceptProposal(org.openmrs.ConceptProposal) */ public ConceptProposal saveConceptProposal(ConceptProposal cp) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConceptProposal(org.openmrs.ConceptProposal) */ public void purgeConceptProposal(ConceptProposal cp) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptsWithDrugsInFormulary() */ public List<Concept> getConceptsWithDrugsInFormulary() throws DAOException; public ConceptNameTag saveConceptNameTag(ConceptNameTag nameTag); public ConceptNameTag getConceptNameTag(Integer i); public ConceptNameTag getConceptNameTagByName(String name); /** * @see org.openmrs.api.ConceptService#getAllConceptNameTags() */ public List<ConceptNameTag> getAllConceptNameTags(); /** * @see org.openmrs.api.ConceptService#getConceptSource(java.lang.Integer) */ public ConceptSource getConceptSource(Integer conceptSourceId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConceptSources(boolean) */ public List<ConceptSource> getAllConceptSources(boolean includeRetired) throws DAOException; /** * @see org.openmrs.api.ConceptService#saveConceptSource(org.openmrs.ConceptSource) */ public ConceptSource saveConceptSource(ConceptSource conceptSource) throws DAOException; /** * @see org.openmrs.api.ConceptService#purgeConceptSource(org.openmrs.ConceptSource) */ public ConceptSource deleteConceptSource(ConceptSource cs) throws DAOException; /** * @see org.openmrs.api.ConceptService#getLocalesOfConceptNames() */ public Set<Locale> getLocalesOfConceptNames(); /** * @see ConceptService#getMaxConceptId() */ public Integer getMaxConceptId(); /** * @see org.openmrs.api.ConceptService#conceptIterator() */ public Iterator<Concept> conceptIterator(); /** * @see org.openmrs.api.ConceptService#getConceptsByMapping(java.lang.String, java.lang.String) * * @deprecated As of 2.5.0, this method has been deprecated in favor of {@link #getConceptIdsByMapping(String, String, boolean)} */ @Deprecated public List<Concept> getConceptsByMapping(String code, String sourceName, boolean includeRetired); /** * @see org.openmrs.api.ConceptService#getConceptIdsByMapping(String, String, boolean) */ public List<Integer> getConceptIdsByMapping(String code, String sourceName, boolean includeRetired); /** * @param uuid * @return concept or null */ public Concept getConceptByUuid(String uuid); /** * @param uuid * @return concept class or null */ public ConceptClass getConceptClassByUuid(String uuid); public ConceptAnswer getConceptAnswerByUuid(String uuid); public ConceptName getConceptNameByUuid(String uuid); public ConceptSet getConceptSetByUuid(String uuid); public ConceptSource getConceptSourceByUuid(String uuid); /** * @param uuid * @return concept data type or null */ public ConceptDatatype getConceptDatatypeByUuid(String uuid); /** * @param uuid * @return concept numeric or null */ public ConceptNumeric getConceptNumericByUuid(String uuid); /** * @param uuid * @return concept proposal or null */ public ConceptProposal getConceptProposalByUuid(String uuid); /** * @param uuid * @return drug or null */ public Drug getDrugByUuid(String uuid); public DrugIngredient getDrugIngredientByUuid(String uuid); public Map<Integer, String> getConceptUuids(); public ConceptDescription getConceptDescriptionByUuid(String uuid); public ConceptNameTag getConceptNameTagByUuid(String uuid); /** * @see ConceptService#getConceptMappingsToSource(ConceptSource) */ public List<ConceptMap> getConceptMapsBySource(ConceptSource conceptSource) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptSourceByName(java.lang.String) */ public ConceptSource getConceptSourceByName(String conceptSourceName) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptSourceByUniqueId(java.lang.String) */ public ConceptSource getConceptSourceByUniqueId(String uniqueId); /** * @see org.openmrs.api.ConceptService#getConceptSourceByHL7Code(java.lang.String) */ public ConceptSource getConceptSourceByHL7Code(String hl7Code); /** * Gets the value of conceptDatatype currently saved in the database for the given concept, * bypassing any caches. This is used prior to saving an concept so that we can change the obs * if need be * * @param concept for which the conceptDatatype should be fetched * @return the conceptDatatype currently in the database for this concept * <strong>Should</strong> get saved conceptDatatype from database */ public ConceptDatatype getSavedConceptDatatype(Concept concept); /** * Gets the persisted copy of the conceptName currently saved in the database for the given * conceptName, bypassing any caches. This is used prior to saving an concept so that we can * change the obs if need be or avoid breaking any obs referencing it. * * @param conceptName ConceptName to fetch from the database * @return the persisted copy of the conceptName currently saved in the database for this * conceptName */ public ConceptName getSavedConceptName(ConceptName conceptName); /** * @see org.openmrs.api.ConceptService#saveConceptStopWord(org.openmrs.ConceptStopWord) */ public ConceptStopWord saveConceptStopWord(ConceptStopWord conceptStopWord) throws DAOException; /** * @see org.openmrs.api.ConceptService#deleteConceptStopWord(Integer) */ public void deleteConceptStopWord(Integer conceptStopWordId) throws DAOException; /** * @see org.openmrs.api.ConceptService#getConceptStopWords(java.util.Locale) */ public List<String> getConceptStopWords(Locale locale) throws DAOException; /** * @see org.openmrs.api.ConceptService#getAllConceptStopWords() */ public List<ConceptStopWord> getAllConceptStopWords(); /** * @see ConceptService#getCountOfDrugs(String, Concept, boolean, boolean, boolean) */ public Long getCountOfDrugs(String drugName, Concept concept, boolean searchOnPhrase, boolean searchDrugConceptNames, boolean includeRetired) throws DAOException; /** * @see ConceptService#getDrugs(String, Concept, boolean, boolean, boolean, Integer, Integer) */ public List<Drug> getDrugs(String drugName, Concept concept, boolean searchOnPhrase, boolean searchDrugConceptNames, boolean includeRetired, Integer start, Integer length) throws DAOException; /** * @see ConceptService#getDrugsByIngredient(Concept) */ public List<Drug> getDrugsByIngredient(Concept ingredient); /** * @see ConceptService#getConceptMapTypes(boolean, boolean) */ public List<ConceptMapType> getConceptMapTypes(boolean includeRetired, boolean includeHidden) throws DAOException; /** * @see ConceptService#getConceptMapType(Integer) */ public ConceptMapType getConceptMapType(Integer conceptMapTypeId) throws DAOException; /** * @see ConceptService#getConceptMapTypeByUuid(String) */ public ConceptMapType getConceptMapTypeByUuid(String uuid) throws DAOException; /** * @see ConceptService#getConceptMapTypeByName(String) */ public ConceptMapType getConceptMapTypeByName(String name) throws DAOException; /** * @see ConceptService#saveConceptMapType(ConceptMapType) */ public ConceptMapType saveConceptMapType(ConceptMapType conceptMapType) throws DAOException; /** * @see ConceptService#purgeConceptMapType(ConceptMapType) */ public void deleteConceptMapType(ConceptMapType conceptMapType) throws DAOException; /** * @see ConceptService#getConceptReferenceTerms(boolean) */ public List<ConceptReferenceTerm> getConceptReferenceTerms(boolean includeRetired) throws DAOException; /** * @see ConceptService#getConceptReferenceTerm(Integer) */ public ConceptReferenceTerm getConceptReferenceTerm(Integer conceptReferenceTermId) throws DAOException; /** * @see ConceptService#getConceptReferenceTermByUuid(String) */ public ConceptReferenceTerm getConceptReferenceTermByUuid(String uuid) throws DAOException; public List<ConceptReferenceTerm> getConceptReferenceTermsBySource(ConceptSource conceptSource) throws DAOException; /** * @see ConceptService#getConceptReferenceTermByName(String, ConceptSource) */ public ConceptReferenceTerm getConceptReferenceTermByName(String name, ConceptSource conceptSource) throws DAOException; /** * @see ConceptService#getConceptReferenceTermByCode(String, ConceptSource) */ public ConceptReferenceTerm getConceptReferenceTermByCode(String code, ConceptSource conceptSource) throws DAOException; /** * @see ConceptService#getConceptReferenceTermByCode(String, ConceptSource, boolean) */ public List<ConceptReferenceTerm> getConceptReferenceTermByCode(String code, ConceptSource conceptSource, boolean includeRetired) throws DAOException; /** * @see ConceptService#saveConceptReferenceTerm(ConceptReferenceTerm) */ public ConceptReferenceTerm saveConceptReferenceTerm(ConceptReferenceTerm conceptReferenceTerm) throws DAOException; /** * @see ConceptService#purgeConceptReferenceTerm(ConceptReferenceTerm) */ public void deleteConceptReferenceTerm(ConceptReferenceTerm conceptReferenceTerm) throws DAOException; /** * @see ConceptService#getCountOfConceptReferenceTerms(String, ConceptSource, boolean) */ public Long getCountOfConceptReferenceTerms(String query, ConceptSource conceptSource, boolean includeRetired) throws DAOException; /** * @see ConceptService#getConceptReferenceTerms(String, ConceptSource, Integer, Integer, * boolean) */ public List<ConceptReferenceTerm> getConceptReferenceTerms(String query, ConceptSource conceptSource, Integer start, Integer length, boolean includeRetired) throws APIException; /** * @see ConceptService#getReferenceTermMappingsTo(ConceptReferenceTerm) */ public List<ConceptReferenceTermMap> getReferenceTermMappingsTo(ConceptReferenceTerm term) throws DAOException; /** * Checks if there are any {@link ConceptReferenceTermMap}s or {@link ConceptMap}s using the * specified term * * @param term * @return true if term is in use * @throws DAOException * <strong>Should</strong> return true if a term has a conceptMap or more using it * <strong>Should</strong> return true if a term has a conceptReferenceTermMap or more using it * <strong>Should</strong> return false if a term has no maps using it */ public boolean isConceptReferenceTermInUse(ConceptReferenceTerm term) throws DAOException; /** * Checks if there are any {@link ConceptReferenceTermMap}s or {@link ConceptMap}s using the * specified mapType * * @param mapType * @return true if map type is in use * @throws DAOException * <strong>Should</strong> return true if a mapType has a conceptMap or more using it * <strong>Should</strong> return true if a mapType has a conceptReferenceTermMap or more using it * <strong>Should</strong> return false if a mapType has no maps using it */ public boolean isConceptMapTypeInUse(ConceptMapType mapType) throws DAOException; /** * @see ConceptService#getConceptsByName(String, Locale, Boolean) */ public List<Concept> getConceptsByName(String name, Locale locale, Boolean exactLocal); /** * @see ConceptService#getConceptByName(String) */ public Concept getConceptByName(String name); /** * It is in the DAO, because it must be done in the MANUAL flush mode to prevent premature * flushes in {@link ConceptService#saveConcept(Concept)}. It will be removed in 1.10 when we * have a better way to manage flush modes. * * @see ConceptService#getDefaultConceptMapType() */ public ConceptMapType getDefaultConceptMapType() throws DAOException; /** * @see ConceptService#isConceptNameDuplicate(ConceptName) */ public boolean isConceptNameDuplicate(ConceptName name); /** * @see ConceptService#getDrugs(String, java.util.Locale, boolean, boolean) */ public List<Drug> getDrugs(String searchPhrase, Locale locale, boolean exactLocale, boolean includeRetired); /** * @see org.openmrs.api.ConceptService#getDrugsByMapping(String, ConceptSource, Collection, * boolean) */ public List<Drug> getDrugsByMapping(String code, ConceptSource conceptSource, Collection<ConceptMapType> withAnyOfTheseTypes, boolean includeRetired) throws DAOException; /** * @see org.openmrs.api.ConceptService#getDrugByMapping(String, org.openmrs.ConceptSource, java.util.Collection) */ Drug getDrugByMapping(String code, ConceptSource conceptSource, Collection<ConceptMapType> withAnyOfTheseTypesOrOrderOfPreference) throws DAOException; /** * @see ConceptService#getAllConceptAttributeTypes() */ List<ConceptAttributeType> getAllConceptAttributeTypes(); /** * @see ConceptService#saveConceptAttributeType(ConceptAttributeType) */ ConceptAttributeType saveConceptAttributeType(ConceptAttributeType conceptAttributeType); /** * @see ConceptService#getConceptAttributeType(Integer) */ ConceptAttributeType getConceptAttributeType(Integer id); /** * @see ConceptService#getConceptAttributeTypeByUuid(String) */ ConceptAttributeType getConceptAttributeTypeByUuid(String uuid); /** * @see ConceptService#purgeConceptAttributeType(ConceptAttributeType) */ public void deleteConceptAttributeType(ConceptAttributeType conceptAttributeType); /** * @see ConceptService#getConceptAttributeTypes(String) */ public List<ConceptAttributeType> getConceptAttributeTypes(String name); /** * @see ConceptService#getConceptAttributeTypeByName(String) */ public ConceptAttributeType getConceptAttributeTypeByName(String exactName); /** * @see ConceptService#getConceptAttributeByUuid(String) */ public ConceptAttribute getConceptAttributeByUuid(String uuid); /** * @see ConceptService#hasAnyConceptAttribute(ConceptAttributeType) */ public long getConceptAttributeCount(ConceptAttributeType conceptAttributeType); List<Concept> getConceptsByClass(ConceptClass conceptClass); }
124261_9
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.ui.impl; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DeviceId; import org.onosproject.net.ElementId; import org.onosproject.net.HostId; import org.onosproject.net.Link; import org.onosproject.net.flow.criteria.Criterion; import org.onosproject.net.flow.criteria.PortCriterion; import org.onosproject.net.flow.instructions.Instructions.OutputInstruction; import org.onosproject.net.intent.FlowRuleIntent; import org.onosproject.net.intent.Intent; import org.onosproject.net.intent.IntentService; import org.onosproject.net.intent.OpticalConnectivityIntent; import org.onosproject.net.intent.ProtectionEndpointIntent; import org.onosproject.net.link.LinkService; import org.onosproject.ui.impl.topo.util.ServicesBundle; import org.onosproject.ui.impl.topo.util.TrafficLink; import org.onosproject.ui.impl.topo.util.TrafficLink.StatsType; import org.onosproject.ui.impl.topo.util.TrafficLinkMap; import org.onosproject.ui.topo.AbstractTopoMonitor; import org.onosproject.ui.topo.DeviceHighlight; import org.onosproject.ui.topo.Highlights; import org.onosproject.ui.topo.HostHighlight; import org.onosproject.ui.topo.LinkHighlight.Flavor; import org.onosproject.ui.topo.Mod; import org.onosproject.ui.topo.NodeHighlight; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.stream.Collectors; import static org.onosproject.net.MarkerResource.marker; import static org.onosproject.ui.impl.ProtectedIntentMonitor.ProtectedMode.IDLE; import static org.onosproject.ui.impl.ProtectedIntentMonitor.ProtectedMode.SELECTED_INTENT; /** * Encapsulates the behavior of monitoring protected intents. */ //TODO refactor duplicated methods from here and the TrafficMonitor to AbstractTopoMonitor public class ProtectedIntentMonitor extends AbstractTopoMonitor { private static final Logger log = LoggerFactory.getLogger(ProtectedIntentMonitor.class); private static final String PRIMARY_PATH_TAG = "protection1"; private static final String PROT_PRIMARY = "protPrimary"; private static final String PROT_BACKUP = "protBackup"; private static final Mod MOD_PROT_PRIMARY = new Mod(PROT_PRIMARY); private static final Set<Mod> PROTECTED_MOD_PRIMARY_SET = ImmutableSet.of(MOD_PROT_PRIMARY); private static final Mod MOD_PROT_BACKUP = new Mod(PROT_BACKUP); private static final Set<Mod> PROTECTED_MOD_BACKUP_SET = ImmutableSet.of(MOD_PROT_BACKUP); /** * Designates the different modes of operation. */ public enum ProtectedMode { IDLE, SELECTED_INTENT } private final ServicesBundle services; private final TopologyViewMessageHandler msgHandler; private final Timer timer = new Timer("topo-protected-intents"); private TimerTask trafficTask = null; private ProtectedMode mode = ProtectedMode.IDLE; private Intent selectedIntent = null; /** * Constructs a protected intent monitor. * * @param services bundle of services * @param msgHandler our message handler */ public ProtectedIntentMonitor(ServicesBundle services, TopologyViewMessageHandler msgHandler) { this.services = services; this.msgHandler = msgHandler; } // ======================================================================= // === API === // TODO: move this out to the "h2h/multi-intent app" /** * Monitor for protected intent data to be sent back to the web client, * for the given intent. * * @param intent the intent to monitor */ public synchronized void monitor(Intent intent) { log.debug("monitor intent: {}", intent.id()); selectedIntent = intent; mode = SELECTED_INTENT; scheduleTask(); sendSelectedIntents(); } /** * Stop all traffic monitoring. */ public synchronized void stopMonitoring() { log.debug("STOP monitoring"); if (mode != IDLE) { sendClearAll(); } } // ======================================================================= // === Helper methods === private void sendClearAll() { clearAll(); sendClearHighlights(); } private void clearAll() { this.mode = IDLE; clearSelection(); cancelTask(); } private void clearSelection() { selectedIntent = null; } //TODO duplicate and can be brought in abstract upper class. private synchronized void scheduleTask() { if (trafficTask == null) { log.debug("Starting up background protected intent task..."); trafficTask = new TrafficUpdateTask(); timer.schedule(trafficTask, trafficPeriod, trafficPeriod); } else { log.debug("(protected intent task already running)"); } } private synchronized void cancelTask() { if (trafficTask != null) { trafficTask.cancel(); trafficTask = null; } } private void sendSelectedIntents() { log.debug("sendSelectedIntents: {}", selectedIntent); msgHandler.sendHighlights(protectedIntentHighlights()); } private void sendClearHighlights() { log.debug("sendClearHighlights"); msgHandler.sendHighlights(new Highlights()); } // ======================================================================= // === Generate messages in JSON object node format private Highlights protectedIntentHighlights() { Highlights highlights = new Highlights(); TrafficLinkMap linkMap = new TrafficLinkMap(); IntentService intentService = services.intent(); if (selectedIntent != null) { List<Intent> installables = intentService.getInstallableIntents(selectedIntent.key()); if (installables != null) { ProtectionEndpointIntent ep1 = installables.stream() .filter(ProtectionEndpointIntent.class::isInstance) .map(ProtectionEndpointIntent.class::cast) .findFirst().orElse(null); ProtectionEndpointIntent ep2 = installables.stream() .filter(ii -> !ii.equals(ep1)) .filter(ProtectionEndpointIntent.class::isInstance) .map(ProtectionEndpointIntent.class::cast) .findFirst().orElse(null); if (ep1 == null || ep2 == null) { log.warn("Selected Intent {} didn't have 2 protection endpoints", selectedIntent.key()); stopMonitoring(); return highlights; } Set<Link> primary = new LinkedHashSet<>(); Set<Link> backup = new LinkedHashSet<>(); Map<Boolean, List<FlowRuleIntent>> transits = installables.stream() .filter(FlowRuleIntent.class::isInstance) .map(FlowRuleIntent.class::cast) // only consider fwd links so that ants march in one direction // TODO: didn't help need further investigation. //.filter(i -> !i.resources().contains(marker("rev"))) .collect(Collectors.groupingBy(this::isPrimary)); // walk primary ConnectPoint primHead = ep1.description().paths().get(0).output().connectPoint(); ConnectPoint primTail = ep2.description().paths().get(0).output().connectPoint(); List<FlowRuleIntent> primTransit = transits.getOrDefault(true, ImmutableList.of()); populateLinks(primary, primHead, primTail, primTransit); // walk backup ConnectPoint backHead = ep1.description().paths().get(1).output().connectPoint(); ConnectPoint backTail = ep2.description().paths().get(1).output().connectPoint(); List<FlowRuleIntent> backTransit = transits.getOrDefault(false, ImmutableList.of()); populateLinks(backup, backHead, backTail, backTransit); // Add packet to optical links if (!usingBackup(primary)) { primary.addAll(protectedIntentMultiLayer(primHead, primTail)); } backup.addAll(protectedIntentMultiLayer(backHead, backTail)); boolean isOptical = selectedIntent instanceof OpticalConnectivityIntent; //last parameter (traffic) signals if the link is highlighted with ants or solid line //Flavor is swapped so green is primary path. if (usingBackup(primary)) { //the backup becomes in use so we have a dotted line processLinks(linkMap, backup, Flavor.PRIMARY_HIGHLIGHT, isOptical, true, PROTECTED_MOD_BACKUP_SET); } else { processLinks(linkMap, primary, Flavor.PRIMARY_HIGHLIGHT, isOptical, true, PROTECTED_MOD_PRIMARY_SET); processLinks(linkMap, backup, Flavor.SECONDARY_HIGHLIGHT, isOptical, false, PROTECTED_MOD_BACKUP_SET); } updateHighlights(highlights, primary); updateHighlights(highlights, backup); colorLinks(highlights, linkMap); highlights.subdueAllElse(Highlights.Amount.MINIMALLY); } else { log.debug("Selected Intent has no installable intents"); } } else { log.debug("Selected Intent is null"); } return highlights; } /** * Returns the packet to optical mapping given a head and tail of a protection path. * * @param head head of path * @param tail tail of path */ private Set<Link> protectedIntentMultiLayer(ConnectPoint head, ConnectPoint tail) { List<Link> links = new LinkedList<>(); LinkService linkService = services.link(); IntentService intentService = services.intent(); // Ingress cross connect link links.addAll( linkService.getEgressLinks(head).stream() .filter(l -> l.type() == Link.Type.OPTICAL) .collect(Collectors.toList()) ); // Egress cross connect link links.addAll( linkService.getIngressLinks(tail).stream() .filter(l -> l.type() == Link.Type.OPTICAL) .collect(Collectors.toList()) ); // The protected intent does not rely on a multi-layer mapping if (links.size() != 2) { return Collections.emptySet(); } // Expected head and tail of optical circuit (not connectivity!) intent ConnectPoint ocHead = links.get(0).dst(); ConnectPoint ocTail = links.get(1).src(); // Optical connectivity // FIXME: assumes that transponder (OTN device) is a one-to-one mapping // We need to track the multi-layer aspects better intentService.getIntents().forEach(intent -> { if (intent instanceof OpticalConnectivityIntent) { OpticalConnectivityIntent ocIntent = (OpticalConnectivityIntent) intent; if (ocHead.deviceId().equals(ocIntent.getSrc().deviceId()) && ocTail.deviceId().equals(ocIntent.getDst().deviceId())) { intentService.getInstallableIntents(ocIntent.key()).forEach(i -> { if (i instanceof FlowRuleIntent) { FlowRuleIntent fr = (FlowRuleIntent) i; links.addAll(linkResources(fr)); } }); } } }); return new LinkedHashSet<>(links); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** * Populate Links along the primary/backup path. * * @param links link collection to populate [output] * @param head head-end of primary/backup path * @param tail tail-end of primary/backup path * @param transit Intents if any */ private void populateLinks(Set<Link> links, ConnectPoint head, ConnectPoint tail, List<FlowRuleIntent> transit) { // find first hop link Link first = transit.stream() // search for Link head -> transit Intent head // as first candidate of 1st hop Link .flatMap(fri -> fri.flowRules().stream()) .map(fr -> // find first input port from FlowRule Optional.ofNullable(fr.selector().getCriterion(Criterion.Type.IN_PORT)) .filter(PortCriterion.class::isInstance) .map(PortCriterion.class::cast) .map(PortCriterion::port) .map(pn -> new ConnectPoint(fr.deviceId(), pn)) .orElse(null) ).filter(Objects::nonNull) .map(dst -> services.link().getLink(head, dst)) .filter(Objects::nonNull) .findFirst() // if there isn't one probably 1 hop to the tail .orElse(services.link().getLink(head, tail)); // add first link if (first != null) { links.add(first); } // add links in the middle if any transit.forEach(fri -> links.addAll(linkResources(fri))); // add last hop if any Lists.reverse(transit).stream() // search for Link transit Intent tail -> tail // as candidate of last hop Link .flatMap(fri -> ImmutableList.copyOf(fri.flowRules()).reverse().stream()) .map(fr -> // find first output port from FlowRule fr.treatment().allInstructions().stream() .filter(OutputInstruction.class::isInstance).findFirst() .map(OutputInstruction.class::cast) .map(OutputInstruction::port) .map(pn -> new ConnectPoint(fr.deviceId(), pn)) .orElse(null) ).filter(Objects::nonNull) .map(src -> services.link().getLink(src, tail)) .filter(Objects::nonNull) .findFirst() .ifPresent(links::add); } /** * Returns true if specified intent is marked with primary marker resource. * * @param intent to test * @return true if it is an Intent taking part of primary transit path */ private boolean isPrimary(Intent intent) { return intent.resources() .contains(marker(PRIMARY_PATH_TAG)); } // returns true if the backup path is the one where the traffic is currently flowing private boolean usingBackup(Set<Link> primary) { Set<Link> activeLinks = Sets.newHashSet(services.link().getActiveLinks()); return primary.isEmpty() || !activeLinks.containsAll(primary); } private void updateHighlights(Highlights highlights, Iterable<Link> links) { for (Link link : links) { ensureNodePresent(highlights, link.src().elementId()); ensureNodePresent(highlights, link.dst().elementId()); } } //TODO duplicate and can be brought in abstract upper class. private void ensureNodePresent(Highlights highlights, ElementId eid) { String id = eid.toString(); NodeHighlight nh = highlights.getNode(id); if (nh == null) { if (eid instanceof DeviceId) { nh = new DeviceHighlight(id); highlights.add((DeviceHighlight) nh); } else if (eid instanceof HostId) { nh = new HostHighlight(id); highlights.add((HostHighlight) nh); } } } private void processLinks(TrafficLinkMap linkMap, Iterable<Link> links, Flavor flavor, boolean isOptical, boolean showTraffic, Set<Mod> mods) { if (links != null) { for (Link link : links) { TrafficLink tlink = linkMap.add(link); tlink.tagFlavor(flavor); tlink.optical(isOptical); if (showTraffic) { tlink.antMarch(true); } tlink.tagMods(mods); } } } //TODO duplicate and can be brought in abstract upper class. private void colorLinks(Highlights highlights, TrafficLinkMap linkMap) { for (TrafficLink tlink : linkMap.biLinks()) { highlights.add(tlink.highlight(StatsType.TAGGED)); } } //TODO duplicate and can be brought in abstract upper class. // Extracts links from the specified flow rule intent resources private Collection<Link> linkResources(Intent installable) { ImmutableList.Builder<Link> builder = ImmutableList.builder(); installable.resources().stream().filter(r -> r instanceof Link) .forEach(r -> builder.add((Link) r)); return builder.build(); } // ======================================================================= // === Background Task // Provides periodic update of traffic information to the client private class TrafficUpdateTask extends TimerTask { @Override public void run() { try { switch (mode) { case SELECTED_INTENT: sendSelectedIntents(); break; default: // RELATED_INTENTS and IDLE modes should never invoke // the background task, but if they do, they have // nothing to do break; } } catch (Exception e) { log.warn("Unable to process protected intent task due to {}", e.getMessage()); log.warn("Boom!", e); } } } }
opennetworkinglab/onos
web/gui/src/main/java/org/onosproject/ui/impl/ProtectedIntentMonitor.java
5,187
// === Helper methods ===
line_comment
nl
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.ui.impl; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DeviceId; import org.onosproject.net.ElementId; import org.onosproject.net.HostId; import org.onosproject.net.Link; import org.onosproject.net.flow.criteria.Criterion; import org.onosproject.net.flow.criteria.PortCriterion; import org.onosproject.net.flow.instructions.Instructions.OutputInstruction; import org.onosproject.net.intent.FlowRuleIntent; import org.onosproject.net.intent.Intent; import org.onosproject.net.intent.IntentService; import org.onosproject.net.intent.OpticalConnectivityIntent; import org.onosproject.net.intent.ProtectionEndpointIntent; import org.onosproject.net.link.LinkService; import org.onosproject.ui.impl.topo.util.ServicesBundle; import org.onosproject.ui.impl.topo.util.TrafficLink; import org.onosproject.ui.impl.topo.util.TrafficLink.StatsType; import org.onosproject.ui.impl.topo.util.TrafficLinkMap; import org.onosproject.ui.topo.AbstractTopoMonitor; import org.onosproject.ui.topo.DeviceHighlight; import org.onosproject.ui.topo.Highlights; import org.onosproject.ui.topo.HostHighlight; import org.onosproject.ui.topo.LinkHighlight.Flavor; import org.onosproject.ui.topo.Mod; import org.onosproject.ui.topo.NodeHighlight; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.stream.Collectors; import static org.onosproject.net.MarkerResource.marker; import static org.onosproject.ui.impl.ProtectedIntentMonitor.ProtectedMode.IDLE; import static org.onosproject.ui.impl.ProtectedIntentMonitor.ProtectedMode.SELECTED_INTENT; /** * Encapsulates the behavior of monitoring protected intents. */ //TODO refactor duplicated methods from here and the TrafficMonitor to AbstractTopoMonitor public class ProtectedIntentMonitor extends AbstractTopoMonitor { private static final Logger log = LoggerFactory.getLogger(ProtectedIntentMonitor.class); private static final String PRIMARY_PATH_TAG = "protection1"; private static final String PROT_PRIMARY = "protPrimary"; private static final String PROT_BACKUP = "protBackup"; private static final Mod MOD_PROT_PRIMARY = new Mod(PROT_PRIMARY); private static final Set<Mod> PROTECTED_MOD_PRIMARY_SET = ImmutableSet.of(MOD_PROT_PRIMARY); private static final Mod MOD_PROT_BACKUP = new Mod(PROT_BACKUP); private static final Set<Mod> PROTECTED_MOD_BACKUP_SET = ImmutableSet.of(MOD_PROT_BACKUP); /** * Designates the different modes of operation. */ public enum ProtectedMode { IDLE, SELECTED_INTENT } private final ServicesBundle services; private final TopologyViewMessageHandler msgHandler; private final Timer timer = new Timer("topo-protected-intents"); private TimerTask trafficTask = null; private ProtectedMode mode = ProtectedMode.IDLE; private Intent selectedIntent = null; /** * Constructs a protected intent monitor. * * @param services bundle of services * @param msgHandler our message handler */ public ProtectedIntentMonitor(ServicesBundle services, TopologyViewMessageHandler msgHandler) { this.services = services; this.msgHandler = msgHandler; } // ======================================================================= // === API === // TODO: move this out to the "h2h/multi-intent app" /** * Monitor for protected intent data to be sent back to the web client, * for the given intent. * * @param intent the intent to monitor */ public synchronized void monitor(Intent intent) { log.debug("monitor intent: {}", intent.id()); selectedIntent = intent; mode = SELECTED_INTENT; scheduleTask(); sendSelectedIntents(); } /** * Stop all traffic monitoring. */ public synchronized void stopMonitoring() { log.debug("STOP monitoring"); if (mode != IDLE) { sendClearAll(); } } // ======================================================================= // === Helper<SUF> private void sendClearAll() { clearAll(); sendClearHighlights(); } private void clearAll() { this.mode = IDLE; clearSelection(); cancelTask(); } private void clearSelection() { selectedIntent = null; } //TODO duplicate and can be brought in abstract upper class. private synchronized void scheduleTask() { if (trafficTask == null) { log.debug("Starting up background protected intent task..."); trafficTask = new TrafficUpdateTask(); timer.schedule(trafficTask, trafficPeriod, trafficPeriod); } else { log.debug("(protected intent task already running)"); } } private synchronized void cancelTask() { if (trafficTask != null) { trafficTask.cancel(); trafficTask = null; } } private void sendSelectedIntents() { log.debug("sendSelectedIntents: {}", selectedIntent); msgHandler.sendHighlights(protectedIntentHighlights()); } private void sendClearHighlights() { log.debug("sendClearHighlights"); msgHandler.sendHighlights(new Highlights()); } // ======================================================================= // === Generate messages in JSON object node format private Highlights protectedIntentHighlights() { Highlights highlights = new Highlights(); TrafficLinkMap linkMap = new TrafficLinkMap(); IntentService intentService = services.intent(); if (selectedIntent != null) { List<Intent> installables = intentService.getInstallableIntents(selectedIntent.key()); if (installables != null) { ProtectionEndpointIntent ep1 = installables.stream() .filter(ProtectionEndpointIntent.class::isInstance) .map(ProtectionEndpointIntent.class::cast) .findFirst().orElse(null); ProtectionEndpointIntent ep2 = installables.stream() .filter(ii -> !ii.equals(ep1)) .filter(ProtectionEndpointIntent.class::isInstance) .map(ProtectionEndpointIntent.class::cast) .findFirst().orElse(null); if (ep1 == null || ep2 == null) { log.warn("Selected Intent {} didn't have 2 protection endpoints", selectedIntent.key()); stopMonitoring(); return highlights; } Set<Link> primary = new LinkedHashSet<>(); Set<Link> backup = new LinkedHashSet<>(); Map<Boolean, List<FlowRuleIntent>> transits = installables.stream() .filter(FlowRuleIntent.class::isInstance) .map(FlowRuleIntent.class::cast) // only consider fwd links so that ants march in one direction // TODO: didn't help need further investigation. //.filter(i -> !i.resources().contains(marker("rev"))) .collect(Collectors.groupingBy(this::isPrimary)); // walk primary ConnectPoint primHead = ep1.description().paths().get(0).output().connectPoint(); ConnectPoint primTail = ep2.description().paths().get(0).output().connectPoint(); List<FlowRuleIntent> primTransit = transits.getOrDefault(true, ImmutableList.of()); populateLinks(primary, primHead, primTail, primTransit); // walk backup ConnectPoint backHead = ep1.description().paths().get(1).output().connectPoint(); ConnectPoint backTail = ep2.description().paths().get(1).output().connectPoint(); List<FlowRuleIntent> backTransit = transits.getOrDefault(false, ImmutableList.of()); populateLinks(backup, backHead, backTail, backTransit); // Add packet to optical links if (!usingBackup(primary)) { primary.addAll(protectedIntentMultiLayer(primHead, primTail)); } backup.addAll(protectedIntentMultiLayer(backHead, backTail)); boolean isOptical = selectedIntent instanceof OpticalConnectivityIntent; //last parameter (traffic) signals if the link is highlighted with ants or solid line //Flavor is swapped so green is primary path. if (usingBackup(primary)) { //the backup becomes in use so we have a dotted line processLinks(linkMap, backup, Flavor.PRIMARY_HIGHLIGHT, isOptical, true, PROTECTED_MOD_BACKUP_SET); } else { processLinks(linkMap, primary, Flavor.PRIMARY_HIGHLIGHT, isOptical, true, PROTECTED_MOD_PRIMARY_SET); processLinks(linkMap, backup, Flavor.SECONDARY_HIGHLIGHT, isOptical, false, PROTECTED_MOD_BACKUP_SET); } updateHighlights(highlights, primary); updateHighlights(highlights, backup); colorLinks(highlights, linkMap); highlights.subdueAllElse(Highlights.Amount.MINIMALLY); } else { log.debug("Selected Intent has no installable intents"); } } else { log.debug("Selected Intent is null"); } return highlights; } /** * Returns the packet to optical mapping given a head and tail of a protection path. * * @param head head of path * @param tail tail of path */ private Set<Link> protectedIntentMultiLayer(ConnectPoint head, ConnectPoint tail) { List<Link> links = new LinkedList<>(); LinkService linkService = services.link(); IntentService intentService = services.intent(); // Ingress cross connect link links.addAll( linkService.getEgressLinks(head).stream() .filter(l -> l.type() == Link.Type.OPTICAL) .collect(Collectors.toList()) ); // Egress cross connect link links.addAll( linkService.getIngressLinks(tail).stream() .filter(l -> l.type() == Link.Type.OPTICAL) .collect(Collectors.toList()) ); // The protected intent does not rely on a multi-layer mapping if (links.size() != 2) { return Collections.emptySet(); } // Expected head and tail of optical circuit (not connectivity!) intent ConnectPoint ocHead = links.get(0).dst(); ConnectPoint ocTail = links.get(1).src(); // Optical connectivity // FIXME: assumes that transponder (OTN device) is a one-to-one mapping // We need to track the multi-layer aspects better intentService.getIntents().forEach(intent -> { if (intent instanceof OpticalConnectivityIntent) { OpticalConnectivityIntent ocIntent = (OpticalConnectivityIntent) intent; if (ocHead.deviceId().equals(ocIntent.getSrc().deviceId()) && ocTail.deviceId().equals(ocIntent.getDst().deviceId())) { intentService.getInstallableIntents(ocIntent.key()).forEach(i -> { if (i instanceof FlowRuleIntent) { FlowRuleIntent fr = (FlowRuleIntent) i; links.addAll(linkResources(fr)); } }); } } }); return new LinkedHashSet<>(links); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** * Populate Links along the primary/backup path. * * @param links link collection to populate [output] * @param head head-end of primary/backup path * @param tail tail-end of primary/backup path * @param transit Intents if any */ private void populateLinks(Set<Link> links, ConnectPoint head, ConnectPoint tail, List<FlowRuleIntent> transit) { // find first hop link Link first = transit.stream() // search for Link head -> transit Intent head // as first candidate of 1st hop Link .flatMap(fri -> fri.flowRules().stream()) .map(fr -> // find first input port from FlowRule Optional.ofNullable(fr.selector().getCriterion(Criterion.Type.IN_PORT)) .filter(PortCriterion.class::isInstance) .map(PortCriterion.class::cast) .map(PortCriterion::port) .map(pn -> new ConnectPoint(fr.deviceId(), pn)) .orElse(null) ).filter(Objects::nonNull) .map(dst -> services.link().getLink(head, dst)) .filter(Objects::nonNull) .findFirst() // if there isn't one probably 1 hop to the tail .orElse(services.link().getLink(head, tail)); // add first link if (first != null) { links.add(first); } // add links in the middle if any transit.forEach(fri -> links.addAll(linkResources(fri))); // add last hop if any Lists.reverse(transit).stream() // search for Link transit Intent tail -> tail // as candidate of last hop Link .flatMap(fri -> ImmutableList.copyOf(fri.flowRules()).reverse().stream()) .map(fr -> // find first output port from FlowRule fr.treatment().allInstructions().stream() .filter(OutputInstruction.class::isInstance).findFirst() .map(OutputInstruction.class::cast) .map(OutputInstruction::port) .map(pn -> new ConnectPoint(fr.deviceId(), pn)) .orElse(null) ).filter(Objects::nonNull) .map(src -> services.link().getLink(src, tail)) .filter(Objects::nonNull) .findFirst() .ifPresent(links::add); } /** * Returns true if specified intent is marked with primary marker resource. * * @param intent to test * @return true if it is an Intent taking part of primary transit path */ private boolean isPrimary(Intent intent) { return intent.resources() .contains(marker(PRIMARY_PATH_TAG)); } // returns true if the backup path is the one where the traffic is currently flowing private boolean usingBackup(Set<Link> primary) { Set<Link> activeLinks = Sets.newHashSet(services.link().getActiveLinks()); return primary.isEmpty() || !activeLinks.containsAll(primary); } private void updateHighlights(Highlights highlights, Iterable<Link> links) { for (Link link : links) { ensureNodePresent(highlights, link.src().elementId()); ensureNodePresent(highlights, link.dst().elementId()); } } //TODO duplicate and can be brought in abstract upper class. private void ensureNodePresent(Highlights highlights, ElementId eid) { String id = eid.toString(); NodeHighlight nh = highlights.getNode(id); if (nh == null) { if (eid instanceof DeviceId) { nh = new DeviceHighlight(id); highlights.add((DeviceHighlight) nh); } else if (eid instanceof HostId) { nh = new HostHighlight(id); highlights.add((HostHighlight) nh); } } } private void processLinks(TrafficLinkMap linkMap, Iterable<Link> links, Flavor flavor, boolean isOptical, boolean showTraffic, Set<Mod> mods) { if (links != null) { for (Link link : links) { TrafficLink tlink = linkMap.add(link); tlink.tagFlavor(flavor); tlink.optical(isOptical); if (showTraffic) { tlink.antMarch(true); } tlink.tagMods(mods); } } } //TODO duplicate and can be brought in abstract upper class. private void colorLinks(Highlights highlights, TrafficLinkMap linkMap) { for (TrafficLink tlink : linkMap.biLinks()) { highlights.add(tlink.highlight(StatsType.TAGGED)); } } //TODO duplicate and can be brought in abstract upper class. // Extracts links from the specified flow rule intent resources private Collection<Link> linkResources(Intent installable) { ImmutableList.Builder<Link> builder = ImmutableList.builder(); installable.resources().stream().filter(r -> r instanceof Link) .forEach(r -> builder.add((Link) r)); return builder.build(); } // ======================================================================= // === Background Task // Provides periodic update of traffic information to the client private class TrafficUpdateTask extends TimerTask { @Override public void run() { try { switch (mode) { case SELECTED_INTENT: sendSelectedIntents(); break; default: // RELATED_INTENTS and IDLE modes should never invoke // the background task, but if they do, they have // nothing to do break; } } catch (Exception e) { log.warn("Unable to process protected intent task due to {}", e.getMessage()); log.warn("Boom!", e); } } } }
63007_8
/********************************************************************** * PDump - JSTOR/Harvard Object Validation Environment * Copyright 2003 by JSTOR and the President and Fellows of Harvard College * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 **********************************************************************/ import edu.harvard.hul.ois.jhove.*; import edu.harvard.hul.ois.jhove.module.pdf.*; import java.io.*; /** * Dump contents of PDF file in human-readable format. */ public class PDump extends Dump { /****************************************************************** * MAIN ENTRY POINT. ******************************************************************/ /** * Main entry point. * @param args Command line arguments */ public static void main (String [] args) { if (args.length < 1) { System.err.println ("usage: java PDump file"); System.exit (-1); } try { RandomAccessFile file = new RandomAccessFile (args[0], "r"); Tokenizer tokenizer = new FileTokenizer (file); Token token = null; long offset = 0; while ((token = tokenizer.getNext ()) != null) { System.out.print (leading (offset, 8) + offset + ": "); if (token instanceof ArrayEnd) { System.out.println ("ArrayEnd"); } else if (token instanceof ArrayStart) { System.out.println ("ArrayStart"); } else if (token instanceof Comment) { System.out.println ("Comment \"" + ((Comment) token).getValue () + "\""); } else if (token instanceof DictionaryEnd) { System.out.println ("DictionaryEnd"); } else if (token instanceof DictionaryStart) { System.out.println ("DictionaryStart"); } // else if (token instanceof Hexadecimal) { // System.out.println ("Hexadecimal[" + // (((Hexadecimal) token).isPDFDocEncoding () ? // "PDF" : "UTF-16") + "] \"" + // ((Hexadecimal) token).getValue () + // "\""); // } else if (token instanceof Keyword) { System.out.println ("Keyword \"" + ((Keyword) token).getValue () + "\""); } else if (token instanceof Literal) { System.out.println ("Literal[" + (((Literal)token).isPDFDocEncoding () ? "PDF" : "UTF-16") + "] \"" + ((Literal) token).getValue () + "\""); } else if (token instanceof Name) { System.out.println ("Name \"" + ((Name) token).getValue () + "\""); } else if (token instanceof Numeric) { Numeric numeric = (Numeric) token; if (numeric.isReal ()) { System.out.println ("Numeric " + numeric.getValue ()); } else { System.out.println ("Numeric " + numeric.getIntegerValue ()); } } else if (token instanceof Stream) { System.out.println ("Stream " + ((Stream) token).getLength ()); } else { System.out.println (token); } offset = tokenizer.getOffset (); } } catch (Exception e) { e.printStackTrace (System.err); System.exit (-2); } } }
openpreserve/jhove
jhove-modules/pdf-hul/src/main/java/PDump.java
1,132
// ((Hexadecimal) token).getValue () +
line_comment
nl
/********************************************************************** * PDump - JSTOR/Harvard Object Validation Environment * Copyright 2003 by JSTOR and the President and Fellows of Harvard College * * This program 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 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 **********************************************************************/ import edu.harvard.hul.ois.jhove.*; import edu.harvard.hul.ois.jhove.module.pdf.*; import java.io.*; /** * Dump contents of PDF file in human-readable format. */ public class PDump extends Dump { /****************************************************************** * MAIN ENTRY POINT. ******************************************************************/ /** * Main entry point. * @param args Command line arguments */ public static void main (String [] args) { if (args.length < 1) { System.err.println ("usage: java PDump file"); System.exit (-1); } try { RandomAccessFile file = new RandomAccessFile (args[0], "r"); Tokenizer tokenizer = new FileTokenizer (file); Token token = null; long offset = 0; while ((token = tokenizer.getNext ()) != null) { System.out.print (leading (offset, 8) + offset + ": "); if (token instanceof ArrayEnd) { System.out.println ("ArrayEnd"); } else if (token instanceof ArrayStart) { System.out.println ("ArrayStart"); } else if (token instanceof Comment) { System.out.println ("Comment \"" + ((Comment) token).getValue () + "\""); } else if (token instanceof DictionaryEnd) { System.out.println ("DictionaryEnd"); } else if (token instanceof DictionaryStart) { System.out.println ("DictionaryStart"); } // else if (token instanceof Hexadecimal) { // System.out.println ("Hexadecimal[" + // (((Hexadecimal) token).isPDFDocEncoding () ? // "PDF" : "UTF-16") + "] \"" + // ((Hexadecimal) token).getValue<SUF> // "\""); // } else if (token instanceof Keyword) { System.out.println ("Keyword \"" + ((Keyword) token).getValue () + "\""); } else if (token instanceof Literal) { System.out.println ("Literal[" + (((Literal)token).isPDFDocEncoding () ? "PDF" : "UTF-16") + "] \"" + ((Literal) token).getValue () + "\""); } else if (token instanceof Name) { System.out.println ("Name \"" + ((Name) token).getValue () + "\""); } else if (token instanceof Numeric) { Numeric numeric = (Numeric) token; if (numeric.isReal ()) { System.out.println ("Numeric " + numeric.getValue ()); } else { System.out.println ("Numeric " + numeric.getIntegerValue ()); } } else if (token instanceof Stream) { System.out.println ("Stream " + ((Stream) token).getLength ()); } else { System.out.println (token); } offset = tokenizer.getOffset (); } } catch (Exception e) { e.printStackTrace (System.err); System.exit (-2); } } }
3683_8
package net.oschina.app.bean; import java.io.Serializable; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import net.oschina.app.common.StringUtils; /** * 接口URL实体类 * @author liux (http://my.oschina.net/liux) * @version 1.0 * @created 2012-3-21 */ public class URLs implements Serializable { public final static String HOST = "www.oschina.net";//192.168.1.213 www.oschina.net public final static String HTTP = "http://"; public final static String HTTPS = "https://"; private final static String URL_SPLITTER = "/"; private final static String URL_UNDERLINE = "_"; private final static String URL_API_HOST = HTTP + HOST + URL_SPLITTER; public final static String LOGIN_VALIDATE_HTTP = HTTP + HOST + URL_SPLITTER + "action/api/login_validate"; public final static String LOGIN_VALIDATE_HTTPS = HTTPS + HOST + URL_SPLITTER + "action/api/login_validate"; public final static String NEWS_LIST = URL_API_HOST+"action/api/news_list"; public final static String NEWS_DETAIL = URL_API_HOST+"action/api/news_detail"; public final static String POST_LIST = URL_API_HOST+"action/api/post_list"; public final static String POST_DETAIL = URL_API_HOST+"action/api/post_detail"; public final static String POST_PUB = URL_API_HOST+"action/api/post_pub"; public final static String TWEET_LIST = URL_API_HOST+"action/api/tweet_list"; public final static String TWEET_DETAIL = URL_API_HOST+"action/api/tweet_detail"; public final static String TWEET_PUB = URL_API_HOST+"action/api/tweet_pub"; public final static String TWEET_DELETE = URL_API_HOST+"action/api/tweet_delete"; public final static String ACTIVE_LIST = URL_API_HOST+"action/api/active_list"; public final static String MESSAGE_LIST = URL_API_HOST+"action/api/message_list"; public final static String MESSAGE_DELETE = URL_API_HOST+"action/api/message_delete"; public final static String MESSAGE_PUB = URL_API_HOST+"action/api/message_pub"; public final static String COMMENT_LIST = URL_API_HOST+"action/api/comment_list"; public final static String COMMENT_PUB = URL_API_HOST+"action/api/comment_pub"; public final static String COMMENT_REPLY = URL_API_HOST+"action/api/comment_reply"; public final static String COMMENT_DELETE = URL_API_HOST+"action/api/comment_delete"; public final static String SOFTWARECATALOG_LIST = URL_API_HOST+"action/api/softwarecatalog_list"; public final static String SOFTWARETAG_LIST = URL_API_HOST+"action/api/softwaretag_list"; public final static String SOFTWARE_LIST = URL_API_HOST+"action/api/software_list"; public final static String SOFTWARE_DETAIL = URL_API_HOST+"action/api/software_detail"; public final static String USERBLOG_LIST = URL_API_HOST+"action/api/userblog_list"; public final static String USERBLOG_DELETE = URL_API_HOST+"action/api/userblog_delete"; public final static String BLOG_LIST = URL_API_HOST+"action/api/blog_list"; public final static String BLOG_DETAIL = URL_API_HOST+"action/api/blog_detail"; public final static String BLOGCOMMENT_LIST = URL_API_HOST+"action/api/blogcomment_list"; public final static String BLOGCOMMENT_PUB = URL_API_HOST+"action/api/blogcomment_pub"; public final static String BLOGCOMMENT_DELETE = URL_API_HOST+"action/api/blogcomment_delete"; public final static String MY_INFORMATION = URL_API_HOST+"action/api/my_information"; public final static String USER_INFORMATION = URL_API_HOST+"action/api/user_information"; public final static String USER_UPDATERELATION = URL_API_HOST+"action/api/user_updaterelation"; public final static String USER_NOTICE = URL_API_HOST+"action/api/user_notice"; public final static String NOTICE_CLEAR = URL_API_HOST+"action/api/notice_clear"; public final static String FRIENDS_LIST = URL_API_HOST+"action/api/friends_list"; public final static String FAVORITE_LIST = URL_API_HOST+"action/api/favorite_list"; public final static String FAVORITE_ADD = URL_API_HOST+"action/api/favorite_add"; public final static String FAVORITE_DELETE = URL_API_HOST+"action/api/favorite_delete"; public final static String SEARCH_LIST = URL_API_HOST+"action/api/search_list"; public final static String PORTRAIT_UPDATE = URL_API_HOST+"action/api/portrait_update"; public final static String UPDATE_VERSION = URL_API_HOST+"MobileAppVersion.xml"; private final static String URL_HOST = "oschina.net"; private final static String URL_WWW_HOST = "www."+URL_HOST; private final static String URL_MY_HOST = "my."+URL_HOST; private final static String URL_TYPE_NEWS = URL_WWW_HOST + URL_SPLITTER + "news" + URL_SPLITTER; private final static String URL_TYPE_SOFTWARE = URL_WWW_HOST + URL_SPLITTER + "p" + URL_SPLITTER; private final static String URL_TYPE_QUESTION = URL_WWW_HOST + URL_SPLITTER + "question" + URL_SPLITTER; private final static String URL_TYPE_BLOG = URL_SPLITTER + "blog" + URL_SPLITTER; private final static String URL_TYPE_TWEET = URL_SPLITTER + "tweet" + URL_SPLITTER; private final static String URL_TYPE_ZONE = URL_MY_HOST + URL_SPLITTER + "u" + URL_SPLITTER; private final static String URL_TYPE_QUESTION_TAG = URL_TYPE_QUESTION + "tag" + URL_SPLITTER; public final static int URL_OBJ_TYPE_OTHER = 0x000; public final static int URL_OBJ_TYPE_NEWS = 0x001; public final static int URL_OBJ_TYPE_SOFTWARE = 0x002; public final static int URL_OBJ_TYPE_QUESTION = 0x003; public final static int URL_OBJ_TYPE_ZONE = 0x004; public final static int URL_OBJ_TYPE_BLOG = 0x005; public final static int URL_OBJ_TYPE_TWEET = 0x006; public final static int URL_OBJ_TYPE_QUESTION_TAG = 0x007; private int objId; private String objKey = ""; private int objType; public int getObjId() { return objId; } public void setObjId(int objId) { this.objId = objId; } public String getObjKey() { return objKey; } public void setObjKey(String objKey) { this.objKey = objKey; } public int getObjType() { return objType; } public void setObjType(int objType) { this.objType = objType; } /** * 转化URL为URLs实体 * @param path * @return 不能转化的链接返回null */ public final static URLs parseURL(String path) { if(StringUtils.isEmpty(path))return null; path = formatURL(path); URLs urls = null; String objId = ""; try { URL url = new URL(path); //站内链接 if(url.getHost().contains(URL_HOST)){ urls = new URLs(); //www if(path.contains(URL_WWW_HOST )){ //新闻 www.oschina.net/news/27259/mobile-internet-market-is-small if(path.contains(URL_TYPE_NEWS)){ objId = parseObjId(path, URL_TYPE_NEWS); urls.setObjId(StringUtils.toInt(objId)); urls.setObjType(URL_OBJ_TYPE_NEWS); } //软件 www.oschina.net/p/jx else if(path.contains(URL_TYPE_SOFTWARE)){ urls.setObjKey(parseObjKey(path, URL_TYPE_SOFTWARE)); urls.setObjType(URL_OBJ_TYPE_SOFTWARE); } //问答 else if(path.contains(URL_TYPE_QUESTION)){ //问答-标签 http://www.oschina.net/question/tag/python if(path.contains(URL_TYPE_QUESTION_TAG)){ urls.setObjKey(parseObjKey(path, URL_TYPE_QUESTION_TAG)); urls.setObjType(URL_OBJ_TYPE_QUESTION_TAG); } //问答 www.oschina.net/question/12_45738 else{ objId = parseObjId(path, URL_TYPE_QUESTION); String[] _tmp = objId.split(URL_UNDERLINE); urls.setObjId(StringUtils.toInt(_tmp[1])); urls.setObjType(URL_OBJ_TYPE_QUESTION); } } //other else{ urls.setObjKey(path); urls.setObjType(URL_OBJ_TYPE_OTHER); } } //my else if(path.contains(URL_MY_HOST)){ //博客 my.oschina.net/szpengvictor/blog/50879 if(path.contains(URL_TYPE_BLOG)){ objId = parseObjId(path, URL_TYPE_BLOG); urls.setObjId(StringUtils.toInt(objId)); urls.setObjType(URL_OBJ_TYPE_BLOG); } //动弹 my.oschina.net/dong706/tweet/612947 else if(path.contains(URL_TYPE_TWEET)){ objId = parseObjId(path, URL_TYPE_TWEET); urls.setObjId(StringUtils.toInt(objId)); urls.setObjType(URL_OBJ_TYPE_TWEET); } //个人专页 my.oschina.net/u/12 else if(path.contains(URL_TYPE_ZONE)){ objId = parseObjId(path, URL_TYPE_ZONE); urls.setObjId(StringUtils.toInt(objId)); urls.setObjType(URL_OBJ_TYPE_ZONE); } else{ //另一种个人专页 my.oschina.net/dong706 int p = path.indexOf(URL_MY_HOST+URL_SPLITTER) + (URL_MY_HOST+URL_SPLITTER).length(); String str = path.substring(p); if(!str.contains(URL_SPLITTER)){ urls.setObjKey(str); urls.setObjType(URL_OBJ_TYPE_ZONE); } //other else{ urls.setObjKey(path); urls.setObjType(URL_OBJ_TYPE_OTHER); } } } //other else{ urls.setObjKey(path); urls.setObjType(URL_OBJ_TYPE_OTHER); } } } catch (Exception e) { e.printStackTrace(); urls = null; } return urls; } /** * 解析url获得objId * @param path * @param url_type * @return */ private final static String parseObjId(String path, String url_type){ String objId = ""; int p = 0; String str = ""; String[] tmp = null; p = path.indexOf(url_type) + url_type.length(); str = path.substring(p); if(str.contains(URL_SPLITTER)){ tmp = str.split(URL_SPLITTER); objId = tmp[0]; }else{ objId = str; } return objId; } /** * 解析url获得objKey * @param path * @param url_type * @return */ private final static String parseObjKey(String path, String url_type){ path = URLDecoder.decode(path); String objKey = ""; int p = 0; String str = ""; String[] tmp = null; p = path.indexOf(url_type) + url_type.length(); str = path.substring(p); if(str.contains("?")){ tmp = str.split("?"); objKey = tmp[0]; }else{ objKey = str; } return objKey; } /** * 对URL进行格式处理 * @param path * @return */ private final static String formatURL(String path) { if(path.startsWith("http://") || path.startsWith("https://")) return path; return "http://" + URLEncoder.encode(path); } }
openproject/android-app
src/net/oschina/app/bean/URLs.java
3,853
//动弹 my.oschina.net/dong706/tweet/612947
line_comment
nl
package net.oschina.app.bean; import java.io.Serializable; import java.net.URL; import java.net.URLDecoder; import java.net.URLEncoder; import net.oschina.app.common.StringUtils; /** * 接口URL实体类 * @author liux (http://my.oschina.net/liux) * @version 1.0 * @created 2012-3-21 */ public class URLs implements Serializable { public final static String HOST = "www.oschina.net";//192.168.1.213 www.oschina.net public final static String HTTP = "http://"; public final static String HTTPS = "https://"; private final static String URL_SPLITTER = "/"; private final static String URL_UNDERLINE = "_"; private final static String URL_API_HOST = HTTP + HOST + URL_SPLITTER; public final static String LOGIN_VALIDATE_HTTP = HTTP + HOST + URL_SPLITTER + "action/api/login_validate"; public final static String LOGIN_VALIDATE_HTTPS = HTTPS + HOST + URL_SPLITTER + "action/api/login_validate"; public final static String NEWS_LIST = URL_API_HOST+"action/api/news_list"; public final static String NEWS_DETAIL = URL_API_HOST+"action/api/news_detail"; public final static String POST_LIST = URL_API_HOST+"action/api/post_list"; public final static String POST_DETAIL = URL_API_HOST+"action/api/post_detail"; public final static String POST_PUB = URL_API_HOST+"action/api/post_pub"; public final static String TWEET_LIST = URL_API_HOST+"action/api/tweet_list"; public final static String TWEET_DETAIL = URL_API_HOST+"action/api/tweet_detail"; public final static String TWEET_PUB = URL_API_HOST+"action/api/tweet_pub"; public final static String TWEET_DELETE = URL_API_HOST+"action/api/tweet_delete"; public final static String ACTIVE_LIST = URL_API_HOST+"action/api/active_list"; public final static String MESSAGE_LIST = URL_API_HOST+"action/api/message_list"; public final static String MESSAGE_DELETE = URL_API_HOST+"action/api/message_delete"; public final static String MESSAGE_PUB = URL_API_HOST+"action/api/message_pub"; public final static String COMMENT_LIST = URL_API_HOST+"action/api/comment_list"; public final static String COMMENT_PUB = URL_API_HOST+"action/api/comment_pub"; public final static String COMMENT_REPLY = URL_API_HOST+"action/api/comment_reply"; public final static String COMMENT_DELETE = URL_API_HOST+"action/api/comment_delete"; public final static String SOFTWARECATALOG_LIST = URL_API_HOST+"action/api/softwarecatalog_list"; public final static String SOFTWARETAG_LIST = URL_API_HOST+"action/api/softwaretag_list"; public final static String SOFTWARE_LIST = URL_API_HOST+"action/api/software_list"; public final static String SOFTWARE_DETAIL = URL_API_HOST+"action/api/software_detail"; public final static String USERBLOG_LIST = URL_API_HOST+"action/api/userblog_list"; public final static String USERBLOG_DELETE = URL_API_HOST+"action/api/userblog_delete"; public final static String BLOG_LIST = URL_API_HOST+"action/api/blog_list"; public final static String BLOG_DETAIL = URL_API_HOST+"action/api/blog_detail"; public final static String BLOGCOMMENT_LIST = URL_API_HOST+"action/api/blogcomment_list"; public final static String BLOGCOMMENT_PUB = URL_API_HOST+"action/api/blogcomment_pub"; public final static String BLOGCOMMENT_DELETE = URL_API_HOST+"action/api/blogcomment_delete"; public final static String MY_INFORMATION = URL_API_HOST+"action/api/my_information"; public final static String USER_INFORMATION = URL_API_HOST+"action/api/user_information"; public final static String USER_UPDATERELATION = URL_API_HOST+"action/api/user_updaterelation"; public final static String USER_NOTICE = URL_API_HOST+"action/api/user_notice"; public final static String NOTICE_CLEAR = URL_API_HOST+"action/api/notice_clear"; public final static String FRIENDS_LIST = URL_API_HOST+"action/api/friends_list"; public final static String FAVORITE_LIST = URL_API_HOST+"action/api/favorite_list"; public final static String FAVORITE_ADD = URL_API_HOST+"action/api/favorite_add"; public final static String FAVORITE_DELETE = URL_API_HOST+"action/api/favorite_delete"; public final static String SEARCH_LIST = URL_API_HOST+"action/api/search_list"; public final static String PORTRAIT_UPDATE = URL_API_HOST+"action/api/portrait_update"; public final static String UPDATE_VERSION = URL_API_HOST+"MobileAppVersion.xml"; private final static String URL_HOST = "oschina.net"; private final static String URL_WWW_HOST = "www."+URL_HOST; private final static String URL_MY_HOST = "my."+URL_HOST; private final static String URL_TYPE_NEWS = URL_WWW_HOST + URL_SPLITTER + "news" + URL_SPLITTER; private final static String URL_TYPE_SOFTWARE = URL_WWW_HOST + URL_SPLITTER + "p" + URL_SPLITTER; private final static String URL_TYPE_QUESTION = URL_WWW_HOST + URL_SPLITTER + "question" + URL_SPLITTER; private final static String URL_TYPE_BLOG = URL_SPLITTER + "blog" + URL_SPLITTER; private final static String URL_TYPE_TWEET = URL_SPLITTER + "tweet" + URL_SPLITTER; private final static String URL_TYPE_ZONE = URL_MY_HOST + URL_SPLITTER + "u" + URL_SPLITTER; private final static String URL_TYPE_QUESTION_TAG = URL_TYPE_QUESTION + "tag" + URL_SPLITTER; public final static int URL_OBJ_TYPE_OTHER = 0x000; public final static int URL_OBJ_TYPE_NEWS = 0x001; public final static int URL_OBJ_TYPE_SOFTWARE = 0x002; public final static int URL_OBJ_TYPE_QUESTION = 0x003; public final static int URL_OBJ_TYPE_ZONE = 0x004; public final static int URL_OBJ_TYPE_BLOG = 0x005; public final static int URL_OBJ_TYPE_TWEET = 0x006; public final static int URL_OBJ_TYPE_QUESTION_TAG = 0x007; private int objId; private String objKey = ""; private int objType; public int getObjId() { return objId; } public void setObjId(int objId) { this.objId = objId; } public String getObjKey() { return objKey; } public void setObjKey(String objKey) { this.objKey = objKey; } public int getObjType() { return objType; } public void setObjType(int objType) { this.objType = objType; } /** * 转化URL为URLs实体 * @param path * @return 不能转化的链接返回null */ public final static URLs parseURL(String path) { if(StringUtils.isEmpty(path))return null; path = formatURL(path); URLs urls = null; String objId = ""; try { URL url = new URL(path); //站内链接 if(url.getHost().contains(URL_HOST)){ urls = new URLs(); //www if(path.contains(URL_WWW_HOST )){ //新闻 www.oschina.net/news/27259/mobile-internet-market-is-small if(path.contains(URL_TYPE_NEWS)){ objId = parseObjId(path, URL_TYPE_NEWS); urls.setObjId(StringUtils.toInt(objId)); urls.setObjType(URL_OBJ_TYPE_NEWS); } //软件 www.oschina.net/p/jx else if(path.contains(URL_TYPE_SOFTWARE)){ urls.setObjKey(parseObjKey(path, URL_TYPE_SOFTWARE)); urls.setObjType(URL_OBJ_TYPE_SOFTWARE); } //问答 else if(path.contains(URL_TYPE_QUESTION)){ //问答-标签 http://www.oschina.net/question/tag/python if(path.contains(URL_TYPE_QUESTION_TAG)){ urls.setObjKey(parseObjKey(path, URL_TYPE_QUESTION_TAG)); urls.setObjType(URL_OBJ_TYPE_QUESTION_TAG); } //问答 www.oschina.net/question/12_45738 else{ objId = parseObjId(path, URL_TYPE_QUESTION); String[] _tmp = objId.split(URL_UNDERLINE); urls.setObjId(StringUtils.toInt(_tmp[1])); urls.setObjType(URL_OBJ_TYPE_QUESTION); } } //other else{ urls.setObjKey(path); urls.setObjType(URL_OBJ_TYPE_OTHER); } } //my else if(path.contains(URL_MY_HOST)){ //博客 my.oschina.net/szpengvictor/blog/50879 if(path.contains(URL_TYPE_BLOG)){ objId = parseObjId(path, URL_TYPE_BLOG); urls.setObjId(StringUtils.toInt(objId)); urls.setObjType(URL_OBJ_TYPE_BLOG); } //动弹 <SUF> else if(path.contains(URL_TYPE_TWEET)){ objId = parseObjId(path, URL_TYPE_TWEET); urls.setObjId(StringUtils.toInt(objId)); urls.setObjType(URL_OBJ_TYPE_TWEET); } //个人专页 my.oschina.net/u/12 else if(path.contains(URL_TYPE_ZONE)){ objId = parseObjId(path, URL_TYPE_ZONE); urls.setObjId(StringUtils.toInt(objId)); urls.setObjType(URL_OBJ_TYPE_ZONE); } else{ //另一种个人专页 my.oschina.net/dong706 int p = path.indexOf(URL_MY_HOST+URL_SPLITTER) + (URL_MY_HOST+URL_SPLITTER).length(); String str = path.substring(p); if(!str.contains(URL_SPLITTER)){ urls.setObjKey(str); urls.setObjType(URL_OBJ_TYPE_ZONE); } //other else{ urls.setObjKey(path); urls.setObjType(URL_OBJ_TYPE_OTHER); } } } //other else{ urls.setObjKey(path); urls.setObjType(URL_OBJ_TYPE_OTHER); } } } catch (Exception e) { e.printStackTrace(); urls = null; } return urls; } /** * 解析url获得objId * @param path * @param url_type * @return */ private final static String parseObjId(String path, String url_type){ String objId = ""; int p = 0; String str = ""; String[] tmp = null; p = path.indexOf(url_type) + url_type.length(); str = path.substring(p); if(str.contains(URL_SPLITTER)){ tmp = str.split(URL_SPLITTER); objId = tmp[0]; }else{ objId = str; } return objId; } /** * 解析url获得objKey * @param path * @param url_type * @return */ private final static String parseObjKey(String path, String url_type){ path = URLDecoder.decode(path); String objKey = ""; int p = 0; String str = ""; String[] tmp = null; p = path.indexOf(url_type) + url_type.length(); str = path.substring(p); if(str.contains("?")){ tmp = str.split("?"); objKey = tmp[0]; }else{ objKey = str; } return objKey; } /** * 对URL进行格式处理 * @param path * @return */ private final static String formatURL(String path) { if(path.startsWith("http://") || path.startsWith("https://")) return path; return "http://" + URLEncoder.encode(path); } }
80895_10
/* * Created on 21-feb-2006 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package microdev.db; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.dbutils.BasicRowProcessor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author andrea * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class QueryExecutor { private Log log = LogFactory.getLog(QueryExecutor.class); private Connection conn = null; /** TODO */ public void execute(String query) { // TODO } public List executeQuery(String query) { return executeQuery(query, null); } public List executeQuery(String query, QueryTips tips) { // aggrega temporaneamente i risultati ArrayList vect = new ArrayList(); String order_query = ""; String limit_query = ""; if ( tips != null ) { order_query = tips.getOrderQuery(); limit_query = tips.getLimitQuery(); } String final_query = query + order_query + limit_query; Statement stmt = null; ResultSet rs = null; try { conn = ConnectionUtil.currentConnection(); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); //log.debug("executing query: " + final_query); rs = stmt.executeQuery(final_query); ResultSetMetaData meta = rs.getMetaData(); while (rs.next()) { //ResultRecord rec = new ResultRecord(); Map rec = new LinkedHashMap(); for ( int i=1; i <= meta.getColumnCount(); i++ ) { // log.debug("meta.getColumnLabel(i):" + meta.getColumnLabel(i)); // log.debug("meta.getColumnClassName(i):" + meta.getColumnClassName(i)); // log.debug("meta.getColumnType(i):" + meta.getColumnType(i)); // log.debug("meta.getColumnTypeName(i):" + meta.getColumnTypeName(i)); // // log.debug("rs.getObject(i):" + rs.getObject(i)); // log.debug("rs.getObject(i).getClass():" + rs.getObject(i).getClass()); rec.put(meta.getColumnLabel(i),rs.getObject(i)); } //log.debug("added record: " + rec); vect.add(rec); } rs.close(); } catch (Exception e) { log.error("",e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) {} stmt = null; } //In realt� la connessione dovrebbe essere chiusa dal ConnectionFilter //In questo caso sarebbe meglio chiedere la connessione ad ibatis e lasciarla //chiudere a lui. //Per motivi di tempo � stato utilizzato un workaround ovvero si � deciso //di bypassare il connection filter e di fare il post processing alla fine di questo metodo. //Per due motivi: il primo � che non avrebbe senso aggiungere il connection filter di //questo modulo al web.xml, il secondo � che si ha bisogno di una soluzione immediata //La soluzione migliore � quella iniziale ConnectionUtil.closeConnection(); } if ( vect.size() > 0 ) { //return (ResultRecord[]) vect.toArray(new ResultRecord[vect.size()]); return vect; } return null; } public List executeQueryTyped(String query, Class type, QueryTips tips){ // aggrega temporaneamente i risultati ArrayList vect = new ArrayList(); String order_query = ""; String limit_query = ""; if ( tips != null ) { order_query = tips.getOrderQuery(); limit_query = tips.getLimitQuery(); log.debug("order query:" + order_query); log.debug("limit query:" + limit_query); } String final_query = query + order_query + limit_query; Statement stmt = null; ResultSet rs = null; try { conn = ConnectionUtil.currentConnection(); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); log.debug(final_query); rs = stmt.executeQuery(final_query); while (rs.next()) { BasicRowProcessor proc = new BasicRowProcessor(); Object obj = proc.toBean(rs, type); //log.debug("added object: " + obj); vect.add(obj); } rs.close(); } catch (Exception e) { log.error("",e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) {} stmt = null; } //In realt� la connessione dovrebbe essere chiusa dal ConnectionFilter //In questo caso sarebbe meglio chiedere la connessione ad ibatis e lasciarla //chiudere a lui. //Per motivi di tempo � stato utilizzato un workaround ovvero si � deciso //di bypassare il connection filter e di fare il post processing alla fine di questo metodo. //Per due motivi: il primo � che non avrebbe senso aggiungere il connection filter di //questo modulo al web.xml, il secondo � che si ha bisogno di una soluzione immediata //La soluzione migliore � quella iniziale ConnectionUtil.closeConnection(); } if ( vect.size() > 0 ) { //return (ResultRecord[]) vect.toArray(new ResultRecord[vect.size()]); return vect; } return null; } }
openrecordz/openrecordz-server
src/main/java/microdev/db/QueryExecutor.java
1,713
// log.debug("rs.getObject(i).getClass():" + rs.getObject(i).getClass());
line_comment
nl
/* * Created on 21-feb-2006 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package microdev.db; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.dbutils.BasicRowProcessor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author andrea * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class QueryExecutor { private Log log = LogFactory.getLog(QueryExecutor.class); private Connection conn = null; /** TODO */ public void execute(String query) { // TODO } public List executeQuery(String query) { return executeQuery(query, null); } public List executeQuery(String query, QueryTips tips) { // aggrega temporaneamente i risultati ArrayList vect = new ArrayList(); String order_query = ""; String limit_query = ""; if ( tips != null ) { order_query = tips.getOrderQuery(); limit_query = tips.getLimitQuery(); } String final_query = query + order_query + limit_query; Statement stmt = null; ResultSet rs = null; try { conn = ConnectionUtil.currentConnection(); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); //log.debug("executing query: " + final_query); rs = stmt.executeQuery(final_query); ResultSetMetaData meta = rs.getMetaData(); while (rs.next()) { //ResultRecord rec = new ResultRecord(); Map rec = new LinkedHashMap(); for ( int i=1; i <= meta.getColumnCount(); i++ ) { // log.debug("meta.getColumnLabel(i):" + meta.getColumnLabel(i)); // log.debug("meta.getColumnClassName(i):" + meta.getColumnClassName(i)); // log.debug("meta.getColumnType(i):" + meta.getColumnType(i)); // log.debug("meta.getColumnTypeName(i):" + meta.getColumnTypeName(i)); // // log.debug("rs.getObject(i):" + rs.getObject(i)); // log.debug("rs.getObject(i).getClass():" +<SUF> rec.put(meta.getColumnLabel(i),rs.getObject(i)); } //log.debug("added record: " + rec); vect.add(rec); } rs.close(); } catch (Exception e) { log.error("",e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) {} stmt = null; } //In realt� la connessione dovrebbe essere chiusa dal ConnectionFilter //In questo caso sarebbe meglio chiedere la connessione ad ibatis e lasciarla //chiudere a lui. //Per motivi di tempo � stato utilizzato un workaround ovvero si � deciso //di bypassare il connection filter e di fare il post processing alla fine di questo metodo. //Per due motivi: il primo � che non avrebbe senso aggiungere il connection filter di //questo modulo al web.xml, il secondo � che si ha bisogno di una soluzione immediata //La soluzione migliore � quella iniziale ConnectionUtil.closeConnection(); } if ( vect.size() > 0 ) { //return (ResultRecord[]) vect.toArray(new ResultRecord[vect.size()]); return vect; } return null; } public List executeQueryTyped(String query, Class type, QueryTips tips){ // aggrega temporaneamente i risultati ArrayList vect = new ArrayList(); String order_query = ""; String limit_query = ""; if ( tips != null ) { order_query = tips.getOrderQuery(); limit_query = tips.getLimitQuery(); log.debug("order query:" + order_query); log.debug("limit query:" + limit_query); } String final_query = query + order_query + limit_query; Statement stmt = null; ResultSet rs = null; try { conn = ConnectionUtil.currentConnection(); stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); log.debug(final_query); rs = stmt.executeQuery(final_query); while (rs.next()) { BasicRowProcessor proc = new BasicRowProcessor(); Object obj = proc.toBean(rs, type); //log.debug("added object: " + obj); vect.add(obj); } rs.close(); } catch (Exception e) { log.error("",e); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) {} stmt = null; } //In realt� la connessione dovrebbe essere chiusa dal ConnectionFilter //In questo caso sarebbe meglio chiedere la connessione ad ibatis e lasciarla //chiudere a lui. //Per motivi di tempo � stato utilizzato un workaround ovvero si � deciso //di bypassare il connection filter e di fare il post processing alla fine di questo metodo. //Per due motivi: il primo � che non avrebbe senso aggiungere il connection filter di //questo modulo al web.xml, il secondo � che si ha bisogno di una soluzione immediata //La soluzione migliore � quella iniziale ConnectionUtil.closeConnection(); } if ( vect.size() > 0 ) { //return (ResultRecord[]) vect.toArray(new ResultRecord[vect.size()]); return vect; } return null; } }
189584_1
package com.rs.utilities; import java.util.concurrent.atomic.AtomicInteger; /** * The container class that contains functions to simplify the modification of a * number. * <p> * <p> * This class is similar in functionality to {@link AtomicInteger} but does not * support atomic operations, and therefore should not be used across multiple * threads. * @author lare96 <http://github.com/lare96> */ public final class MutableNumber extends Number implements Comparable<MutableNumber> { // pure lare code, echt ongelofelijk dit /** * The constant serial version UID for serialization. */ private static final long serialVersionUID = -7475363158492415879L; /** * The value present within this counter. */ private int value; /** * Creates a new {@link MutableNumber} with {@code value}. * @param value the value present within this counter. */ public MutableNumber(int value) { this.value = value; } /** * Creates a new {@link MutableNumber} with a value of {@code 0}. */ public MutableNumber() { this(0); } @Override public String toString() { return Integer.toString(value); } @Override public int hashCode() { return Integer.hashCode(value); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(!(obj instanceof MutableNumber)) return false; MutableNumber other = (MutableNumber) obj; return value == other.value; } @Override public int compareTo(MutableNumber o) { return Integer.compare(value, o.value); } /** * {@inheritDoc} * <p> * This function equates to the {@link MutableNumber#get()} function. */ @Override public int intValue() { return value; } @Override public long longValue() { return (long) value; } @Override public float floatValue() { return (float) value; } @Override public double doubleValue() { return (double) value; } /** * Returns the value within this counter and then increments it by * {@code amount} to a maximum of {@code maximum}. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value before it is incremented. */ public int getAndIncrement(int amount, int maximum) { int val = value; value += amount; if(value > maximum) value = maximum; return val; } /** * Returns the value within this counter and then increments it by * {@code amount}. * @param amount the amount to increment it by. * @return the value before it is incremented. */ public int getAndIncrement(int amount) { return getAndIncrement(amount, Integer.MAX_VALUE); } /** * Returns the value within this counter and then increments it by an amount * of {@code 1}. * @return the value before it is incremented. */ public int getAndIncrement() { return getAndIncrement(1); } //guys I have to go, it's me stan //It's taraweeh time, gonna go pray and come back //u guys can stay on teamviewer just shut it down when ur done, ill //tell my mom not to close the laptop //just dont do stupid stuff please xD ok -at rtnp ty <3 /** * Increments the value within this counter by {@code amount} to a maximum * of {@code maximum} and then returns it. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value after it is incremented. */ public int incrementAndGet(int amount, int maximum) { value += amount; if(value > maximum) value = maximum; return value; } /** * Increments the value within this counter by {@code amount} and then * returns it. * @param amount the amount to increment it by. * @return the value after it is incremented. */ public int incrementAndGet(int amount) { return incrementAndGet(amount, Integer.MAX_VALUE); } /** * Increments the value within this counter by {@code 1} and then returns * it. * @return the value after it is incremented. */ public int incrementAndGet() { return incrementAndGet(1); } /** * Returns the value within this counter and then decrements it by * {@code amount} to a minimum of {@code minimum}. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value before it is decremented. */ public int getAndDecrement(int amount, int minimum) { int val = value; value -= amount; if(value < minimum) value = minimum; return val; } /** * Returns the value within this counter and then decrements it by * {@code amount}. * @param amount the amount to decrement it by. * @return the value before it is decremented. */ public int getAndDecrement(int amount) { return getAndDecrement(amount, Integer.MIN_VALUE); } /** * Returns the value within this counter and then decrements it by an amount * of {@code 1}. * @return the value before it is decremented. */ public int getAndDecrement() { return getAndDecrement(1); } /** * Decrements the value within this counter by {@code amount} to a minimum * of {@code minimum} and then returns it. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value after it is decremented. */ public int decrementAndGet(int amount, int minimum) { value -= amount; if(value < minimum) value = minimum; return value; } /** * Decrements the value within this counter by {@code amount} and then * returns it. * @param amount the amount to decrement it by. * @return the value after it is decremented. */ public int decrementAndGet(int amount) { return decrementAndGet(amount, Integer.MIN_VALUE); } /** * Decrements the value within this counter by {@code 1} and then returns * it. * @return the value after it is decremented. */ public int decrementAndGet() { return decrementAndGet(1); } /** * Gets the value present within this counter. This function equates to the * inherited {@link MutableNumber#intValue()} function. * @return the value present. */ public int get() { return value; } /** * Sets the value within this container to {@code value}. * @param value the new value to set. */ public void set(int value) { this.value = value; } }
openrsx/open633-server
src/com/rs/utilities/MutableNumber.java
1,978
// pure lare code, echt ongelofelijk dit
line_comment
nl
package com.rs.utilities; import java.util.concurrent.atomic.AtomicInteger; /** * The container class that contains functions to simplify the modification of a * number. * <p> * <p> * This class is similar in functionality to {@link AtomicInteger} but does not * support atomic operations, and therefore should not be used across multiple * threads. * @author lare96 <http://github.com/lare96> */ public final class MutableNumber extends Number implements Comparable<MutableNumber> { // pure lare<SUF> /** * The constant serial version UID for serialization. */ private static final long serialVersionUID = -7475363158492415879L; /** * The value present within this counter. */ private int value; /** * Creates a new {@link MutableNumber} with {@code value}. * @param value the value present within this counter. */ public MutableNumber(int value) { this.value = value; } /** * Creates a new {@link MutableNumber} with a value of {@code 0}. */ public MutableNumber() { this(0); } @Override public String toString() { return Integer.toString(value); } @Override public int hashCode() { return Integer.hashCode(value); } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(!(obj instanceof MutableNumber)) return false; MutableNumber other = (MutableNumber) obj; return value == other.value; } @Override public int compareTo(MutableNumber o) { return Integer.compare(value, o.value); } /** * {@inheritDoc} * <p> * This function equates to the {@link MutableNumber#get()} function. */ @Override public int intValue() { return value; } @Override public long longValue() { return (long) value; } @Override public float floatValue() { return (float) value; } @Override public double doubleValue() { return (double) value; } /** * Returns the value within this counter and then increments it by * {@code amount} to a maximum of {@code maximum}. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value before it is incremented. */ public int getAndIncrement(int amount, int maximum) { int val = value; value += amount; if(value > maximum) value = maximum; return val; } /** * Returns the value within this counter and then increments it by * {@code amount}. * @param amount the amount to increment it by. * @return the value before it is incremented. */ public int getAndIncrement(int amount) { return getAndIncrement(amount, Integer.MAX_VALUE); } /** * Returns the value within this counter and then increments it by an amount * of {@code 1}. * @return the value before it is incremented. */ public int getAndIncrement() { return getAndIncrement(1); } //guys I have to go, it's me stan //It's taraweeh time, gonna go pray and come back //u guys can stay on teamviewer just shut it down when ur done, ill //tell my mom not to close the laptop //just dont do stupid stuff please xD ok -at rtnp ty <3 /** * Increments the value within this counter by {@code amount} to a maximum * of {@code maximum} and then returns it. * @param amount the amount to increment it by. * @param maximum the maximum amount it will be incremented to. * @return the value after it is incremented. */ public int incrementAndGet(int amount, int maximum) { value += amount; if(value > maximum) value = maximum; return value; } /** * Increments the value within this counter by {@code amount} and then * returns it. * @param amount the amount to increment it by. * @return the value after it is incremented. */ public int incrementAndGet(int amount) { return incrementAndGet(amount, Integer.MAX_VALUE); } /** * Increments the value within this counter by {@code 1} and then returns * it. * @return the value after it is incremented. */ public int incrementAndGet() { return incrementAndGet(1); } /** * Returns the value within this counter and then decrements it by * {@code amount} to a minimum of {@code minimum}. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value before it is decremented. */ public int getAndDecrement(int amount, int minimum) { int val = value; value -= amount; if(value < minimum) value = minimum; return val; } /** * Returns the value within this counter and then decrements it by * {@code amount}. * @param amount the amount to decrement it by. * @return the value before it is decremented. */ public int getAndDecrement(int amount) { return getAndDecrement(amount, Integer.MIN_VALUE); } /** * Returns the value within this counter and then decrements it by an amount * of {@code 1}. * @return the value before it is decremented. */ public int getAndDecrement() { return getAndDecrement(1); } /** * Decrements the value within this counter by {@code amount} to a minimum * of {@code minimum} and then returns it. * @param amount the amount to decrement it by. * @param minimum the minimum amount it will be decremented to. * @return the value after it is decremented. */ public int decrementAndGet(int amount, int minimum) { value -= amount; if(value < minimum) value = minimum; return value; } /** * Decrements the value within this counter by {@code amount} and then * returns it. * @param amount the amount to decrement it by. * @return the value after it is decremented. */ public int decrementAndGet(int amount) { return decrementAndGet(amount, Integer.MIN_VALUE); } /** * Decrements the value within this counter by {@code 1} and then returns * it. * @return the value after it is decremented. */ public int decrementAndGet() { return decrementAndGet(1); } /** * Gets the value present within this counter. This function equates to the * inherited {@link MutableNumber#intValue()} function. * @return the value present. */ public int get() { return value; } /** * Sets the value within this container to {@code value}. * @param value the new value to set. */ public void set(int value) { this.value = value; } }
214090_16
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.common.inject; import org.opensearch.common.inject.binder.AnnotatedBindingBuilder; import org.opensearch.common.inject.binder.AnnotatedElementBuilder; import org.opensearch.common.inject.binder.LinkedBindingBuilder; import org.opensearch.common.inject.spi.Message; /** * A module whose configuration information is hidden from its environment by default. Only bindings * that are explicitly exposed will be available to other modules and to the users of the injector. * This module may expose the bindings it creates and the bindings of the modules it installs. * <p> * A private module can be nested within a regular module or within another private module using * {@link Binder#install install()}. Its bindings live in a new environment that inherits bindings, * type converters, scopes, and interceptors from the surrounding ("parent") environment. When you * nest multiple private modules, the result is a tree of environments where the injector's * environment is the root. * <p> * Guice EDSL bindings can be exposed with {@link #expose(Class) expose()}. {@literal @}{@link * org.opensearch.common.inject.Provides Provides} bindings can be exposed with the {@literal @}{@link * Exposed} annotation: * <pre> * public class FooBarBazModule extends PrivateModule { * protected void configure() { * bind(Foo.class).to(RealFoo.class); * expose(Foo.class); * * install(new TransactionalBarModule()); * expose(Bar.class).annotatedWith(Transactional.class); * * bind(SomeImplementationDetail.class); * install(new MoreImplementationDetailsModule()); * } * * {@literal @}Provides {@literal @}Exposed * public Baz provideBaz() { * return new SuperBaz(); * } * } * </pre> * <p> * The scope of a binding is constrained to its environment. A singleton bound in a private * module will be unique to its environment. But a binding for the same type in a different private * module will yield a different instance. * <p> * A shared binding that injects the {@code Injector} gets the root injector, which only has * access to bindings in the root environment. An explicit binding that injects the {@code Injector} * gets access to all bindings in the child environment. * <p> * To promote a just-in-time binding to an explicit binding, bind it: * <pre> * bind(FooImpl.class); * </pre> * * @author [email protected] (Jesse Wilson) * @since 2.0 * * @opensearch.internal */ public abstract class PrivateModule implements Module { /** * Like abstract module, the binder of the current private module */ private PrivateBinder binder; @Override public final synchronized void configure(Binder binder) { if (this.binder != null) { throw new IllegalStateException("Re-entry is not allowed."); } // Guice treats PrivateModules specially and passes in a PrivateBinder automatically. this.binder = (PrivateBinder) binder.skipSources(PrivateModule.class); try { configure(); } finally { this.binder = null; } } /** * Creates bindings and other configurations private to this module. Use {@link #expose(Class) * expose()} to make the bindings in this module available externally. */ protected abstract void configure(); /** * Makes the binding for {@code key} available to other modules and the injector. */ protected final <T> void expose(Key<T> key) { binder.expose(key); } /** * Makes a binding for {@code type} available to other modules and the injector. Use {@link * AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a * binding annotation. */ protected final AnnotatedElementBuilder expose(Class<?> type) { return binder.expose(type); } /** * Makes a binding for {@code type} available to other modules and the injector. Use {@link * AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a * binding annotation. */ protected final AnnotatedElementBuilder expose(TypeLiteral<?> type) { return binder.expose(type); } // everything below is copied from AbstractModule /** * Returns the current binder. */ protected final PrivateBinder binder() { return binder; } /** * @see Binder#bind(Key) */ protected final <T> LinkedBindingBuilder<T> bind(Key<T> key) { return binder.bind(key); } /** * @see Binder#bind(TypeLiteral) */ protected final <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral) { return binder.bind(typeLiteral); } /** * @see Binder#bind(Class) */ protected final <T> AnnotatedBindingBuilder<T> bind(Class<T> clazz) { return binder.bind(clazz); } /** * @see Binder#install(Module) */ protected final void install(Module module) { binder.install(module); } /** * @see Binder#addError(String, Object[]) */ protected final void addError(String message, Object... arguments) { binder.addError(message, arguments); } /** * @see Binder#addError(Throwable) */ protected final void addError(Throwable t) { binder.addError(t); } /** * @see Binder#addError(Message) */ protected final void addError(Message message) { binder.addError(message); } /** * @see Binder#getProvider(Key) */ protected final <T> Provider<T> getProvider(Key<T> key) { return binder.getProvider(key); } /** * @see Binder#getProvider(Class) */ protected final <T> Provider<T> getProvider(Class<T> type) { return binder.getProvider(type); } /** * @see Binder#getMembersInjector(Class) */ protected <T> MembersInjector<T> getMembersInjector(Class<T> type) { return binder.getMembersInjector(type); } /** * @see Binder#getMembersInjector(TypeLiteral) */ protected <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type) { return binder.getMembersInjector(type); } }
opensearch-project/OpenSearch
server/src/main/java/org/opensearch/common/inject/PrivateModule.java
2,039
/** * @see Binder#addError(String, Object[]) */
block_comment
nl
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ /* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ package org.opensearch.common.inject; import org.opensearch.common.inject.binder.AnnotatedBindingBuilder; import org.opensearch.common.inject.binder.AnnotatedElementBuilder; import org.opensearch.common.inject.binder.LinkedBindingBuilder; import org.opensearch.common.inject.spi.Message; /** * A module whose configuration information is hidden from its environment by default. Only bindings * that are explicitly exposed will be available to other modules and to the users of the injector. * This module may expose the bindings it creates and the bindings of the modules it installs. * <p> * A private module can be nested within a regular module or within another private module using * {@link Binder#install install()}. Its bindings live in a new environment that inherits bindings, * type converters, scopes, and interceptors from the surrounding ("parent") environment. When you * nest multiple private modules, the result is a tree of environments where the injector's * environment is the root. * <p> * Guice EDSL bindings can be exposed with {@link #expose(Class) expose()}. {@literal @}{@link * org.opensearch.common.inject.Provides Provides} bindings can be exposed with the {@literal @}{@link * Exposed} annotation: * <pre> * public class FooBarBazModule extends PrivateModule { * protected void configure() { * bind(Foo.class).to(RealFoo.class); * expose(Foo.class); * * install(new TransactionalBarModule()); * expose(Bar.class).annotatedWith(Transactional.class); * * bind(SomeImplementationDetail.class); * install(new MoreImplementationDetailsModule()); * } * * {@literal @}Provides {@literal @}Exposed * public Baz provideBaz() { * return new SuperBaz(); * } * } * </pre> * <p> * The scope of a binding is constrained to its environment. A singleton bound in a private * module will be unique to its environment. But a binding for the same type in a different private * module will yield a different instance. * <p> * A shared binding that injects the {@code Injector} gets the root injector, which only has * access to bindings in the root environment. An explicit binding that injects the {@code Injector} * gets access to all bindings in the child environment. * <p> * To promote a just-in-time binding to an explicit binding, bind it: * <pre> * bind(FooImpl.class); * </pre> * * @author [email protected] (Jesse Wilson) * @since 2.0 * * @opensearch.internal */ public abstract class PrivateModule implements Module { /** * Like abstract module, the binder of the current private module */ private PrivateBinder binder; @Override public final synchronized void configure(Binder binder) { if (this.binder != null) { throw new IllegalStateException("Re-entry is not allowed."); } // Guice treats PrivateModules specially and passes in a PrivateBinder automatically. this.binder = (PrivateBinder) binder.skipSources(PrivateModule.class); try { configure(); } finally { this.binder = null; } } /** * Creates bindings and other configurations private to this module. Use {@link #expose(Class) * expose()} to make the bindings in this module available externally. */ protected abstract void configure(); /** * Makes the binding for {@code key} available to other modules and the injector. */ protected final <T> void expose(Key<T> key) { binder.expose(key); } /** * Makes a binding for {@code type} available to other modules and the injector. Use {@link * AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a * binding annotation. */ protected final AnnotatedElementBuilder expose(Class<?> type) { return binder.expose(type); } /** * Makes a binding for {@code type} available to other modules and the injector. Use {@link * AnnotatedElementBuilder#annotatedWith(Class) annotatedWith()} to expose {@code type} with a * binding annotation. */ protected final AnnotatedElementBuilder expose(TypeLiteral<?> type) { return binder.expose(type); } // everything below is copied from AbstractModule /** * Returns the current binder. */ protected final PrivateBinder binder() { return binder; } /** * @see Binder#bind(Key) */ protected final <T> LinkedBindingBuilder<T> bind(Key<T> key) { return binder.bind(key); } /** * @see Binder#bind(TypeLiteral) */ protected final <T> AnnotatedBindingBuilder<T> bind(TypeLiteral<T> typeLiteral) { return binder.bind(typeLiteral); } /** * @see Binder#bind(Class) */ protected final <T> AnnotatedBindingBuilder<T> bind(Class<T> clazz) { return binder.bind(clazz); } /** * @see Binder#install(Module) */ protected final void install(Module module) { binder.install(module); } /** * @see Binder#addError(String, Object[])<SUF>*/ protected final void addError(String message, Object... arguments) { binder.addError(message, arguments); } /** * @see Binder#addError(Throwable) */ protected final void addError(Throwable t) { binder.addError(t); } /** * @see Binder#addError(Message) */ protected final void addError(Message message) { binder.addError(message); } /** * @see Binder#getProvider(Key) */ protected final <T> Provider<T> getProvider(Key<T> key) { return binder.getProvider(key); } /** * @see Binder#getProvider(Class) */ protected final <T> Provider<T> getProvider(Class<T> type) { return binder.getProvider(type); } /** * @see Binder#getMembersInjector(Class) */ protected <T> MembersInjector<T> getMembersInjector(Class<T> type) { return binder.getMembersInjector(type); } /** * @see Binder#getMembersInjector(TypeLiteral) */ protected <T> MembersInjector<T> getMembersInjector(TypeLiteral<T> type) { return binder.getMembersInjector(type); } }
167714_2
package org.opensourcebim.services; import static org.junit.Assert.fail; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.UUID; import org.bimserver.bimbots.BimBotsServiceInterface; import org.bimserver.client.json.JsonBimServerClientFactory; import org.bimserver.shared.UsernamePasswordAuthenticationInfo; import org.bimserver.shared.exceptions.BimServerClientException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.opensourcebim.ifccollection.MaterialSource; import org.opensourcebim.ifccollection.MpgElement; import org.opensourcebim.ifccollection.MpgObjectStoreImpl; import org.opensourcebim.ifccollection.ObjectStoreBuilder; import org.opensourcebim.nmd.NmdProductCardReference; @RunWith(Parameterized.class) public class BaseServiceIntegrationTest<T extends BimBotsServiceInterface> { String rootDir = Paths.get(System.getProperty("user.dir")).getParent() + File.separator + "2018 BouwBesluit test files" + File.separator; JsonBimServerClientFactory factory = null; UsernamePasswordAuthenticationInfo authInfo = null; protected String fileName; protected String relPath; protected Object referenceData; protected BimBotsServiceInterface bimbot; @SuppressWarnings("unchecked") protected T getService() { return (T) this.bimbot; } public BaseServiceIntegrationTest(String relPath, String fileName, Object referenceData) { this.relPath = relPath; this.fileName = fileName; this.referenceData = referenceData; try { factory = new JsonBimServerClientFactory("http://localhost:8080"); } catch (BimServerClientException e) { fail("bimserver not running"); } authInfo = new UsernamePasswordAuthenticationInfo("[email protected]", "admin"); } @Parameterized.Parameters(name = "{0}/{1} with reference data {2}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][] { {"project a", "3d bwk_K01K05_04-12-2017.ifc", null}, {"Project B", "063_AP_DSB_BIM_CONSTR.ifc", null}, {"Project C (BasisILS)", "model voorbeeld BasisILS.ifc", getProjectCReferenceStore()}, {"Project D", "18014_BWK_totaal.ifc", null}, }); } protected Path getFullIfcModelPath() { return Paths.get(rootDir + this.relPath + File.separator + this.fileName); } @SuppressWarnings("serial") private static MpgObjectStoreImpl getProjectCReferenceStore() { ObjectStoreBuilder factory = new ObjectStoreBuilder(); MpgElement el; MaterialSource refSource = new MaterialSource(UUID.randomUUID().toString(), "dummy name", "reference source"); el = factory.AddUnmappedMpgElement("16_Fundering_funderingsbalk", false, new HashMap<String, Double>() { {put("Beton gewapend C", 1.0);} }, new Double[] {5.0, 0.4, 0.5}, "16.12", "IfcFooting", null); el.mapProductCard(refSource, new NmdProductCardReference(1000D)); //String doorUUID = UUID.randomUUID().toString(); factory.AddUnmappedMpgElement("32_Deur_S-01", false, new HashMap<String, Double>(), // { {put("32_Loofhout", 1.0);} } new Double[] {0.986, 0.114, 2.1}, "32.31", "IfcDoor", null); String floorUUID = UUID.randomUUID().toString(); factory.AddUnmappedMpgElement("Cement", false, new HashMap<String, Double>() { {put("Cement", 1.0);} }, new Double[] {4.88, 5.0, 0.05}, "23.21", "IfcBuildingElementPart", floorUUID); factory.AddUnmappedMpgElement("Beton gewapend prefab vloer", false, new HashMap<String, Double>() { {put("Beton gewapend prefab vloer", 1.0);} }, new Double[] {5.0, 5.0, 0.15}, "23.21", "IfcBuildingElementPart", floorUUID); factory.AddUnmappedMpgElement("Isolatie - Kunststof hard", false, new HashMap<String, Double>() { {put("Isolatie - Kunststof hard", 1.0);} }, new Double[] {5.0, 5.0, 0.10}, "23.21", "IfcBuildingElementPart", floorUUID); factory.AddUnmappedMpgElement("23_Vloer_begane grondvloer", false, new HashMap<String, Double>(), // { {put("Kanaalplaat+dv iso 300", 1.0);} } new Double[] {5.0, 5.0, 0.3}, "23.21", "IfcSlab", null); String wallUUID = UUID.randomUUID().toString(); factory.AddUnmappedMpgElement("Steen - Kalkzandsteen C", false, new HashMap<String, Double>() { {put("Steen - Kalkzandsteen C", 1.0);} }, new Double[] {5.0, 0.12, 2.98}, "21.22", "IfcBuildingElementPart", wallUUID); factory.AddUnmappedMpgElement("Steen - Baksteen AFW", false, new HashMap<String, Double>() { {put("Steen - Baksteen AFW", 1.0);} }, new Double[] {5.0, 0.1, 3.23}, "21.22", "IfcBuildingElementPart", wallUUID); factory.AddUnmappedMpgElement("Isolatie - Steenwol zacht", false, new HashMap<String, Double>() { {put("Isolatie - Steenwol zacht", 1.0);} }, new Double[] {5.0, 0.12, 3.23}, "21.22", "IfcBuildingElementPart", wallUUID); factory.AddUnmappedMpgElement("21_Wand_spouwmuur", false, new HashMap<String, Double>(), new Double[] {5.0, 0.12, 3.23}, "21.22", "IfcWall", null); factory.AddUnmappedMpgElement("22_Wand_binnenwand", false, new HashMap<String, Double>() {{put("Gipsblokken", 1.0);}}, new Double[] {4.88, 0.1, 2.78}, "22.11", "IfcWall", null); factory.AddUnmappedMpgElement("31_Raam_H-01", false, new HashMap<String, Double>(), // { {put("32_Loofhout", 1.0);} } new Double[] {0.9, 0.45, 1.638}, "31.22", "IfcWindow", null); factory.addSpace(25d, 2.5); return factory.getStore(); } }
opensourceBIM/NL-MPG-calc
test/org/opensourcebim/services/BaseServiceIntegrationTest.java
2,066
// { {put("Kanaalplaat+dv iso 300", 1.0);} }
line_comment
nl
package org.opensourcebim.services; import static org.junit.Assert.fail; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.UUID; import org.bimserver.bimbots.BimBotsServiceInterface; import org.bimserver.client.json.JsonBimServerClientFactory; import org.bimserver.shared.UsernamePasswordAuthenticationInfo; import org.bimserver.shared.exceptions.BimServerClientException; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.opensourcebim.ifccollection.MaterialSource; import org.opensourcebim.ifccollection.MpgElement; import org.opensourcebim.ifccollection.MpgObjectStoreImpl; import org.opensourcebim.ifccollection.ObjectStoreBuilder; import org.opensourcebim.nmd.NmdProductCardReference; @RunWith(Parameterized.class) public class BaseServiceIntegrationTest<T extends BimBotsServiceInterface> { String rootDir = Paths.get(System.getProperty("user.dir")).getParent() + File.separator + "2018 BouwBesluit test files" + File.separator; JsonBimServerClientFactory factory = null; UsernamePasswordAuthenticationInfo authInfo = null; protected String fileName; protected String relPath; protected Object referenceData; protected BimBotsServiceInterface bimbot; @SuppressWarnings("unchecked") protected T getService() { return (T) this.bimbot; } public BaseServiceIntegrationTest(String relPath, String fileName, Object referenceData) { this.relPath = relPath; this.fileName = fileName; this.referenceData = referenceData; try { factory = new JsonBimServerClientFactory("http://localhost:8080"); } catch (BimServerClientException e) { fail("bimserver not running"); } authInfo = new UsernamePasswordAuthenticationInfo("[email protected]", "admin"); } @Parameterized.Parameters(name = "{0}/{1} with reference data {2}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][] { {"project a", "3d bwk_K01K05_04-12-2017.ifc", null}, {"Project B", "063_AP_DSB_BIM_CONSTR.ifc", null}, {"Project C (BasisILS)", "model voorbeeld BasisILS.ifc", getProjectCReferenceStore()}, {"Project D", "18014_BWK_totaal.ifc", null}, }); } protected Path getFullIfcModelPath() { return Paths.get(rootDir + this.relPath + File.separator + this.fileName); } @SuppressWarnings("serial") private static MpgObjectStoreImpl getProjectCReferenceStore() { ObjectStoreBuilder factory = new ObjectStoreBuilder(); MpgElement el; MaterialSource refSource = new MaterialSource(UUID.randomUUID().toString(), "dummy name", "reference source"); el = factory.AddUnmappedMpgElement("16_Fundering_funderingsbalk", false, new HashMap<String, Double>() { {put("Beton gewapend C", 1.0);} }, new Double[] {5.0, 0.4, 0.5}, "16.12", "IfcFooting", null); el.mapProductCard(refSource, new NmdProductCardReference(1000D)); //String doorUUID = UUID.randomUUID().toString(); factory.AddUnmappedMpgElement("32_Deur_S-01", false, new HashMap<String, Double>(), // { {put("32_Loofhout", 1.0);} } new Double[] {0.986, 0.114, 2.1}, "32.31", "IfcDoor", null); String floorUUID = UUID.randomUUID().toString(); factory.AddUnmappedMpgElement("Cement", false, new HashMap<String, Double>() { {put("Cement", 1.0);} }, new Double[] {4.88, 5.0, 0.05}, "23.21", "IfcBuildingElementPart", floorUUID); factory.AddUnmappedMpgElement("Beton gewapend prefab vloer", false, new HashMap<String, Double>() { {put("Beton gewapend prefab vloer", 1.0);} }, new Double[] {5.0, 5.0, 0.15}, "23.21", "IfcBuildingElementPart", floorUUID); factory.AddUnmappedMpgElement("Isolatie - Kunststof hard", false, new HashMap<String, Double>() { {put("Isolatie - Kunststof hard", 1.0);} }, new Double[] {5.0, 5.0, 0.10}, "23.21", "IfcBuildingElementPart", floorUUID); factory.AddUnmappedMpgElement("23_Vloer_begane grondvloer", false, new HashMap<String, Double>(), // { {put("Kanaalplaat+dv<SUF> new Double[] {5.0, 5.0, 0.3}, "23.21", "IfcSlab", null); String wallUUID = UUID.randomUUID().toString(); factory.AddUnmappedMpgElement("Steen - Kalkzandsteen C", false, new HashMap<String, Double>() { {put("Steen - Kalkzandsteen C", 1.0);} }, new Double[] {5.0, 0.12, 2.98}, "21.22", "IfcBuildingElementPart", wallUUID); factory.AddUnmappedMpgElement("Steen - Baksteen AFW", false, new HashMap<String, Double>() { {put("Steen - Baksteen AFW", 1.0);} }, new Double[] {5.0, 0.1, 3.23}, "21.22", "IfcBuildingElementPart", wallUUID); factory.AddUnmappedMpgElement("Isolatie - Steenwol zacht", false, new HashMap<String, Double>() { {put("Isolatie - Steenwol zacht", 1.0);} }, new Double[] {5.0, 0.12, 3.23}, "21.22", "IfcBuildingElementPart", wallUUID); factory.AddUnmappedMpgElement("21_Wand_spouwmuur", false, new HashMap<String, Double>(), new Double[] {5.0, 0.12, 3.23}, "21.22", "IfcWall", null); factory.AddUnmappedMpgElement("22_Wand_binnenwand", false, new HashMap<String, Double>() {{put("Gipsblokken", 1.0);}}, new Double[] {4.88, 0.1, 2.78}, "22.11", "IfcWall", null); factory.AddUnmappedMpgElement("31_Raam_H-01", false, new HashMap<String, Double>(), // { {put("32_Loofhout", 1.0);} } new Double[] {0.9, 0.45, 1.638}, "31.22", "IfcWindow", null); factory.addSpace(25d, 2.5); return factory.getStore(); } }
49189_13
package org.opentripplanner.model.plan; import java.time.Duration; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import org.locationtech.jts.geom.LineString; import org.opentripplanner.framework.i18n.I18NString; import org.opentripplanner.framework.lang.Sandbox; import org.opentripplanner.model.BookingInfo; import org.opentripplanner.model.PickDrop; import org.opentripplanner.model.fare.FareProductUse; import org.opentripplanner.model.plan.legreference.LegReference; import org.opentripplanner.model.transfer.ConstrainedTransfer; import org.opentripplanner.routing.alertpatch.TransitAlert; import org.opentripplanner.street.model.note.StreetNote; import org.opentripplanner.transit.model.basic.Accessibility; import org.opentripplanner.transit.model.network.Route; import org.opentripplanner.transit.model.organization.Agency; import org.opentripplanner.transit.model.organization.Operator; import org.opentripplanner.transit.model.site.FareZone; import org.opentripplanner.transit.model.timetable.Trip; import org.opentripplanner.transit.model.timetable.TripOnServiceDate; /** * One leg of a trip -- that is, a temporally continuous piece of the journey that takes place on a * particular vehicle or on the street using mainly a single mode */ public interface Leg { /** * Whether this leg is a transit leg or not. * * @return Boolean true if the leg is a transit leg */ boolean isTransitLeg(); default boolean isScheduledTransitLeg() { return false; } default ScheduledTransitLeg asScheduledTransitLeg() { throw new ClassCastException(); } /** * For transit legs, if the rider should stay on the vehicle as it changes route names. This is * the same as a stay-seated transfer. */ default Boolean isInterlinedWithPreviousLeg() { return false; } /** The mode is walking. */ default boolean isWalkingLeg() { return false; } /** * The mode is a street mode; Hence not a transit mode. */ default boolean isStreetLeg() { return false; } /** * The leg's duration in seconds */ default Duration getDuration() { return Duration.between(getStartTime(), getEndTime()); } /** * Return {@code true} if to legs ride the same trip(same tripId) and at least part of the rides * overlap. Two legs overlap is they have at least one segment(from one stop to the next) in * common. */ default boolean isPartiallySameTransitLeg(Leg other) { // Assert both legs are transit legs if (!isTransitLeg() || !other.isTransitLeg()) { throw new IllegalStateException(); } // Must be on the same service date if (!getServiceDate().equals(other.getServiceDate())) { return false; } // If NOT the same trip, return false if (!getTrip().getId().equals(other.getTrip().getId())) { return false; } // Return true if legs overlap return ( getBoardStopPosInPattern() < other.getAlightStopPosInPattern() && getAlightStopPosInPattern() > other.getBoardStopPosInPattern() ); } /** * Check is this instance has the same type and mode as the given other. */ boolean hasSameMode(Leg other); /** * Return {@code true} if to legs are the same. The mode must match and the time must overlap. * For transit the trip ID must match and board/alight position must overlap. (Two trips with * different service-date can overlap in time, so we use boarding-/alight-position to verify). */ default boolean isPartiallySameLeg(Leg other) { if (!hasSameMode(other)) { return false; } // Overlap in time if (!overlapInTime(other)) { return false; } // The mode is the same, so this and the other are both *street* or *transit* legs if (isStreetLeg()) { return true; } // Transit leg else { // If NOT the same trip, return false if (!getTrip().getId().equals(other.getTrip().getId())) { return false; } // Return true if legs overlap in space(have one common stop visit), this is necessary // since the same trip id on two following service dates may overlap in time. For example, // a trip may run in a loop for 48 hours, overlapping with the same trip id of the trip // scheduled for the next service day. They both visit the same stops, with overlapping // times, but the stop positions will be different. return ( getBoardStopPosInPattern() < other.getAlightStopPosInPattern() && getAlightStopPosInPattern() > other.getBoardStopPosInPattern() ); } } /** * Return true if this leg and the given {@code other} leg overlap in time. If the * start-time equals the end-time this method returns false. */ default boolean overlapInTime(Leg other) { return ( // We convert to epoch seconds to ignore nanos (save CPU), // in favor of using the methods isAfter(...) and isBefore(...) getStartTime().toEpochSecond() < other.getEndTime().toEpochSecond() && other.getStartTime().toEpochSecond() < getEndTime().toEpochSecond() ); } /** * For transit legs, the route agency. For non-transit legs {@code null}. */ default Agency getAgency() { return null; } /** * For transit legs, the trip operator, fallback to route operator. For non-transit legs {@code * null}. * * @see Trip#getOperator() */ default Operator getOperator() { return null; } /** * For transit legs, the route. For non-transit legs, null. */ default Route getRoute() { return null; } /** * For transit legs, the trip. For non-transit legs, null. */ default Trip getTrip() { return null; } /** * For transit legs, the trip on service date, if it exists. For non-transit legs, null. */ @Nullable default TripOnServiceDate getTripOnServiceDate() { return null; } default Accessibility getTripWheelchairAccessibility() { return null; } /** * The date and time this leg begins. */ ZonedDateTime getStartTime(); /** * The date and time this leg ends. */ ZonedDateTime getEndTime(); /** * For transit leg, the offset from the scheduled departure-time of the boarding stop in this leg. * "scheduled time of departure at boarding stop" = startTime - departureDelay Unit: seconds. */ default int getDepartureDelay() { return 0; } /** * For transit leg, the offset from the scheduled arrival-time of the alighting stop in this leg. * "scheduled time of arrival at alighting stop" = endTime - arrivalDelay Unit: seconds. */ default int getArrivalDelay() { return 0; } /** * Whether there is real-time data about this Leg */ default boolean getRealTime() { return false; } /** * Whether this Leg describes a flexible trip. The reason we need this is that FlexTrip does not * inherit from Trip, so that the information that the Trip is flexible would be lost when * creating this object. */ default boolean isFlexibleTrip() { return false; } /** * Is this a frequency-based trip with non-strict departure times? */ default Boolean getNonExactFrequency() { return null; } /** * The best estimate of the time between two arriving vehicles. This is particularly important for * non-strict frequency trips, but could become important for real-time trips, strict frequency * trips, and scheduled trips with empirical headways. */ default Integer getHeadway() { return null; } /** * The distance traveled while traversing the leg in meters. */ double getDistanceMeters(); /** * Get the timezone offset in milliseconds. */ default int getAgencyTimeZoneOffset() { int MILLIS_TO_SECONDS = 1000; return getStartTime().getOffset().getTotalSeconds() * MILLIS_TO_SECONDS; } /** * For transit legs, the type of the route. Non transit -1 When 0-7: 0 Tram, 1 Subway, 2 Train, 3 * Bus, 4 Ferry, 5 Cable Car, 6 Gondola, 7 Funicular When equal or highter than 100, it is coded * using the Hierarchical Vehicle Type (HVT) codes from the European TPEG standard Also see * http://groups.google.com/group/gtfs-changes/msg/ed917a69cf8c5bef */ default Integer getRouteType() { return null; } /** * For transit legs, the headsign of the bus or train being used. For non-transit legs, null. */ default I18NString getHeadsign() { return null; } /** * For transit legs, the service date of the trip. For non-transit legs, null. * <p> * The trip service date should be used to identify the correct trip schedule and can not be * trusted to display the date for any departures or arrivals. For example, the first departure * for a given trip may happen at service date March 25th and service time 25:00, which in local * time would be Mach 26th 01:00. */ default LocalDate getServiceDate() { return null; } /** * For transit leg, the route's branding URL (if one exists). For non-transit legs, null. */ default String getRouteBrandingUrl() { return null; } /** * The Place where the leg originates. */ Place getFrom(); /** * The Place where the leg begins. */ Place getTo(); /** * For transit legs, intermediate stops between the Place where the leg originates and the Place * where the leg ends. For non-transit legs, {@code null}. */ default List<StopArrival> getIntermediateStops() { return null; } /** * The leg's geometry. */ LineString getLegGeometry(); /** * The leg's elevation profile. * * The elevation profile as a comma-separated list of x,y values. x is the distance from the start * of the leg, y is the elevation at this distance. */ default ElevationProfile getElevationProfile() { return null; } /** * A series of turn by turn instructions used for walking, biking and driving. */ default List<WalkStep> getWalkSteps() { return List.of(); } default Set<StreetNote> getStreetNotes() { return null; } default Set<TransitAlert> getTransitAlerts() { return Set.of(); } default PickDrop getBoardRule() { return null; } default PickDrop getAlightRule() { return null; } default BookingInfo getDropOffBookingInfo() { return null; } default BookingInfo getPickupBookingInfo() { return null; } default ConstrainedTransfer getTransferFromPrevLeg() { return null; } default ConstrainedTransfer getTransferToNextLeg() { return null; } default Integer getBoardStopPosInPattern() { return null; } default Integer getAlightStopPosInPattern() { return null; } default Integer getBoardingGtfsStopSequence() { return null; } default Integer getAlightGtfsStopSequence() { return null; } /** * Is this leg walking with a bike? */ default Boolean getWalkingBike() { return null; } /** * A sandbox feature for calculating a numeric score between 0 and 1 which indicates * how accessible the itinerary is as a whole. This is not a very scientific method but just * a rough guidance that expresses certainty or uncertainty about the accessibility. * * The intended audience for this score are frontend developers wanting to show a simple UI * rather than having to iterate over all the stops and trips. * * Note: the information to calculate this score are all available to the frontend, however * calculating them on the backend makes life a little easier and changes are automatically * applied to all frontends. */ @Nullable default Float accessibilityScore() { return null; } default Boolean getRentedVehicle() { return null; } default String getVehicleRentalNetwork() { return null; } /** * If a generalized cost is used in the routing algorithm, this should be the "delta" cost * computed by the algorithm for the section this leg account for. This is relevant for anyone who * want to debug a search and tuning the system. The unit should be equivalent to the cost of "one * second of transit". * <p> * -1 indicate that the cost is not set/computed. */ int getGeneralizedCost(); default LegReference getLegReference() { return null; } default void addAlert(TransitAlert alert) { throw new UnsupportedOperationException(); } default Leg withTimeShift(Duration duration) { throw new UnsupportedOperationException(); } default Set<FareZone> getFareZones() { var intermediate = getIntermediateStops() .stream() .flatMap(stopArrival -> stopArrival.place.stop.getFareZones().stream()); var start = getFareZones(this.getFrom()); var end = getFareZones(this.getTo()); return Stream.of(intermediate, start, end).flatMap(s -> s).collect(Collectors.toSet()); } /** * Set {@link FareProductUse} for this leg. Their use-id can identify them across several * legs. */ @Sandbox void setFareProducts(List<FareProductUse> products); /** * Get the {@link FareProductUse} for this leg. */ @Sandbox List<FareProductUse> fareProducts(); private static Stream<FareZone> getFareZones(Place place) { if (place.stop == null) { return Stream.empty(); } else { return place.stop.getFareZones().stream(); } } }
opentripplanner/OpenTripPlanner
src/main/java/org/opentripplanner/model/plan/Leg.java
4,071
// Overlap in time
line_comment
nl
package org.opentripplanner.model.plan; import java.time.Duration; import java.time.LocalDate; import java.time.ZonedDateTime; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import org.locationtech.jts.geom.LineString; import org.opentripplanner.framework.i18n.I18NString; import org.opentripplanner.framework.lang.Sandbox; import org.opentripplanner.model.BookingInfo; import org.opentripplanner.model.PickDrop; import org.opentripplanner.model.fare.FareProductUse; import org.opentripplanner.model.plan.legreference.LegReference; import org.opentripplanner.model.transfer.ConstrainedTransfer; import org.opentripplanner.routing.alertpatch.TransitAlert; import org.opentripplanner.street.model.note.StreetNote; import org.opentripplanner.transit.model.basic.Accessibility; import org.opentripplanner.transit.model.network.Route; import org.opentripplanner.transit.model.organization.Agency; import org.opentripplanner.transit.model.organization.Operator; import org.opentripplanner.transit.model.site.FareZone; import org.opentripplanner.transit.model.timetable.Trip; import org.opentripplanner.transit.model.timetable.TripOnServiceDate; /** * One leg of a trip -- that is, a temporally continuous piece of the journey that takes place on a * particular vehicle or on the street using mainly a single mode */ public interface Leg { /** * Whether this leg is a transit leg or not. * * @return Boolean true if the leg is a transit leg */ boolean isTransitLeg(); default boolean isScheduledTransitLeg() { return false; } default ScheduledTransitLeg asScheduledTransitLeg() { throw new ClassCastException(); } /** * For transit legs, if the rider should stay on the vehicle as it changes route names. This is * the same as a stay-seated transfer. */ default Boolean isInterlinedWithPreviousLeg() { return false; } /** The mode is walking. */ default boolean isWalkingLeg() { return false; } /** * The mode is a street mode; Hence not a transit mode. */ default boolean isStreetLeg() { return false; } /** * The leg's duration in seconds */ default Duration getDuration() { return Duration.between(getStartTime(), getEndTime()); } /** * Return {@code true} if to legs ride the same trip(same tripId) and at least part of the rides * overlap. Two legs overlap is they have at least one segment(from one stop to the next) in * common. */ default boolean isPartiallySameTransitLeg(Leg other) { // Assert both legs are transit legs if (!isTransitLeg() || !other.isTransitLeg()) { throw new IllegalStateException(); } // Must be on the same service date if (!getServiceDate().equals(other.getServiceDate())) { return false; } // If NOT the same trip, return false if (!getTrip().getId().equals(other.getTrip().getId())) { return false; } // Return true if legs overlap return ( getBoardStopPosInPattern() < other.getAlightStopPosInPattern() && getAlightStopPosInPattern() > other.getBoardStopPosInPattern() ); } /** * Check is this instance has the same type and mode as the given other. */ boolean hasSameMode(Leg other); /** * Return {@code true} if to legs are the same. The mode must match and the time must overlap. * For transit the trip ID must match and board/alight position must overlap. (Two trips with * different service-date can overlap in time, so we use boarding-/alight-position to verify). */ default boolean isPartiallySameLeg(Leg other) { if (!hasSameMode(other)) { return false; } // Overlap in<SUF> if (!overlapInTime(other)) { return false; } // The mode is the same, so this and the other are both *street* or *transit* legs if (isStreetLeg()) { return true; } // Transit leg else { // If NOT the same trip, return false if (!getTrip().getId().equals(other.getTrip().getId())) { return false; } // Return true if legs overlap in space(have one common stop visit), this is necessary // since the same trip id on two following service dates may overlap in time. For example, // a trip may run in a loop for 48 hours, overlapping with the same trip id of the trip // scheduled for the next service day. They both visit the same stops, with overlapping // times, but the stop positions will be different. return ( getBoardStopPosInPattern() < other.getAlightStopPosInPattern() && getAlightStopPosInPattern() > other.getBoardStopPosInPattern() ); } } /** * Return true if this leg and the given {@code other} leg overlap in time. If the * start-time equals the end-time this method returns false. */ default boolean overlapInTime(Leg other) { return ( // We convert to epoch seconds to ignore nanos (save CPU), // in favor of using the methods isAfter(...) and isBefore(...) getStartTime().toEpochSecond() < other.getEndTime().toEpochSecond() && other.getStartTime().toEpochSecond() < getEndTime().toEpochSecond() ); } /** * For transit legs, the route agency. For non-transit legs {@code null}. */ default Agency getAgency() { return null; } /** * For transit legs, the trip operator, fallback to route operator. For non-transit legs {@code * null}. * * @see Trip#getOperator() */ default Operator getOperator() { return null; } /** * For transit legs, the route. For non-transit legs, null. */ default Route getRoute() { return null; } /** * For transit legs, the trip. For non-transit legs, null. */ default Trip getTrip() { return null; } /** * For transit legs, the trip on service date, if it exists. For non-transit legs, null. */ @Nullable default TripOnServiceDate getTripOnServiceDate() { return null; } default Accessibility getTripWheelchairAccessibility() { return null; } /** * The date and time this leg begins. */ ZonedDateTime getStartTime(); /** * The date and time this leg ends. */ ZonedDateTime getEndTime(); /** * For transit leg, the offset from the scheduled departure-time of the boarding stop in this leg. * "scheduled time of departure at boarding stop" = startTime - departureDelay Unit: seconds. */ default int getDepartureDelay() { return 0; } /** * For transit leg, the offset from the scheduled arrival-time of the alighting stop in this leg. * "scheduled time of arrival at alighting stop" = endTime - arrivalDelay Unit: seconds. */ default int getArrivalDelay() { return 0; } /** * Whether there is real-time data about this Leg */ default boolean getRealTime() { return false; } /** * Whether this Leg describes a flexible trip. The reason we need this is that FlexTrip does not * inherit from Trip, so that the information that the Trip is flexible would be lost when * creating this object. */ default boolean isFlexibleTrip() { return false; } /** * Is this a frequency-based trip with non-strict departure times? */ default Boolean getNonExactFrequency() { return null; } /** * The best estimate of the time between two arriving vehicles. This is particularly important for * non-strict frequency trips, but could become important for real-time trips, strict frequency * trips, and scheduled trips with empirical headways. */ default Integer getHeadway() { return null; } /** * The distance traveled while traversing the leg in meters. */ double getDistanceMeters(); /** * Get the timezone offset in milliseconds. */ default int getAgencyTimeZoneOffset() { int MILLIS_TO_SECONDS = 1000; return getStartTime().getOffset().getTotalSeconds() * MILLIS_TO_SECONDS; } /** * For transit legs, the type of the route. Non transit -1 When 0-7: 0 Tram, 1 Subway, 2 Train, 3 * Bus, 4 Ferry, 5 Cable Car, 6 Gondola, 7 Funicular When equal or highter than 100, it is coded * using the Hierarchical Vehicle Type (HVT) codes from the European TPEG standard Also see * http://groups.google.com/group/gtfs-changes/msg/ed917a69cf8c5bef */ default Integer getRouteType() { return null; } /** * For transit legs, the headsign of the bus or train being used. For non-transit legs, null. */ default I18NString getHeadsign() { return null; } /** * For transit legs, the service date of the trip. For non-transit legs, null. * <p> * The trip service date should be used to identify the correct trip schedule and can not be * trusted to display the date for any departures or arrivals. For example, the first departure * for a given trip may happen at service date March 25th and service time 25:00, which in local * time would be Mach 26th 01:00. */ default LocalDate getServiceDate() { return null; } /** * For transit leg, the route's branding URL (if one exists). For non-transit legs, null. */ default String getRouteBrandingUrl() { return null; } /** * The Place where the leg originates. */ Place getFrom(); /** * The Place where the leg begins. */ Place getTo(); /** * For transit legs, intermediate stops between the Place where the leg originates and the Place * where the leg ends. For non-transit legs, {@code null}. */ default List<StopArrival> getIntermediateStops() { return null; } /** * The leg's geometry. */ LineString getLegGeometry(); /** * The leg's elevation profile. * * The elevation profile as a comma-separated list of x,y values. x is the distance from the start * of the leg, y is the elevation at this distance. */ default ElevationProfile getElevationProfile() { return null; } /** * A series of turn by turn instructions used for walking, biking and driving. */ default List<WalkStep> getWalkSteps() { return List.of(); } default Set<StreetNote> getStreetNotes() { return null; } default Set<TransitAlert> getTransitAlerts() { return Set.of(); } default PickDrop getBoardRule() { return null; } default PickDrop getAlightRule() { return null; } default BookingInfo getDropOffBookingInfo() { return null; } default BookingInfo getPickupBookingInfo() { return null; } default ConstrainedTransfer getTransferFromPrevLeg() { return null; } default ConstrainedTransfer getTransferToNextLeg() { return null; } default Integer getBoardStopPosInPattern() { return null; } default Integer getAlightStopPosInPattern() { return null; } default Integer getBoardingGtfsStopSequence() { return null; } default Integer getAlightGtfsStopSequence() { return null; } /** * Is this leg walking with a bike? */ default Boolean getWalkingBike() { return null; } /** * A sandbox feature for calculating a numeric score between 0 and 1 which indicates * how accessible the itinerary is as a whole. This is not a very scientific method but just * a rough guidance that expresses certainty or uncertainty about the accessibility. * * The intended audience for this score are frontend developers wanting to show a simple UI * rather than having to iterate over all the stops and trips. * * Note: the information to calculate this score are all available to the frontend, however * calculating them on the backend makes life a little easier and changes are automatically * applied to all frontends. */ @Nullable default Float accessibilityScore() { return null; } default Boolean getRentedVehicle() { return null; } default String getVehicleRentalNetwork() { return null; } /** * If a generalized cost is used in the routing algorithm, this should be the "delta" cost * computed by the algorithm for the section this leg account for. This is relevant for anyone who * want to debug a search and tuning the system. The unit should be equivalent to the cost of "one * second of transit". * <p> * -1 indicate that the cost is not set/computed. */ int getGeneralizedCost(); default LegReference getLegReference() { return null; } default void addAlert(TransitAlert alert) { throw new UnsupportedOperationException(); } default Leg withTimeShift(Duration duration) { throw new UnsupportedOperationException(); } default Set<FareZone> getFareZones() { var intermediate = getIntermediateStops() .stream() .flatMap(stopArrival -> stopArrival.place.stop.getFareZones().stream()); var start = getFareZones(this.getFrom()); var end = getFareZones(this.getTo()); return Stream.of(intermediate, start, end).flatMap(s -> s).collect(Collectors.toSet()); } /** * Set {@link FareProductUse} for this leg. Their use-id can identify them across several * legs. */ @Sandbox void setFareProducts(List<FareProductUse> products); /** * Get the {@link FareProductUse} for this leg. */ @Sandbox List<FareProductUse> fareProducts(); private static Stream<FareZone> getFareZones(Place place) { if (place.stop == null) { return Stream.empty(); } else { return place.stop.getFareZones().stream(); } } }
88444_37
/* * Copyright The OpenZipkin Authors * SPDX-License-Identifier: Apache-2.0 */ package brave.propagation; import brave.Span; import brave.baggage.BaggageFields; import brave.baggage.BaggagePropagation; import brave.internal.InternalPropagation; import brave.internal.Nullable; import brave.internal.Platform; import brave.internal.baggage.ExtraBaggageContext; import java.lang.ref.WeakReference; import java.util.Collections; import java.util.List; import static brave.internal.InternalPropagation.FLAG_LOCAL_ROOT; import static brave.internal.InternalPropagation.FLAG_SAMPLED; import static brave.internal.InternalPropagation.FLAG_SAMPLED_LOCAL; import static brave.internal.InternalPropagation.FLAG_SAMPLED_SET; import static brave.internal.InternalPropagation.FLAG_SHARED; import static brave.internal.codec.HexCodec.lenientLowerHexToUnsignedLong; import static brave.internal.codec.HexCodec.toLowerHex; import static brave.internal.codec.HexCodec.writeHexLong; import static brave.internal.collect.Lists.ensureImmutable; import static brave.internal.collect.Lists.ensureMutable; import static brave.propagation.TraceIdContext.toTraceIdString; /** * Contains trace identifiers and sampling data propagated in and out-of-process. * * <p>Particularly, this includes trace identifiers and sampled state. * * <p>The implementation was originally {@code com.github.kristofa.brave.SpanId}, which was a * port of {@code com.twitter.finagle.tracing.TraceId}. Unlike these mentioned, this type does not * expose a single binary representation. That's because propagation forms can now vary. * * @since 4.0 */ //@Immutable public final class TraceContext extends SamplingFlags { /** * Used to send the trace context downstream. For example, as http headers. * * <p>For example, to put the context on an {@link java.net.HttpURLConnection}, you can do this: * <pre>{@code * // in your constructor * injector = tracing.propagation().injector(URLConnection::setRequestProperty); * * // later in your code, reuse the function you created above to add trace headers * HttpURLConnection connection = (HttpURLConnection) new URL("http://myserver").openConnection(); * injector.inject(span.context(), connection); * }</pre> * * <p><em>Note</em>: This type is safe to implement as a lambda, or use as a method reference as * it is effectively a {@code FunctionalInterface}. It isn't annotated as such because the project * has a minimum Java language level 6. * * @since 4.0 */ // @FunctionalInterface, except Java language level 6. Do not add methods as it will break API! public interface Injector<R> { /** * Usually calls a setter for each propagation field to send downstream. * * @param traceContext possibly unsampled. * @param request holds propagation fields. For example, an outgoing message or http request. */ void inject(TraceContext traceContext, R request); } /** * Used to continue an incoming trace. For example, by reading http headers. * * <p><em>Note</em>: This type is safe to implement as a lambda, or use as a method reference as * it is effectively a {@code FunctionalInterface}. It isn't annotated as such because the project * has a minimum Java language level 6. * * @see brave.Tracer#nextSpan(TraceContextOrSamplingFlags) * @since 4.0 */ // @FunctionalInterface, except Java language level 6. Do not add methods as it will break API! public interface Extractor<R> { /** * Returns either a trace context or sampling flags parsed from the request. If nothing was * parsable, sampling flags will be set to {@link SamplingFlags#EMPTY}. * * @param request holds propagation fields. For example, an incoming message or http request. */ TraceContextOrSamplingFlags extract(R request); } public static Builder newBuilder() { return new Builder(); } /** When non-zero, the trace containing this span uses 128-bit trace identifiers. */ public long traceIdHigh() { return traceIdHigh; } /** Unique 8-byte identifier for a trace, set on all spans within it. */ public long traceId() { return traceId; } /** * Returns the first {@link #spanId()} in a partition of a trace: otherwise known as an entry * span. This could be a root span or a span representing incoming work (ex {@link * Span.Kind#SERVER} or {@link Span.Kind#CONSUMER}. Unlike {@link #parentIdAsLong()}, this value * is inherited to child contexts until the trace exits the process. This value is inherited for * all child spans until the trace exits the process. This could also be described as an entry * span. * * <p>When {@link #isLocalRoot()}, this ID will be the same as the {@link #spanId() span ID}. * * <p>The local root ID can be used for dependency link processing, skipping data or partitioning * purposes. For example, one processor could skip all intermediate (local) spans between an * incoming service call and any outgoing ones. * * <p>This does not group together multiple points of entry in the same trace. For example, * repetitive consumption of the same incoming message results in different local roots. * * @return the {@link #spanId() span ID} of the local root or zero if this context wasn't * initialized by a {@link brave.Tracer}. */ // This is the first span ID that became a Span or ScopedSpan public long localRootId() { return localRootId; } public boolean isLocalRoot() { return (flags & FLAG_LOCAL_ROOT) == FLAG_LOCAL_ROOT; } /** * The parent's {@link #spanId} or null if this the root span in a trace. * * @see #parentIdAsLong() */ @Nullable public final Long parentId() { return parentId != 0 ? parentId : null; } /** * Like {@link #parentId()} except returns a primitive where zero implies absent. * * <p>Using this method will avoid allocation, so is encouraged when copying data. */ public long parentIdAsLong() { return parentId; } /** * Unique 8-byte identifier of this span within a trace. * * <p>A span is uniquely identified in storage by ({@linkplain #traceId}, {@linkplain #spanId}). */ public long spanId() { return spanId; } /** * True if we are recording a server span with the same span ID parsed from incoming headers. * * <h3>Impact on indexing</h3> * <p>When an RPC trace is client-originated, it will be sampled and the same span ID is used for * the server side. The shared flag helps prioritize timestamp and duration indexing in favor of * the client. In v1 format, there is no shared flag, so it implies converters should not store * timestamp and duration on the server span explicitly. */ public boolean shared() { return (flags & FLAG_SHARED) == FLAG_SHARED; } /** * Used internally by propagation plugins to search for their instance of state regardless of if * it is in a {@linkplain TraceContext} or {@linkplain TraceContextOrSamplingFlags}. * * <p>Tools that work only on {@linkplain TraceContext} should use {@link #findExtra(Class)} * instead. * * @see #findExtra(Class) * @see TraceContextOrSamplingFlags#extra() * @see Builder#addExtra(Object) for notes on extra values. * @since 4.9 */ public List<Object> extra() { return extraList; } /** * Used internally by propagation plugins to search for their instance of state. * * @see #extra() * @see Builder#addExtra(Object) for notes on extra values. */ @Nullable public <T> T findExtra(Class<T> type) { return findExtra(type, extraList); } public Builder toBuilder() { return new Builder(this); } volatile String traceIdString; // Lazily initialized and cached. /** Returns the hex representation of the span's trace ID */ public String traceIdString() { String r = traceIdString; if (r == null) { r = toTraceIdString(traceIdHigh, traceId); traceIdString = r; } return r; } volatile String parentIdString; // Lazily initialized and cached. /** Returns the hex representation of the span's parent ID */ @Nullable public String parentIdString() { String r = parentIdString; if (r == null && parentId != 0L) { r = parentIdString = toLowerHex(parentId); } return r; } volatile String localRootIdString; // Lazily initialized and cached. /** Returns the hex representation of the span's local root ID */ @Nullable public String localRootIdString() { String r = localRootIdString; if (r == null && localRootId != 0L) { r = localRootIdString = toLowerHex(localRootId); } return r; } volatile String spanIdString; // Lazily initialized and cached. /** Returns the hex representation of the span's ID */ public String spanIdString() { String r = spanIdString; if (r == null) { r = spanIdString = toLowerHex(spanId); } return r; } /** Returns {@code $traceId/$spanId} */ @Override public String toString() { boolean traceHi = traceIdHigh != 0; char[] result = new char[((traceHi ? 3 : 2) * 16) + 1]; // 2 ids and the delimiter int pos = 0; if (traceHi) { writeHexLong(result, pos, traceIdHigh); pos += 16; } writeHexLong(result, pos, traceId); pos += 16; result[pos++] = '/'; writeHexLong(result, pos, spanId); return new String(result); } public static final class Builder { long traceIdHigh, traceId, parentId, spanId; long localRootId; // intentionally only mutable by the copy constructor to control usage. int flags; List<Object> extraList = Collections.emptyList(); Builder(TraceContext context) { // no external implementations traceIdHigh = context.traceIdHigh; traceId = context.traceId; localRootId = context.localRootId; parentId = context.parentId; spanId = context.spanId; flags = context.flags; extraList = context.extraList; } /** @see TraceContext#traceIdHigh() */ public Builder traceIdHigh(long traceIdHigh) { this.traceIdHigh = traceIdHigh; return this; } /** @see TraceContext#traceId() */ public Builder traceId(long traceId) { this.traceId = traceId; return this; } /** @see TraceContext#parentIdAsLong() */ public Builder parentId(long parentId) { this.parentId = parentId; return this; } /** @see TraceContext#parentId() */ public Builder parentId(@Nullable Long parentId) { if (parentId == null) parentId = 0L; this.parentId = parentId; return this; } /** @see TraceContext#spanId() */ public Builder spanId(long spanId) { this.spanId = spanId; return this; } /** @see TraceContext#sampledLocal() */ public Builder sampledLocal(boolean sampledLocal) { if (sampledLocal) { flags |= FLAG_SAMPLED_LOCAL; } else { flags &= ~FLAG_SAMPLED_LOCAL; } return this; } /** @see TraceContext#sampled() */ public Builder sampled(boolean sampled) { flags = InternalPropagation.sampled(sampled, flags); return this; } /** @see TraceContext#sampled() */ public Builder sampled(@Nullable Boolean sampled) { if (sampled == null) { flags &= ~(FLAG_SAMPLED_SET | FLAG_SAMPLED); return this; } return sampled(sampled.booleanValue()); } /** @see TraceContext#debug() */ public Builder debug(boolean debug) { flags = SamplingFlags.debug(debug, flags); return this; } /** @see TraceContext#shared() */ public Builder shared(boolean shared) { if (shared) { flags |= FLAG_SHARED; } else { flags &= ~FLAG_SHARED; } return this; } /** * Allows you to control {@link #extra()} explicitly. * * @since 5.12 */ public Builder clearExtra() { extraList = Collections.emptyList(); return this; } /** * This is an advanced function used for {@link Propagation} plugins, such as * {@link BaggagePropagation}, to add an internal object to hold state when it isn't already in * {@linkplain #extra()}. * * <p>The "extra" parameter is intentionally opaque, and should be an internal type defined by * a {@linkplain Propagation} plugin. An example implementation could be storing a class * containing a correlation value, which is extracted from incoming requests and injected as-is * onto outgoing requests. A real world use is {@link BaggageFields}, which holds all baggage * fields to propagate in one instance. * * <p>Note: It is the responsibility of {@link Propagation.Factory#decorate(TraceContext)} * to consolidate elements (by searching for an existing instance of their state with {@link * #findExtra(Class)} or {@link #extra()}). If it doesn't, there could be multiple instances of * a given type and this can break logic and add overhead. Decoration is also when * implementations define their scope. For example, a plugin that only propagates a field * without changing will be constant for the whole request. A plugin that allows changes of * state need careful coding, such as done in {@link BaggagePropagation}. * * @see #extra() * @since 5.12 */ public Builder addExtra(Object extra) { extraList = ensureExtraAdded(extraList, extra); return this; } /** * Returns true when {@link TraceContext#traceId()} and potentially also {@link * TraceContext#traceIdHigh()} were parsed from the input. This assumes the input is valid, an * up to 32 character lower-hex string. * * <p>Returns boolean, not this, for conditional, exception free parsing: * * <p>Example use: * <pre>{@code * // Attempt to parse the trace ID or break out if unsuccessful for any reason * String traceIdString = getter.get(request, key); * if (!builder.parseTraceId(traceIdString, propagation.traceIdKey)) { * return TraceContextOrSamplingFlags.EMPTY; * } * }</pre> * * @param traceIdString the 1-32 character lowerhex string * @param key the name of the propagation field representing the trace ID; only using in * logging * @return false if the input is null or malformed */ // temporarily package protected until we figure out if this is reusable enough to expose boolean parseTraceId(String traceIdString, Object key) { if (isNull(key, traceIdString)) return false; int length = traceIdString.length(); if (invalidIdLength(key, length, 32)) return false; boolean traceIdHighAllZeros = false, traceIdAllZeros = false; // left-most characters, if any, are the high bits int traceIdIndex = Math.max(0, length - 16); if (traceIdIndex > 0) { traceIdHigh = lenientLowerHexToUnsignedLong(traceIdString, 0, traceIdIndex); if (traceIdHigh == 0L) { traceIdHighAllZeros = isAllZeros(traceIdString, 0, traceIdIndex); if (!traceIdHighAllZeros) { maybeLogNotLowerHex(traceIdString); return false; } } } else { traceIdHighAllZeros = true; } // right-most up to 16 characters are the low bits traceId = lenientLowerHexToUnsignedLong(traceIdString, traceIdIndex, length); if (traceId == 0L) { traceIdAllZeros = isAllZeros(traceIdString, traceIdIndex, length); if (!traceIdAllZeros) { maybeLogNotLowerHex(traceIdString); return false; } } if (traceIdHighAllZeros && traceIdAllZeros) { Platform.get().log("Invalid input: traceId was all zeros", null); } return traceIdHigh != 0L || traceId != 0L; } /** Parses the parent id from the input string. Returns true if the ID was missing or valid. */ <R, K> boolean parseParentId(Propagation.Getter<R, K> getter, R request, K key) { String parentIdString = getter.get(request, key); if (parentIdString == null) return true; // absent parent is ok int length = parentIdString.length(); if (invalidIdLength(key, length, 16)) return false; parentId = lenientLowerHexToUnsignedLong(parentIdString, 0, length); if (parentId != 0) return true; maybeLogNotLowerHex(parentIdString); return false; } /** Parses the span id from the input string. Returns true if the ID is valid. */ <R, K> boolean parseSpanId(Propagation.Getter<R, K> getter, R request, K key) { String spanIdString = getter.get(request, key); if (isNull(key, spanIdString)) return false; int length = spanIdString.length(); if (invalidIdLength(key, length, 16)) return false; spanId = lenientLowerHexToUnsignedLong(spanIdString, 0, length); if (spanId == 0) { if (isAllZeros(spanIdString, 0, length)) { Platform.get().log("Invalid input: spanId was all zeros", null); return false; } maybeLogNotLowerHex(spanIdString); return false; } return true; } static boolean invalidIdLength(Object key, int length, int max) { if (length > 1 && length <= max) return false; assert max == 32 || max == 16; Platform.get().log(max == 32 ? "{0} should be a 1 to 32 character lower-hex string with no prefix" : "{0} should be a 1 to 16 character lower-hex string with no prefix", key, null); return true; } static boolean isNull(Object key, String maybeNull) { if (maybeNull != null) return false; Platform.get().log("{0} was null", key, null); return true; } /** Helps differentiate a parse failure from a successful parse of all zeros. */ static boolean isAllZeros(String value, int beginIndex, int endIndex) { for (int i = beginIndex; i < endIndex; i++) { if (value.charAt(i) != '0') return false; } return true; } static void maybeLogNotLowerHex(String notLowerHex) { Platform.get().log("{0} is not a lower-hex string", notLowerHex, null); } /** @throws IllegalArgumentException if missing trace ID or span ID */ public TraceContext build() { String missing = ""; if (traceIdHigh == 0L && traceId == 0L) missing += " traceId"; if (spanId == 0L) missing += " spanId"; if (!"".equals(missing)) throw new IllegalArgumentException("Missing:" + missing); return new TraceContext( flags, traceIdHigh, traceId, localRootId, parentId, spanId, ensureImmutable(extraList) ); } Builder() { // no external implementations } } TraceContext shallowCopy() { return new TraceContext(flags, traceIdHigh, traceId, localRootId, parentId, spanId, extraList); } TraceContext withExtra(List<Object> extra) { return new TraceContext(flags, traceIdHigh, traceId, localRootId, parentId, spanId, extra); } TraceContext withFlags(int flags) { return new TraceContext(flags, traceIdHigh, traceId, localRootId, parentId, spanId, extraList); } final long traceIdHigh, traceId, localRootId, parentId, spanId; final List<Object> extraList; TraceContext( int flags, long traceIdHigh, long traceId, long localRootId, long parentId, long spanId, List<Object> extraList ) { super(flags); this.traceIdHigh = traceIdHigh; this.traceId = traceId; this.localRootId = localRootId; this.parentId = parentId; this.spanId = spanId; this.extraList = extraList; } /** * Includes mandatory fields {@link #traceIdHigh()}, {@link #traceId()}, {@link #spanId()} and the * {@link #shared() shared flag}. * * <p>The shared flag is included to have parity with the {@link #hashCode()}. */ @Override public boolean equals(Object o) { if (o == this) return true; // Hack that allows WeakConcurrentMap to lookup without allocating a new object. if (o instanceof WeakReference) o = ((WeakReference) o).get(); if (!(o instanceof TraceContext)) return false; TraceContext that = (TraceContext) o; return (traceIdHigh == that.traceIdHigh) && (traceId == that.traceId) && (spanId == that.spanId) && ((flags & FLAG_SHARED) == (that.flags & FLAG_SHARED)); } volatile int hashCode; // Lazily initialized and cached. /** * Includes mandatory fields {@link #traceIdHigh()}, {@link #traceId()}, {@link #spanId()} and the * {@link #shared() shared flag}. * * <p>The shared flag is included in the hash code to ensure loopback span data are partitioned * properly. For example, if a client calls itself, the server-side shouldn't overwrite the client * side. */ @Override public int hashCode() { int h = hashCode; if (h == 0) { h = 1000003; h ^= (int) ((traceIdHigh >>> 32) ^ traceIdHigh); h *= 1000003; h ^= (int) ((traceId >>> 32) ^ traceId); h *= 1000003; h ^= (int) ((spanId >>> 32) ^ spanId); h *= 1000003; h ^= flags & FLAG_SHARED; hashCode = h; } return h; } static List<Object> ensureExtraAdded(List<Object> extraList, Object extra) { if (extra == null) throw new NullPointerException("extra == null"); // ignore adding the same instance twice for (int i = 0, length = extraList.size(); i < length; i++) { if (extra == extraList.get(i)) return extraList; } extraList = ensureMutable(extraList); extraList.add(extra); return extraList; } static <T> T findExtra(Class<T> type, List<Object> extra) { if (type == null) throw new NullPointerException("type == null"); for (int i = 0, length = extra.size(); i < length; i++) { Object nextExtra = extra.get(i); if (nextExtra.getClass() == type) return (T) nextExtra; } return null; } }
openzipkin/brave
brave/src/main/java/brave/propagation/TraceContext.java
6,660
// absent parent is ok
line_comment
nl
/* * Copyright The OpenZipkin Authors * SPDX-License-Identifier: Apache-2.0 */ package brave.propagation; import brave.Span; import brave.baggage.BaggageFields; import brave.baggage.BaggagePropagation; import brave.internal.InternalPropagation; import brave.internal.Nullable; import brave.internal.Platform; import brave.internal.baggage.ExtraBaggageContext; import java.lang.ref.WeakReference; import java.util.Collections; import java.util.List; import static brave.internal.InternalPropagation.FLAG_LOCAL_ROOT; import static brave.internal.InternalPropagation.FLAG_SAMPLED; import static brave.internal.InternalPropagation.FLAG_SAMPLED_LOCAL; import static brave.internal.InternalPropagation.FLAG_SAMPLED_SET; import static brave.internal.InternalPropagation.FLAG_SHARED; import static brave.internal.codec.HexCodec.lenientLowerHexToUnsignedLong; import static brave.internal.codec.HexCodec.toLowerHex; import static brave.internal.codec.HexCodec.writeHexLong; import static brave.internal.collect.Lists.ensureImmutable; import static brave.internal.collect.Lists.ensureMutable; import static brave.propagation.TraceIdContext.toTraceIdString; /** * Contains trace identifiers and sampling data propagated in and out-of-process. * * <p>Particularly, this includes trace identifiers and sampled state. * * <p>The implementation was originally {@code com.github.kristofa.brave.SpanId}, which was a * port of {@code com.twitter.finagle.tracing.TraceId}. Unlike these mentioned, this type does not * expose a single binary representation. That's because propagation forms can now vary. * * @since 4.0 */ //@Immutable public final class TraceContext extends SamplingFlags { /** * Used to send the trace context downstream. For example, as http headers. * * <p>For example, to put the context on an {@link java.net.HttpURLConnection}, you can do this: * <pre>{@code * // in your constructor * injector = tracing.propagation().injector(URLConnection::setRequestProperty); * * // later in your code, reuse the function you created above to add trace headers * HttpURLConnection connection = (HttpURLConnection) new URL("http://myserver").openConnection(); * injector.inject(span.context(), connection); * }</pre> * * <p><em>Note</em>: This type is safe to implement as a lambda, or use as a method reference as * it is effectively a {@code FunctionalInterface}. It isn't annotated as such because the project * has a minimum Java language level 6. * * @since 4.0 */ // @FunctionalInterface, except Java language level 6. Do not add methods as it will break API! public interface Injector<R> { /** * Usually calls a setter for each propagation field to send downstream. * * @param traceContext possibly unsampled. * @param request holds propagation fields. For example, an outgoing message or http request. */ void inject(TraceContext traceContext, R request); } /** * Used to continue an incoming trace. For example, by reading http headers. * * <p><em>Note</em>: This type is safe to implement as a lambda, or use as a method reference as * it is effectively a {@code FunctionalInterface}. It isn't annotated as such because the project * has a minimum Java language level 6. * * @see brave.Tracer#nextSpan(TraceContextOrSamplingFlags) * @since 4.0 */ // @FunctionalInterface, except Java language level 6. Do not add methods as it will break API! public interface Extractor<R> { /** * Returns either a trace context or sampling flags parsed from the request. If nothing was * parsable, sampling flags will be set to {@link SamplingFlags#EMPTY}. * * @param request holds propagation fields. For example, an incoming message or http request. */ TraceContextOrSamplingFlags extract(R request); } public static Builder newBuilder() { return new Builder(); } /** When non-zero, the trace containing this span uses 128-bit trace identifiers. */ public long traceIdHigh() { return traceIdHigh; } /** Unique 8-byte identifier for a trace, set on all spans within it. */ public long traceId() { return traceId; } /** * Returns the first {@link #spanId()} in a partition of a trace: otherwise known as an entry * span. This could be a root span or a span representing incoming work (ex {@link * Span.Kind#SERVER} or {@link Span.Kind#CONSUMER}. Unlike {@link #parentIdAsLong()}, this value * is inherited to child contexts until the trace exits the process. This value is inherited for * all child spans until the trace exits the process. This could also be described as an entry * span. * * <p>When {@link #isLocalRoot()}, this ID will be the same as the {@link #spanId() span ID}. * * <p>The local root ID can be used for dependency link processing, skipping data or partitioning * purposes. For example, one processor could skip all intermediate (local) spans between an * incoming service call and any outgoing ones. * * <p>This does not group together multiple points of entry in the same trace. For example, * repetitive consumption of the same incoming message results in different local roots. * * @return the {@link #spanId() span ID} of the local root or zero if this context wasn't * initialized by a {@link brave.Tracer}. */ // This is the first span ID that became a Span or ScopedSpan public long localRootId() { return localRootId; } public boolean isLocalRoot() { return (flags & FLAG_LOCAL_ROOT) == FLAG_LOCAL_ROOT; } /** * The parent's {@link #spanId} or null if this the root span in a trace. * * @see #parentIdAsLong() */ @Nullable public final Long parentId() { return parentId != 0 ? parentId : null; } /** * Like {@link #parentId()} except returns a primitive where zero implies absent. * * <p>Using this method will avoid allocation, so is encouraged when copying data. */ public long parentIdAsLong() { return parentId; } /** * Unique 8-byte identifier of this span within a trace. * * <p>A span is uniquely identified in storage by ({@linkplain #traceId}, {@linkplain #spanId}). */ public long spanId() { return spanId; } /** * True if we are recording a server span with the same span ID parsed from incoming headers. * * <h3>Impact on indexing</h3> * <p>When an RPC trace is client-originated, it will be sampled and the same span ID is used for * the server side. The shared flag helps prioritize timestamp and duration indexing in favor of * the client. In v1 format, there is no shared flag, so it implies converters should not store * timestamp and duration on the server span explicitly. */ public boolean shared() { return (flags & FLAG_SHARED) == FLAG_SHARED; } /** * Used internally by propagation plugins to search for their instance of state regardless of if * it is in a {@linkplain TraceContext} or {@linkplain TraceContextOrSamplingFlags}. * * <p>Tools that work only on {@linkplain TraceContext} should use {@link #findExtra(Class)} * instead. * * @see #findExtra(Class) * @see TraceContextOrSamplingFlags#extra() * @see Builder#addExtra(Object) for notes on extra values. * @since 4.9 */ public List<Object> extra() { return extraList; } /** * Used internally by propagation plugins to search for their instance of state. * * @see #extra() * @see Builder#addExtra(Object) for notes on extra values. */ @Nullable public <T> T findExtra(Class<T> type) { return findExtra(type, extraList); } public Builder toBuilder() { return new Builder(this); } volatile String traceIdString; // Lazily initialized and cached. /** Returns the hex representation of the span's trace ID */ public String traceIdString() { String r = traceIdString; if (r == null) { r = toTraceIdString(traceIdHigh, traceId); traceIdString = r; } return r; } volatile String parentIdString; // Lazily initialized and cached. /** Returns the hex representation of the span's parent ID */ @Nullable public String parentIdString() { String r = parentIdString; if (r == null && parentId != 0L) { r = parentIdString = toLowerHex(parentId); } return r; } volatile String localRootIdString; // Lazily initialized and cached. /** Returns the hex representation of the span's local root ID */ @Nullable public String localRootIdString() { String r = localRootIdString; if (r == null && localRootId != 0L) { r = localRootIdString = toLowerHex(localRootId); } return r; } volatile String spanIdString; // Lazily initialized and cached. /** Returns the hex representation of the span's ID */ public String spanIdString() { String r = spanIdString; if (r == null) { r = spanIdString = toLowerHex(spanId); } return r; } /** Returns {@code $traceId/$spanId} */ @Override public String toString() { boolean traceHi = traceIdHigh != 0; char[] result = new char[((traceHi ? 3 : 2) * 16) + 1]; // 2 ids and the delimiter int pos = 0; if (traceHi) { writeHexLong(result, pos, traceIdHigh); pos += 16; } writeHexLong(result, pos, traceId); pos += 16; result[pos++] = '/'; writeHexLong(result, pos, spanId); return new String(result); } public static final class Builder { long traceIdHigh, traceId, parentId, spanId; long localRootId; // intentionally only mutable by the copy constructor to control usage. int flags; List<Object> extraList = Collections.emptyList(); Builder(TraceContext context) { // no external implementations traceIdHigh = context.traceIdHigh; traceId = context.traceId; localRootId = context.localRootId; parentId = context.parentId; spanId = context.spanId; flags = context.flags; extraList = context.extraList; } /** @see TraceContext#traceIdHigh() */ public Builder traceIdHigh(long traceIdHigh) { this.traceIdHigh = traceIdHigh; return this; } /** @see TraceContext#traceId() */ public Builder traceId(long traceId) { this.traceId = traceId; return this; } /** @see TraceContext#parentIdAsLong() */ public Builder parentId(long parentId) { this.parentId = parentId; return this; } /** @see TraceContext#parentId() */ public Builder parentId(@Nullable Long parentId) { if (parentId == null) parentId = 0L; this.parentId = parentId; return this; } /** @see TraceContext#spanId() */ public Builder spanId(long spanId) { this.spanId = spanId; return this; } /** @see TraceContext#sampledLocal() */ public Builder sampledLocal(boolean sampledLocal) { if (sampledLocal) { flags |= FLAG_SAMPLED_LOCAL; } else { flags &= ~FLAG_SAMPLED_LOCAL; } return this; } /** @see TraceContext#sampled() */ public Builder sampled(boolean sampled) { flags = InternalPropagation.sampled(sampled, flags); return this; } /** @see TraceContext#sampled() */ public Builder sampled(@Nullable Boolean sampled) { if (sampled == null) { flags &= ~(FLAG_SAMPLED_SET | FLAG_SAMPLED); return this; } return sampled(sampled.booleanValue()); } /** @see TraceContext#debug() */ public Builder debug(boolean debug) { flags = SamplingFlags.debug(debug, flags); return this; } /** @see TraceContext#shared() */ public Builder shared(boolean shared) { if (shared) { flags |= FLAG_SHARED; } else { flags &= ~FLAG_SHARED; } return this; } /** * Allows you to control {@link #extra()} explicitly. * * @since 5.12 */ public Builder clearExtra() { extraList = Collections.emptyList(); return this; } /** * This is an advanced function used for {@link Propagation} plugins, such as * {@link BaggagePropagation}, to add an internal object to hold state when it isn't already in * {@linkplain #extra()}. * * <p>The "extra" parameter is intentionally opaque, and should be an internal type defined by * a {@linkplain Propagation} plugin. An example implementation could be storing a class * containing a correlation value, which is extracted from incoming requests and injected as-is * onto outgoing requests. A real world use is {@link BaggageFields}, which holds all baggage * fields to propagate in one instance. * * <p>Note: It is the responsibility of {@link Propagation.Factory#decorate(TraceContext)} * to consolidate elements (by searching for an existing instance of their state with {@link * #findExtra(Class)} or {@link #extra()}). If it doesn't, there could be multiple instances of * a given type and this can break logic and add overhead. Decoration is also when * implementations define their scope. For example, a plugin that only propagates a field * without changing will be constant for the whole request. A plugin that allows changes of * state need careful coding, such as done in {@link BaggagePropagation}. * * @see #extra() * @since 5.12 */ public Builder addExtra(Object extra) { extraList = ensureExtraAdded(extraList, extra); return this; } /** * Returns true when {@link TraceContext#traceId()} and potentially also {@link * TraceContext#traceIdHigh()} were parsed from the input. This assumes the input is valid, an * up to 32 character lower-hex string. * * <p>Returns boolean, not this, for conditional, exception free parsing: * * <p>Example use: * <pre>{@code * // Attempt to parse the trace ID or break out if unsuccessful for any reason * String traceIdString = getter.get(request, key); * if (!builder.parseTraceId(traceIdString, propagation.traceIdKey)) { * return TraceContextOrSamplingFlags.EMPTY; * } * }</pre> * * @param traceIdString the 1-32 character lowerhex string * @param key the name of the propagation field representing the trace ID; only using in * logging * @return false if the input is null or malformed */ // temporarily package protected until we figure out if this is reusable enough to expose boolean parseTraceId(String traceIdString, Object key) { if (isNull(key, traceIdString)) return false; int length = traceIdString.length(); if (invalidIdLength(key, length, 32)) return false; boolean traceIdHighAllZeros = false, traceIdAllZeros = false; // left-most characters, if any, are the high bits int traceIdIndex = Math.max(0, length - 16); if (traceIdIndex > 0) { traceIdHigh = lenientLowerHexToUnsignedLong(traceIdString, 0, traceIdIndex); if (traceIdHigh == 0L) { traceIdHighAllZeros = isAllZeros(traceIdString, 0, traceIdIndex); if (!traceIdHighAllZeros) { maybeLogNotLowerHex(traceIdString); return false; } } } else { traceIdHighAllZeros = true; } // right-most up to 16 characters are the low bits traceId = lenientLowerHexToUnsignedLong(traceIdString, traceIdIndex, length); if (traceId == 0L) { traceIdAllZeros = isAllZeros(traceIdString, traceIdIndex, length); if (!traceIdAllZeros) { maybeLogNotLowerHex(traceIdString); return false; } } if (traceIdHighAllZeros && traceIdAllZeros) { Platform.get().log("Invalid input: traceId was all zeros", null); } return traceIdHigh != 0L || traceId != 0L; } /** Parses the parent id from the input string. Returns true if the ID was missing or valid. */ <R, K> boolean parseParentId(Propagation.Getter<R, K> getter, R request, K key) { String parentIdString = getter.get(request, key); if (parentIdString == null) return true; // absent parent<SUF> int length = parentIdString.length(); if (invalidIdLength(key, length, 16)) return false; parentId = lenientLowerHexToUnsignedLong(parentIdString, 0, length); if (parentId != 0) return true; maybeLogNotLowerHex(parentIdString); return false; } /** Parses the span id from the input string. Returns true if the ID is valid. */ <R, K> boolean parseSpanId(Propagation.Getter<R, K> getter, R request, K key) { String spanIdString = getter.get(request, key); if (isNull(key, spanIdString)) return false; int length = spanIdString.length(); if (invalidIdLength(key, length, 16)) return false; spanId = lenientLowerHexToUnsignedLong(spanIdString, 0, length); if (spanId == 0) { if (isAllZeros(spanIdString, 0, length)) { Platform.get().log("Invalid input: spanId was all zeros", null); return false; } maybeLogNotLowerHex(spanIdString); return false; } return true; } static boolean invalidIdLength(Object key, int length, int max) { if (length > 1 && length <= max) return false; assert max == 32 || max == 16; Platform.get().log(max == 32 ? "{0} should be a 1 to 32 character lower-hex string with no prefix" : "{0} should be a 1 to 16 character lower-hex string with no prefix", key, null); return true; } static boolean isNull(Object key, String maybeNull) { if (maybeNull != null) return false; Platform.get().log("{0} was null", key, null); return true; } /** Helps differentiate a parse failure from a successful parse of all zeros. */ static boolean isAllZeros(String value, int beginIndex, int endIndex) { for (int i = beginIndex; i < endIndex; i++) { if (value.charAt(i) != '0') return false; } return true; } static void maybeLogNotLowerHex(String notLowerHex) { Platform.get().log("{0} is not a lower-hex string", notLowerHex, null); } /** @throws IllegalArgumentException if missing trace ID or span ID */ public TraceContext build() { String missing = ""; if (traceIdHigh == 0L && traceId == 0L) missing += " traceId"; if (spanId == 0L) missing += " spanId"; if (!"".equals(missing)) throw new IllegalArgumentException("Missing:" + missing); return new TraceContext( flags, traceIdHigh, traceId, localRootId, parentId, spanId, ensureImmutable(extraList) ); } Builder() { // no external implementations } } TraceContext shallowCopy() { return new TraceContext(flags, traceIdHigh, traceId, localRootId, parentId, spanId, extraList); } TraceContext withExtra(List<Object> extra) { return new TraceContext(flags, traceIdHigh, traceId, localRootId, parentId, spanId, extra); } TraceContext withFlags(int flags) { return new TraceContext(flags, traceIdHigh, traceId, localRootId, parentId, spanId, extraList); } final long traceIdHigh, traceId, localRootId, parentId, spanId; final List<Object> extraList; TraceContext( int flags, long traceIdHigh, long traceId, long localRootId, long parentId, long spanId, List<Object> extraList ) { super(flags); this.traceIdHigh = traceIdHigh; this.traceId = traceId; this.localRootId = localRootId; this.parentId = parentId; this.spanId = spanId; this.extraList = extraList; } /** * Includes mandatory fields {@link #traceIdHigh()}, {@link #traceId()}, {@link #spanId()} and the * {@link #shared() shared flag}. * * <p>The shared flag is included to have parity with the {@link #hashCode()}. */ @Override public boolean equals(Object o) { if (o == this) return true; // Hack that allows WeakConcurrentMap to lookup without allocating a new object. if (o instanceof WeakReference) o = ((WeakReference) o).get(); if (!(o instanceof TraceContext)) return false; TraceContext that = (TraceContext) o; return (traceIdHigh == that.traceIdHigh) && (traceId == that.traceId) && (spanId == that.spanId) && ((flags & FLAG_SHARED) == (that.flags & FLAG_SHARED)); } volatile int hashCode; // Lazily initialized and cached. /** * Includes mandatory fields {@link #traceIdHigh()}, {@link #traceId()}, {@link #spanId()} and the * {@link #shared() shared flag}. * * <p>The shared flag is included in the hash code to ensure loopback span data are partitioned * properly. For example, if a client calls itself, the server-side shouldn't overwrite the client * side. */ @Override public int hashCode() { int h = hashCode; if (h == 0) { h = 1000003; h ^= (int) ((traceIdHigh >>> 32) ^ traceIdHigh); h *= 1000003; h ^= (int) ((traceId >>> 32) ^ traceId); h *= 1000003; h ^= (int) ((spanId >>> 32) ^ spanId); h *= 1000003; h ^= flags & FLAG_SHARED; hashCode = h; } return h; } static List<Object> ensureExtraAdded(List<Object> extraList, Object extra) { if (extra == null) throw new NullPointerException("extra == null"); // ignore adding the same instance twice for (int i = 0, length = extraList.size(); i < length; i++) { if (extra == extraList.get(i)) return extraList; } extraList = ensureMutable(extraList); extraList.add(extra); return extraList; } static <T> T findExtra(Class<T> type, List<Object> extra) { if (type == null) throw new NullPointerException("type == null"); for (int i = 0, length = extra.size(); i < length; i++) { Object nextExtra = extra.get(i); if (nextExtra.getClass() == type) return (T) nextExtra; } return null; } }
3421_22
/* * Copyright The OpenZipkin Authors * SPDX-License-Identifier: Apache-2.0 */ package zipkin2.v1; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Objects; import zipkin2.Endpoint; import zipkin2.Span; import zipkin2.internal.Nullable; import static java.util.Collections.unmodifiableList; import static zipkin2.internal.HexCodec.lowerHexToUnsignedLong; /** * V1 spans are different from v2 especially as annotations repeat. Support is available to help * migrate old code or allow for parsing older data formats. * * @deprecated new code should use {@link Span}. */ @Deprecated public final class V1Span { static final Endpoint EMPTY_ENDPOINT = Endpoint.newBuilder().build(); /** When non-zero, the trace containing this span uses 128-bit trace identifiers. */ public long traceIdHigh() { return traceIdHigh; } /** lower 64-bits of the {@link Span#traceId()} */ public long traceId() { return traceId; } /** Same as {@link zipkin2.Span#id()} except packed into a long. Zero means root span. */ public long id() { return id; } /** Same as {@link zipkin2.Span#name()} */ public String name() { return name; } /** The parent's {@link #id()} or zero if this the root span in a trace. */ public long parentId() { return parentId; } /** Same as {@link Span#timestampAsLong()} */ public long timestamp() { return timestamp; } /** Same as {@link Span#durationAsLong()} */ public long duration() { return duration; } /** * Same as {@link Span#annotations()}, except each may be associated with {@link * Span#localEndpoint()} */ public List<V1Annotation> annotations() { return annotations; } /** * {@link Span#tags()} are allocated to binary annotations with a {@link * V1BinaryAnnotation#stringValue()}. {@link Span#remoteEndpoint()} to those without. */ public List<V1BinaryAnnotation> binaryAnnotations() { return binaryAnnotations; } /** Same as {@link Span#debug()} */ public Boolean debug() { return debug; } final long traceIdHigh, traceId, id; final String name; final long parentId, timestamp, duration; final List<V1Annotation> annotations; final List<V1BinaryAnnotation> binaryAnnotations; final Boolean debug; V1Span(Builder builder) { if (builder.traceId == 0L) throw new IllegalArgumentException("traceId == 0"); if (builder.id == 0L) throw new IllegalArgumentException("id == 0"); this.traceId = builder.traceId; this.traceIdHigh = builder.traceIdHigh; this.name = builder.name; this.id = builder.id; this.parentId = builder.parentId; this.timestamp = builder.timestamp; this.duration = builder.duration; this.annotations = sortedList(builder.annotations); this.binaryAnnotations = sortedList(builder.binaryAnnotations); this.debug = builder.debug; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { // ID accessors are here to help organize builders by their identifiers /** Sets {@link V1Span#traceIdHigh()} */ public long traceIdHigh() { return traceIdHigh; } /** Sets {@link V1Span#traceId()} */ public long traceId() { return traceId; } /** Sets {@link V1Span#id()} */ public long id() { return id; } long traceIdHigh, traceId, parentId, id; String name; long timestamp, duration; ArrayList<V1Annotation> annotations; ArrayList<V1BinaryAnnotation> binaryAnnotations; Boolean debug; Builder() { } public Builder clear() { traceId = traceIdHigh = id = 0; name = null; parentId = timestamp = duration = 0; if (annotations != null) annotations.clear(); if (binaryAnnotations != null) binaryAnnotations.clear(); debug = null; return this; } /** Same as {@link Span.Builder#traceId(String)} */ public Builder traceId(String traceId) { if (traceId == null) throw new NullPointerException("traceId == null"); if (traceId.length() == 32) { traceIdHigh = lowerHexToUnsignedLong(traceId, 0); } this.traceId = lowerHexToUnsignedLong(traceId); return this; } /** Sets {@link V1Span#traceId()} */ public Builder traceId(long traceId) { this.traceId = traceId; return this; } /** Sets {@link V1Span#traceIdHigh()} */ public Builder traceIdHigh(long traceIdHigh) { this.traceIdHigh = traceIdHigh; return this; } /** Sets {@link V1Span#id()} */ public Builder id(long id) { this.id = id; return this; } /** Same as {@link Span.Builder#id(String)} */ public Builder id(String id) { if (id == null) throw new NullPointerException("id == null"); this.id = lowerHexToUnsignedLong(id); return this; } /** Same as {@link Span.Builder#parentId(String)} */ public Builder parentId(String parentId) { this.parentId = parentId != null ? lowerHexToUnsignedLong(parentId) : 0L; return this; } /** Sets {@link V1Span#parentId()} */ public Builder parentId(long parentId) { this.parentId = parentId; return this; } /** Sets {@link V1Span#name()} */ public Builder name(String name) { this.name = name == null || name.isEmpty() ? null : name.toLowerCase(Locale.ROOT); return this; } /** Sets {@link V1Span#timestamp()} */ public Builder timestamp(long timestamp) { this.timestamp = timestamp; return this; } /** Sets {@link V1Span#duration()} */ public Builder duration(long duration) { this.duration = duration; return this; } /** Sets {@link V1Span#annotations()} */ public Builder addAnnotation(long timestamp, String value, @Nullable Endpoint endpoint) { if (annotations == null) annotations = new ArrayList<>(4); if (EMPTY_ENDPOINT.equals(endpoint)) endpoint = null; annotations.add(new V1Annotation(timestamp, value, endpoint)); return this; } /** Creates an address annotation, which is the same as {@link Span#remoteEndpoint()} */ public Builder addBinaryAnnotation(String address, Endpoint endpoint) { // Ignore empty endpoints rather than crashing v1 parsers on bad address data if (endpoint == null || EMPTY_ENDPOINT.equals(endpoint)) return this; if (binaryAnnotations == null) binaryAnnotations = new ArrayList<>(4); binaryAnnotations.add(new V1BinaryAnnotation(address, null, endpoint)); return this; } /** * Creates a tag annotation, which is the same as {@link Span#tags()} except duplicating the * endpoint. * * <p>A key of "lc" and empty value substitutes for {@link Span#localEndpoint()}. */ public Builder addBinaryAnnotation(String key, String value, Endpoint endpoint) { if (value == null) throw new NullPointerException("value == null"); if (EMPTY_ENDPOINT.equals(endpoint)) endpoint = null; if (binaryAnnotations == null) binaryAnnotations = new ArrayList<>(4); binaryAnnotations.add(new V1BinaryAnnotation(key, value, endpoint)); return this; } /** Sets {@link V1Span#debug()} */ public Builder debug(@Nullable Boolean debug) { this.debug = debug; return this; } public V1Span build() { return new V1Span(this); } } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof V1Span)) return false; V1Span that = (V1Span) o; return traceIdHigh == that.traceIdHigh && traceId == that.traceId && Objects.equals(name, that.name) && id == that.id && parentId == that.parentId && timestamp == that.timestamp && duration == that.duration && annotations.equals(that.annotations) && binaryAnnotations.equals(that.binaryAnnotations) && Objects.equals(debug, that.debug); } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= (int) (h ^ ((traceIdHigh >>> 32) ^ traceIdHigh)); h *= 1000003; h ^= (int) (h ^ ((traceId >>> 32) ^ traceId)); h *= 1000003; h ^= name == null ? 0 : name.hashCode(); h *= 1000003; h ^= (int) (h ^ ((id >>> 32) ^ id)); h *= 1000003; h ^= (int) (h ^ ((parentId >>> 32) ^ parentId)); h *= 1000003; h ^= (int) (h ^ ((timestamp >>> 32) ^ timestamp)); h *= 1000003; h ^= (int) (h ^ ((duration >>> 32) ^ duration)); h *= 1000003; h ^= annotations.hashCode(); h *= 1000003; h ^= binaryAnnotations.hashCode(); h *= 1000003; h ^= debug == null ? 0 : debug.hashCode(); return h; } static <T extends Comparable<T>> List<T> sortedList(List<T> input) { if (input == null) return Collections.emptyList(); Collections.sort(input); return unmodifiableList(new ArrayList<>(input)); } }
openzipkin/zipkin
zipkin/src/main/java/zipkin2/v1/V1Span.java
2,848
/** Sets {@link V1Span#parentId()} */
block_comment
nl
/* * Copyright The OpenZipkin Authors * SPDX-License-Identifier: Apache-2.0 */ package zipkin2.v1; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Objects; import zipkin2.Endpoint; import zipkin2.Span; import zipkin2.internal.Nullable; import static java.util.Collections.unmodifiableList; import static zipkin2.internal.HexCodec.lowerHexToUnsignedLong; /** * V1 spans are different from v2 especially as annotations repeat. Support is available to help * migrate old code or allow for parsing older data formats. * * @deprecated new code should use {@link Span}. */ @Deprecated public final class V1Span { static final Endpoint EMPTY_ENDPOINT = Endpoint.newBuilder().build(); /** When non-zero, the trace containing this span uses 128-bit trace identifiers. */ public long traceIdHigh() { return traceIdHigh; } /** lower 64-bits of the {@link Span#traceId()} */ public long traceId() { return traceId; } /** Same as {@link zipkin2.Span#id()} except packed into a long. Zero means root span. */ public long id() { return id; } /** Same as {@link zipkin2.Span#name()} */ public String name() { return name; } /** The parent's {@link #id()} or zero if this the root span in a trace. */ public long parentId() { return parentId; } /** Same as {@link Span#timestampAsLong()} */ public long timestamp() { return timestamp; } /** Same as {@link Span#durationAsLong()} */ public long duration() { return duration; } /** * Same as {@link Span#annotations()}, except each may be associated with {@link * Span#localEndpoint()} */ public List<V1Annotation> annotations() { return annotations; } /** * {@link Span#tags()} are allocated to binary annotations with a {@link * V1BinaryAnnotation#stringValue()}. {@link Span#remoteEndpoint()} to those without. */ public List<V1BinaryAnnotation> binaryAnnotations() { return binaryAnnotations; } /** Same as {@link Span#debug()} */ public Boolean debug() { return debug; } final long traceIdHigh, traceId, id; final String name; final long parentId, timestamp, duration; final List<V1Annotation> annotations; final List<V1BinaryAnnotation> binaryAnnotations; final Boolean debug; V1Span(Builder builder) { if (builder.traceId == 0L) throw new IllegalArgumentException("traceId == 0"); if (builder.id == 0L) throw new IllegalArgumentException("id == 0"); this.traceId = builder.traceId; this.traceIdHigh = builder.traceIdHigh; this.name = builder.name; this.id = builder.id; this.parentId = builder.parentId; this.timestamp = builder.timestamp; this.duration = builder.duration; this.annotations = sortedList(builder.annotations); this.binaryAnnotations = sortedList(builder.binaryAnnotations); this.debug = builder.debug; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { // ID accessors are here to help organize builders by their identifiers /** Sets {@link V1Span#traceIdHigh()} */ public long traceIdHigh() { return traceIdHigh; } /** Sets {@link V1Span#traceId()} */ public long traceId() { return traceId; } /** Sets {@link V1Span#id()} */ public long id() { return id; } long traceIdHigh, traceId, parentId, id; String name; long timestamp, duration; ArrayList<V1Annotation> annotations; ArrayList<V1BinaryAnnotation> binaryAnnotations; Boolean debug; Builder() { } public Builder clear() { traceId = traceIdHigh = id = 0; name = null; parentId = timestamp = duration = 0; if (annotations != null) annotations.clear(); if (binaryAnnotations != null) binaryAnnotations.clear(); debug = null; return this; } /** Same as {@link Span.Builder#traceId(String)} */ public Builder traceId(String traceId) { if (traceId == null) throw new NullPointerException("traceId == null"); if (traceId.length() == 32) { traceIdHigh = lowerHexToUnsignedLong(traceId, 0); } this.traceId = lowerHexToUnsignedLong(traceId); return this; } /** Sets {@link V1Span#traceId()} */ public Builder traceId(long traceId) { this.traceId = traceId; return this; } /** Sets {@link V1Span#traceIdHigh()} */ public Builder traceIdHigh(long traceIdHigh) { this.traceIdHigh = traceIdHigh; return this; } /** Sets {@link V1Span#id()} */ public Builder id(long id) { this.id = id; return this; } /** Same as {@link Span.Builder#id(String)} */ public Builder id(String id) { if (id == null) throw new NullPointerException("id == null"); this.id = lowerHexToUnsignedLong(id); return this; } /** Same as {@link Span.Builder#parentId(String)} */ public Builder parentId(String parentId) { this.parentId = parentId != null ? lowerHexToUnsignedLong(parentId) : 0L; return this; } /** Sets {@link V1Span#parentId()}<SUF>*/ public Builder parentId(long parentId) { this.parentId = parentId; return this; } /** Sets {@link V1Span#name()} */ public Builder name(String name) { this.name = name == null || name.isEmpty() ? null : name.toLowerCase(Locale.ROOT); return this; } /** Sets {@link V1Span#timestamp()} */ public Builder timestamp(long timestamp) { this.timestamp = timestamp; return this; } /** Sets {@link V1Span#duration()} */ public Builder duration(long duration) { this.duration = duration; return this; } /** Sets {@link V1Span#annotations()} */ public Builder addAnnotation(long timestamp, String value, @Nullable Endpoint endpoint) { if (annotations == null) annotations = new ArrayList<>(4); if (EMPTY_ENDPOINT.equals(endpoint)) endpoint = null; annotations.add(new V1Annotation(timestamp, value, endpoint)); return this; } /** Creates an address annotation, which is the same as {@link Span#remoteEndpoint()} */ public Builder addBinaryAnnotation(String address, Endpoint endpoint) { // Ignore empty endpoints rather than crashing v1 parsers on bad address data if (endpoint == null || EMPTY_ENDPOINT.equals(endpoint)) return this; if (binaryAnnotations == null) binaryAnnotations = new ArrayList<>(4); binaryAnnotations.add(new V1BinaryAnnotation(address, null, endpoint)); return this; } /** * Creates a tag annotation, which is the same as {@link Span#tags()} except duplicating the * endpoint. * * <p>A key of "lc" and empty value substitutes for {@link Span#localEndpoint()}. */ public Builder addBinaryAnnotation(String key, String value, Endpoint endpoint) { if (value == null) throw new NullPointerException("value == null"); if (EMPTY_ENDPOINT.equals(endpoint)) endpoint = null; if (binaryAnnotations == null) binaryAnnotations = new ArrayList<>(4); binaryAnnotations.add(new V1BinaryAnnotation(key, value, endpoint)); return this; } /** Sets {@link V1Span#debug()} */ public Builder debug(@Nullable Boolean debug) { this.debug = debug; return this; } public V1Span build() { return new V1Span(this); } } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof V1Span)) return false; V1Span that = (V1Span) o; return traceIdHigh == that.traceIdHigh && traceId == that.traceId && Objects.equals(name, that.name) && id == that.id && parentId == that.parentId && timestamp == that.timestamp && duration == that.duration && annotations.equals(that.annotations) && binaryAnnotations.equals(that.binaryAnnotations) && Objects.equals(debug, that.debug); } @Override public int hashCode() { int h = 1; h *= 1000003; h ^= (int) (h ^ ((traceIdHigh >>> 32) ^ traceIdHigh)); h *= 1000003; h ^= (int) (h ^ ((traceId >>> 32) ^ traceId)); h *= 1000003; h ^= name == null ? 0 : name.hashCode(); h *= 1000003; h ^= (int) (h ^ ((id >>> 32) ^ id)); h *= 1000003; h ^= (int) (h ^ ((parentId >>> 32) ^ parentId)); h *= 1000003; h ^= (int) (h ^ ((timestamp >>> 32) ^ timestamp)); h *= 1000003; h ^= (int) (h ^ ((duration >>> 32) ^ duration)); h *= 1000003; h ^= annotations.hashCode(); h *= 1000003; h ^= binaryAnnotations.hashCode(); h *= 1000003; h ^= debug == null ? 0 : debug.hashCode(); return h; } static <T extends Comparable<T>> List<T> sortedList(List<T> input) { if (input == null) return Collections.emptyList(); Collections.sort(input); return unmodifiableList(new ArrayList<>(input)); } }
116445_46
package com.opedio.jboss.service.discus; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.solusi247.poin.data.WFSendSmsQueue; import com.solusi247.poin.util.TselpoinIDGenerator; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jboss.logging.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.IOException; import java.net.URLEncoder; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import javax.sql.DataSource; import javax.tools.JavaFileObject; public class DataDiscusSender extends Thread { private static Logger logger = Logger.getLogger(DataDiscusSender.class); private boolean keep_running = false; /* <jms-queue name="WFSendSmsQueue"> <entry name="queue/WFSendSmsQueue"/> <entry name="java:jboss/exported/jms/queue/WFSendSmsQueue"/> </jms-queue> <jms-queue name="WFSendSmsHisQueue"> <entry name="queue/WFSendSmsHisQueue"/> <entry name="java:jboss/exported/jms/queue/WFSendSmsHisQueue"/> </jms-queue> */ private List<PullerJMSClient>_broker = new ArrayList<PullerJMSClient>(); private int _nr_of_jms_connections = 4; private String JMS_QUEUE = "queue/WFSendSmsQueue"; private BlockingQueue<WFSendSmsQueue> _sms_queue = null; private int _max_row_num = 1000; private int _timer = 60000; private DataSource ds = null; private DB db = null; private volatile long start_time;//ms private volatile long end_time; private volatile long dif_time; public DataDiscusSender(int thread_number, int queue_size, int row_num, int timer, DataSource datasource, DB mongoDB) { if (thread_number>0) this._nr_of_jms_connections = thread_number; if (queue_size>=(2*_nr_of_jms_connections)) _sms_queue = new ArrayBlockingQueue<WFSendSmsQueue>(queue_size); else _sms_queue = new ArrayBlockingQueue<WFSendSmsQueue>(3*this._nr_of_jms_connections); if (row_num>0) this._max_row_num = row_num; if (timer>100) this._timer = timer; this.ds = datasource; this.db = mongoDB; logger.info("construct SmsSender"); } public void ophouden() { this.keep_running = false; } private void startApp() { logger.info("startApp"); // TODO /*for (int i=0;i<_nr_of_jms_connections;i++) { PullerJMSClient jj = new PullerJMSClient(JMS_QUEUE,_sms_queue); jj.start(); _broker.add(jj); }*/ } private void stopApp() { logger.info("[SmsSender] is stopping"); for (PullerJMSClient j: _broker) { try { j.ophouden(); j.interrupt(); } catch (Exception e) { logger.error("[closeJMSConnection] "+ e); for (StackTraceElement s: e.getStackTrace()) { logger.error(" at "+ s); } } } for (PullerJMSClient j: _broker) { try { if (j!=null && j.isAlive()) { j.join(); } } catch (Exception e) { logger.error("[closeJMSConnection] "+ e); for (StackTraceElement s: e.getStackTrace()) { logger.error(" at "+ s); } } } logger.info("[SmsSender] closeJMSConnection done"); } @Override public void run() { keep_running = true; startApp(); while (keep_running) { try { // getData(); getDataMongo(); // logger.info("TIMER"); } catch (Exception e) { logger.error(e); // keep_running = false; } try { Thread.sleep(_timer); } catch (InterruptedException e) { keep_running = false; logger.error(e); } } stopApp(); logger.info(" : Done"); } private void getDataMongo(){ //mongoDB logger.info("getDataMongo"); JSONArray All_ja = null; DBCollection coll = db.getCollection("WFSSDiscusMsgCollection"); DBCursor cursor = coll.find(); // int i = 0; try { while(cursor.hasNext()) { // System.out.println(cursor.next()); //array object try { // logger.info(i+". "+cursor.next().get("data")); // i++; if(!JSONUtils.isValid(""+cursor.next().get("data"))){ logger.error("colom data bukan json string: "+cursor.next().get("data").toString()); } else{ //merge string try { JSONParser parser = new JSONParser(); Object obj = parser.parse(""+cursor.next().get("data")); JSONArray ja = (JSONArray) obj; logger.info("array length: "+ja.size()); // logger.info("data: "+cursor.next().get("data").toString()); for (int i = 0; i < ja.size(); i++) { logger.info(ja.get(i)); // destinationArray.put(sourceArray.getJSONObject(i)); } // result.put("poin", ja); } catch (ParseException e1) { // e1.printStackTrace(); logger.error(""+ e1.getMessage()); for (StackTraceElement se: e1.getStackTrace()) { logger.error(" at "+ se); } } } } catch (Exception e) { logger.error("colom data tidak ada. e:"+e.getMessage()); for (StackTraceElement se: e.getStackTrace()) { logger.error(" at "+ se); } } //delete row } } finally { cursor.close(); } //HIT and send data to apps2 } private void getData(){ //protected String query = "select * from WF_QUEUE_SENDSMS where rownum < "; //protected String query1 = "delete WF_QUEUE_SENDSMS where MSGID = ?"; JavaFileObject jObj = null; String q_WF_QUEUE_SENDSMS = "select msgid, msisdn,msgtxt, delay, expiration,corrid, enq_uid, deq_time, " + "enq_time, priority, status, q_name, sender from WF_QUEUE_SENDSMS where rownum <" + _max_row_num; String del_WF_QUEUE_SENDSMS = "delete WF_QUEUE_SENDSMS where MSGID = ?"; java.sql.Connection conn = null; Statement st = null; ResultSet rs = null; PreparedStatement ps = null; Vector<Long> sms_sents = new Vector<Long>(); // logger.info("GET DATA FROM NODE JS"); String _line_ = ""; // _line_ = "https://192.168.137.1:8000/puller"; // _line_ = "http://mmm2-opedio.rhcloud.com/puller"; _line_ = "http://oksipyoucansmsboxto9116-as10009116.rhcloud.com/puller?uname=jboss&pass=jboss123"; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = null; CloseableHttpResponse response1 = null; try { // httpGet = new HttpGet("http://targethost/homepage"); logger.debug("HIT "+_line_); httpGet = new HttpGet(_line_); start_time = System.currentTimeMillis(); // logger.info(" HIT "+_line_); // logger.debug(" HIT start_time="+start_time+" url:"+_line_); response1 = httpclient.execute(httpGet); HttpEntity entity1 = response1.getEntity(); String responseString = EntityUtils.toString(entity1, "UTF-8"); end_time = System.currentTimeMillis(); dif_time = end_time - start_time; float elapse = (end_time - start_time) / 1000f; // logger.debug(" start_time="+start_time+" end_time="+end_time+" dif="+dif_time+" elapse="+elapse+" resp = "+ response1.getStatusLine()+" json="+responseString); // JSONObject obj = new JSONObject(); JSONParser parser=new JSONParser(); Object obj = parser.parse(responseString); JSONArray array = (JSONArray)obj; for (int i = 0; i < array.toArray().length; i++) { JSONObject obj2 = (JSONObject)array.get(i); logger.debug("msgtxt: "+obj2.get("MSGTXT")); logger.debug("msisdn: "+obj2.get("MSISDN")); long _msg_id = TselpoinIDGenerator.getNextTselpoinID(); WFSendSmsQueue sms = new WFSendSmsQueue(); // sms.set_msgid(Long.parseLong(""+obj2.get("MSGID"))); sms.set_msgid(_msg_id); sms.set_msisdn(""+obj2.get("MSISDN")); sms.set_msgtxt(""+obj2.get("MSGTXT")); // sms.set_delay(rs.getInt(4)); // sms.set_expiration(rs.getInt(5)); // sms.set_corrid(rs.getString(6)); // sms.set_enqueue_uid(rs.getInt(7)); // sms.set_dequeue_time(rs.getDate(8)); // sms.set_enqueue_time(rs.getDate(9)); // sms.set_priority(rs.getInt(10)); sms.set_status(""+obj2.get("STATUS")); sms.set_q_name(""+obj2.get("Q_NAME")); // sms.set_sender("777"); logger.debug("send to queue"); _sms_queue.put(sms); // sms_sents.add(Long.parseLong(""+obj2.get("MSGID"))); } // JSONObject jsonObj = new JSONObject(responseString); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } catch (ClientProtocolException e) { /* Multiple markers at this line - Unhandled exception type ClientProtocolException - Unhandled exception type IOException - Resource leak: 'response1' is not closed at this location */ logger.error("ClientProtocolException, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } catch (IOException e) { logger.error("IOException, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } catch (Exception e) { logger.error("Exception, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } finally { try { response1.close(); } catch (IOException e) {} } // processing(null); // try { // // conn = ds.getConnection(); // st = conn.createStatement(); // // rs = st.executeQuery(q_WF_QUEUE_SENDSMS); //gjhgjg // // while (rs.next()) { // // WFSendSmsQueue sms = new WFSendSmsQueue(); // // sms.set_msgid(rs.getInt(1)); // sms.set_msisdn(rs.getString(2)); // sms.set_msgtxt(rs.getString(3)); // // sms.set_delay(rs.getInt(4)); // sms.set_expiration(rs.getInt(5)); // sms.set_corrid(rs.getString(6)); // // sms.set_enqueue_uid(rs.getInt(7)); // sms.set_dequeue_time(rs.getDate(8)); // sms.set_enqueue_time(rs.getDate(9)); // // sms.set_priority(rs.getInt(10)); // sms.set_status(rs.getString(11)); // sms.set_q_name(rs.getString(12)); // sms.set_sender(rs.getString(13)); // // _sms_queue.put(sms); // // sms_sents.add(sms.get_msgid()); // // } // // ps = conn.prepareStatement(del_WF_QUEUE_SENDSMS); // // for (long msg_id: sms_sents) { // // ps.setLong(1,msg_id); // // ps.executeUpdate(); // // } // // // // } finally { // if (st != null){ try {st.close();} catch (SQLException e){} } // if (ps != null){ try {ps.close();} catch(SQLException e){} } // if (conn!=null){ try{conn.close();} catch (SQLException e) {} // } // } } private void processing(WFSendSmsQueue _send_message){ String _line_ = ""; //CallbackCDDS m = _queue.take(); // head or waiting WFSendSmsQueue m = _send_message; String adn_from = "777"; //UNTUK SMAULOOP try { if(m.get_q_name().equals("SMAULOOP")){ adn_from = "2323"; }else{ adn_from = "777"; } } catch (Exception e) { adn_from = "777"; } //text message String textmsg = ""; try { textmsg = URLEncoder.encode(m.get_msgtxt(),"UTF-8"); } catch (Exception e) { textmsg = m.get_msgtxt(); } String qName = ""; try { qName = m.get_q_name(); if(m.get_q_name().equals(null)){ qName = "DEFAULT"; } } catch (Exception e) { qName = "DEFAULT"; } _line_ = "http://192.168.137.1:3000/puller"; // _line_ = this._base_url +"?user="+this._user+"&pass="+this._pwd+"&from="+adn_from+"&to=" + m.get_msisdn() +"&text="+textmsg+"&qname="+qName; // String url_line = this._base_url+"___&from="+adn_from+"&to=" + m.get_msisdn() +"&text="+textmsg+"&qname="+qName; // _line_ = this._base_url +"?user=TPOIN&pass=mt2014&from=TPOIN&to="+ m.get_msisdn() +"&text=test"; // CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = null; CloseableHttpResponse response1 = null; // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST either fully consume the response content or abort request // execution by calling CloseableHttpResponse#close(). try { // httpGet = new HttpGet("http://targethost/homepage"); httpGet = new HttpGet(_line_); start_time = System.currentTimeMillis(); logger.debug(" HIT start_time="+start_time+" msgid="+ m.get_msgid() +"|" +m.get_msisdn() +"|enq="+m.get_enqueue_time() +"|deq=" +m.get_dequeue_time() +"|" +m.get_msgtxt()+"|adn:"+adn_from+" q:"+m.get_q_name()+" url:"+_line_); response1 = httpclient.execute(httpGet); HttpEntity entity1 = response1.getEntity(); end_time = System.currentTimeMillis(); dif_time = end_time - start_time; float elapse = (end_time - start_time) / 1000f; logger.debug("msgid = "+ m.get_msgid() +"msisdn="+m.get_msisdn()+" start_time="+start_time+" end_time="+end_time+" dif="+dif_time+" elapse="+elapse+" resp = "+ response1.getStatusLine()); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } catch (ClientProtocolException e) { /* Multiple markers at this line - Unhandled exception type ClientProtocolException - Unhandled exception type IOException - Resource leak: 'response1' is not closed at this location */ logger.error("ClientProtocolException, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } catch (IOException e) { logger.error("IOException, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } catch (Exception e) { logger.error("Exception, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } finally { try { response1.close(); } catch (IOException e) {} } } }
opetstudio/jbossas
NvSsDiscus/src/main/java/com/opedio/jboss/service/discus/DataDiscusSender.java
5,639
// httpGet = new HttpGet("http://targethost/homepage");
line_comment
nl
package com.opedio.jboss.service.discus; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.solusi247.poin.data.WFSendSmsQueue; import com.solusi247.poin.util.TselpoinIDGenerator; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.jboss.logging.Logger; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.IOException; import java.net.URLEncoder; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import javax.sql.DataSource; import javax.tools.JavaFileObject; public class DataDiscusSender extends Thread { private static Logger logger = Logger.getLogger(DataDiscusSender.class); private boolean keep_running = false; /* <jms-queue name="WFSendSmsQueue"> <entry name="queue/WFSendSmsQueue"/> <entry name="java:jboss/exported/jms/queue/WFSendSmsQueue"/> </jms-queue> <jms-queue name="WFSendSmsHisQueue"> <entry name="queue/WFSendSmsHisQueue"/> <entry name="java:jboss/exported/jms/queue/WFSendSmsHisQueue"/> </jms-queue> */ private List<PullerJMSClient>_broker = new ArrayList<PullerJMSClient>(); private int _nr_of_jms_connections = 4; private String JMS_QUEUE = "queue/WFSendSmsQueue"; private BlockingQueue<WFSendSmsQueue> _sms_queue = null; private int _max_row_num = 1000; private int _timer = 60000; private DataSource ds = null; private DB db = null; private volatile long start_time;//ms private volatile long end_time; private volatile long dif_time; public DataDiscusSender(int thread_number, int queue_size, int row_num, int timer, DataSource datasource, DB mongoDB) { if (thread_number>0) this._nr_of_jms_connections = thread_number; if (queue_size>=(2*_nr_of_jms_connections)) _sms_queue = new ArrayBlockingQueue<WFSendSmsQueue>(queue_size); else _sms_queue = new ArrayBlockingQueue<WFSendSmsQueue>(3*this._nr_of_jms_connections); if (row_num>0) this._max_row_num = row_num; if (timer>100) this._timer = timer; this.ds = datasource; this.db = mongoDB; logger.info("construct SmsSender"); } public void ophouden() { this.keep_running = false; } private void startApp() { logger.info("startApp"); // TODO /*for (int i=0;i<_nr_of_jms_connections;i++) { PullerJMSClient jj = new PullerJMSClient(JMS_QUEUE,_sms_queue); jj.start(); _broker.add(jj); }*/ } private void stopApp() { logger.info("[SmsSender] is stopping"); for (PullerJMSClient j: _broker) { try { j.ophouden(); j.interrupt(); } catch (Exception e) { logger.error("[closeJMSConnection] "+ e); for (StackTraceElement s: e.getStackTrace()) { logger.error(" at "+ s); } } } for (PullerJMSClient j: _broker) { try { if (j!=null && j.isAlive()) { j.join(); } } catch (Exception e) { logger.error("[closeJMSConnection] "+ e); for (StackTraceElement s: e.getStackTrace()) { logger.error(" at "+ s); } } } logger.info("[SmsSender] closeJMSConnection done"); } @Override public void run() { keep_running = true; startApp(); while (keep_running) { try { // getData(); getDataMongo(); // logger.info("TIMER"); } catch (Exception e) { logger.error(e); // keep_running = false; } try { Thread.sleep(_timer); } catch (InterruptedException e) { keep_running = false; logger.error(e); } } stopApp(); logger.info(" : Done"); } private void getDataMongo(){ //mongoDB logger.info("getDataMongo"); JSONArray All_ja = null; DBCollection coll = db.getCollection("WFSSDiscusMsgCollection"); DBCursor cursor = coll.find(); // int i = 0; try { while(cursor.hasNext()) { // System.out.println(cursor.next()); //array object try { // logger.info(i+". "+cursor.next().get("data")); // i++; if(!JSONUtils.isValid(""+cursor.next().get("data"))){ logger.error("colom data bukan json string: "+cursor.next().get("data").toString()); } else{ //merge string try { JSONParser parser = new JSONParser(); Object obj = parser.parse(""+cursor.next().get("data")); JSONArray ja = (JSONArray) obj; logger.info("array length: "+ja.size()); // logger.info("data: "+cursor.next().get("data").toString()); for (int i = 0; i < ja.size(); i++) { logger.info(ja.get(i)); // destinationArray.put(sourceArray.getJSONObject(i)); } // result.put("poin", ja); } catch (ParseException e1) { // e1.printStackTrace(); logger.error(""+ e1.getMessage()); for (StackTraceElement se: e1.getStackTrace()) { logger.error(" at "+ se); } } } } catch (Exception e) { logger.error("colom data tidak ada. e:"+e.getMessage()); for (StackTraceElement se: e.getStackTrace()) { logger.error(" at "+ se); } } //delete row } } finally { cursor.close(); } //HIT and send data to apps2 } private void getData(){ //protected String query = "select * from WF_QUEUE_SENDSMS where rownum < "; //protected String query1 = "delete WF_QUEUE_SENDSMS where MSGID = ?"; JavaFileObject jObj = null; String q_WF_QUEUE_SENDSMS = "select msgid, msisdn,msgtxt, delay, expiration,corrid, enq_uid, deq_time, " + "enq_time, priority, status, q_name, sender from WF_QUEUE_SENDSMS where rownum <" + _max_row_num; String del_WF_QUEUE_SENDSMS = "delete WF_QUEUE_SENDSMS where MSGID = ?"; java.sql.Connection conn = null; Statement st = null; ResultSet rs = null; PreparedStatement ps = null; Vector<Long> sms_sents = new Vector<Long>(); // logger.info("GET DATA FROM NODE JS"); String _line_ = ""; // _line_ = "https://192.168.137.1:8000/puller"; // _line_ = "http://mmm2-opedio.rhcloud.com/puller"; _line_ = "http://oksipyoucansmsboxto9116-as10009116.rhcloud.com/puller?uname=jboss&pass=jboss123"; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = null; CloseableHttpResponse response1 = null; try { // httpGet = new HttpGet("http://targethost/homepage"); logger.debug("HIT "+_line_); httpGet = new HttpGet(_line_); start_time = System.currentTimeMillis(); // logger.info(" HIT "+_line_); // logger.debug(" HIT start_time="+start_time+" url:"+_line_); response1 = httpclient.execute(httpGet); HttpEntity entity1 = response1.getEntity(); String responseString = EntityUtils.toString(entity1, "UTF-8"); end_time = System.currentTimeMillis(); dif_time = end_time - start_time; float elapse = (end_time - start_time) / 1000f; // logger.debug(" start_time="+start_time+" end_time="+end_time+" dif="+dif_time+" elapse="+elapse+" resp = "+ response1.getStatusLine()+" json="+responseString); // JSONObject obj = new JSONObject(); JSONParser parser=new JSONParser(); Object obj = parser.parse(responseString); JSONArray array = (JSONArray)obj; for (int i = 0; i < array.toArray().length; i++) { JSONObject obj2 = (JSONObject)array.get(i); logger.debug("msgtxt: "+obj2.get("MSGTXT")); logger.debug("msisdn: "+obj2.get("MSISDN")); long _msg_id = TselpoinIDGenerator.getNextTselpoinID(); WFSendSmsQueue sms = new WFSendSmsQueue(); // sms.set_msgid(Long.parseLong(""+obj2.get("MSGID"))); sms.set_msgid(_msg_id); sms.set_msisdn(""+obj2.get("MSISDN")); sms.set_msgtxt(""+obj2.get("MSGTXT")); // sms.set_delay(rs.getInt(4)); // sms.set_expiration(rs.getInt(5)); // sms.set_corrid(rs.getString(6)); // sms.set_enqueue_uid(rs.getInt(7)); // sms.set_dequeue_time(rs.getDate(8)); // sms.set_enqueue_time(rs.getDate(9)); // sms.set_priority(rs.getInt(10)); sms.set_status(""+obj2.get("STATUS")); sms.set_q_name(""+obj2.get("Q_NAME")); // sms.set_sender("777"); logger.debug("send to queue"); _sms_queue.put(sms); // sms_sents.add(Long.parseLong(""+obj2.get("MSGID"))); } // JSONObject jsonObj = new JSONObject(responseString); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } catch (ClientProtocolException e) { /* Multiple markers at this line - Unhandled exception type ClientProtocolException - Unhandled exception type IOException - Resource leak: 'response1' is not closed at this location */ logger.error("ClientProtocolException, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } catch (IOException e) { logger.error("IOException, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } catch (Exception e) { logger.error("Exception, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } finally { try { response1.close(); } catch (IOException e) {} } // processing(null); // try { // // conn = ds.getConnection(); // st = conn.createStatement(); // // rs = st.executeQuery(q_WF_QUEUE_SENDSMS); //gjhgjg // // while (rs.next()) { // // WFSendSmsQueue sms = new WFSendSmsQueue(); // // sms.set_msgid(rs.getInt(1)); // sms.set_msisdn(rs.getString(2)); // sms.set_msgtxt(rs.getString(3)); // // sms.set_delay(rs.getInt(4)); // sms.set_expiration(rs.getInt(5)); // sms.set_corrid(rs.getString(6)); // // sms.set_enqueue_uid(rs.getInt(7)); // sms.set_dequeue_time(rs.getDate(8)); // sms.set_enqueue_time(rs.getDate(9)); // // sms.set_priority(rs.getInt(10)); // sms.set_status(rs.getString(11)); // sms.set_q_name(rs.getString(12)); // sms.set_sender(rs.getString(13)); // // _sms_queue.put(sms); // // sms_sents.add(sms.get_msgid()); // // } // // ps = conn.prepareStatement(del_WF_QUEUE_SENDSMS); // // for (long msg_id: sms_sents) { // // ps.setLong(1,msg_id); // // ps.executeUpdate(); // // } // // // // } finally { // if (st != null){ try {st.close();} catch (SQLException e){} } // if (ps != null){ try {ps.close();} catch(SQLException e){} } // if (conn!=null){ try{conn.close();} catch (SQLException e) {} // } // } } private void processing(WFSendSmsQueue _send_message){ String _line_ = ""; //CallbackCDDS m = _queue.take(); // head or waiting WFSendSmsQueue m = _send_message; String adn_from = "777"; //UNTUK SMAULOOP try { if(m.get_q_name().equals("SMAULOOP")){ adn_from = "2323"; }else{ adn_from = "777"; } } catch (Exception e) { adn_from = "777"; } //text message String textmsg = ""; try { textmsg = URLEncoder.encode(m.get_msgtxt(),"UTF-8"); } catch (Exception e) { textmsg = m.get_msgtxt(); } String qName = ""; try { qName = m.get_q_name(); if(m.get_q_name().equals(null)){ qName = "DEFAULT"; } } catch (Exception e) { qName = "DEFAULT"; } _line_ = "http://192.168.137.1:3000/puller"; // _line_ = this._base_url +"?user="+this._user+"&pass="+this._pwd+"&from="+adn_from+"&to=" + m.get_msisdn() +"&text="+textmsg+"&qname="+qName; // String url_line = this._base_url+"___&from="+adn_from+"&to=" + m.get_msisdn() +"&text="+textmsg+"&qname="+qName; // _line_ = this._base_url +"?user=TPOIN&pass=mt2014&from=TPOIN&to="+ m.get_msisdn() +"&text=test"; // CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = null; CloseableHttpResponse response1 = null; // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST either fully consume the response content or abort request // execution by calling CloseableHttpResponse#close(). try { // httpGet =<SUF> httpGet = new HttpGet(_line_); start_time = System.currentTimeMillis(); logger.debug(" HIT start_time="+start_time+" msgid="+ m.get_msgid() +"|" +m.get_msisdn() +"|enq="+m.get_enqueue_time() +"|deq=" +m.get_dequeue_time() +"|" +m.get_msgtxt()+"|adn:"+adn_from+" q:"+m.get_q_name()+" url:"+_line_); response1 = httpclient.execute(httpGet); HttpEntity entity1 = response1.getEntity(); end_time = System.currentTimeMillis(); dif_time = end_time - start_time; float elapse = (end_time - start_time) / 1000f; logger.debug("msgid = "+ m.get_msgid() +"msisdn="+m.get_msisdn()+" start_time="+start_time+" end_time="+end_time+" dif="+dif_time+" elapse="+elapse+" resp = "+ response1.getStatusLine()); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } catch (ClientProtocolException e) { /* Multiple markers at this line - Unhandled exception type ClientProtocolException - Unhandled exception type IOException - Resource leak: 'response1' is not closed at this location */ logger.error("ClientProtocolException, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } catch (IOException e) { logger.error("IOException, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } catch (Exception e) { logger.error("Exception, "+ e); // for (StackTraceElement s: e.getStackTrace()) { // logger.error(" at "+ s); // } } finally { try { response1.close(); } catch (IOException e) {} } } }
180219_1
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import oracle.ucp.admin.UniversalConnectionPoolManagerImpl; import oracle.ucp.jdbc.PoolDataSource; /** * Servlet implementation class UCPServlet */ @WebServlet("/UCPServlet") public class UCPServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UCPServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Servlet to test ATP using UCP"); Connection conn = null; try { // Get a context for the JNDI look up PoolDataSource pds = getPoolInstance(); conn = pds.getConnection(); // Prepare a statement to execute the SQL Queries. Statement statement = conn.createStatement(); // Create table EMP statement.executeUpdate("create table EMP(EMPLOYEEID NUMBER," + "EMPLOYEENAME VARCHAR2 (20))"); out.println("New table EMP is created"); // Insert some records into the table EMP statement.executeUpdate("insert into EMP values(1, 'Jennifer Jones')"); statement.executeUpdate("insert into EMP values(2, 'Alex Debouir')"); out.println("Two records are inserted."); // Update a record on EMP table. statement.executeUpdate("update EMP set EMPLOYEENAME='Alex Deborie'" + " where EMPLOYEEID=2"); out.println("One record is updated."); // Verify the table EMP ResultSet resultSet = statement.executeQuery("select * from EMP"); out.println("\nNew table EMP contains:"); out.println("EMPLOYEEID" + " " + "EMPLOYEENAME"); out.println("--------------------------"); while (resultSet.next()) { out.println(resultSet.getInt(1) + " " + resultSet.getString(2)); } out.println("\nSuccessfully tested a connection to ATP using UCP"); } catch (Exception e) { response.setStatus(500); response.setHeader("Exception", e.toString()); out.print("\n Web Request failed"); out.print("\n "+e.toString()); e.printStackTrace(); } finally { // Clean-up after everything try (Statement statement = conn.createStatement()) { statement.execute("drop table EMP"); conn.close(); } catch (SQLException e) { System.out.println("UCPServlet - " + "doSQLWork()- SQLException occurred : " + e.getMessage()); } } } /* Get the appropriate datasource */ private PoolDataSource getPoolInstance() throws NamingException { Context ctx; ctx = new InitialContext(); Context envContext = (Context) ctx.lookup("java:/comp/env"); // Look up a data source javax.sql.DataSource ds = (javax.sql.DataSource) envContext.lookup ("tomcat/UCP_atp"); PoolDataSource pds=(PoolDataSource)ds; return pds; } public void destroy() { try { UniversalConnectionPoolManagerImpl.getUniversalConnectionPoolManager() .destroyConnectionPool(getPoolInstance().getConnectionPoolName()); System.out.println("Pool Destroyed"); } catch (Exception e) { System.out.println("destroy pool got Exception:"); e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
oracle-samples/oracle-db-examples
java/jdbc/Tomcat_Servlet/src/UCPServlet.java
1,220
/** * @see HttpServlet#HttpServlet() */
block_comment
nl
import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import oracle.ucp.admin.UniversalConnectionPoolManagerImpl; import oracle.ucp.jdbc.PoolDataSource; /** * Servlet implementation class UCPServlet */ @WebServlet("/UCPServlet") public class UCPServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() <SUF>*/ public UCPServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Servlet to test ATP using UCP"); Connection conn = null; try { // Get a context for the JNDI look up PoolDataSource pds = getPoolInstance(); conn = pds.getConnection(); // Prepare a statement to execute the SQL Queries. Statement statement = conn.createStatement(); // Create table EMP statement.executeUpdate("create table EMP(EMPLOYEEID NUMBER," + "EMPLOYEENAME VARCHAR2 (20))"); out.println("New table EMP is created"); // Insert some records into the table EMP statement.executeUpdate("insert into EMP values(1, 'Jennifer Jones')"); statement.executeUpdate("insert into EMP values(2, 'Alex Debouir')"); out.println("Two records are inserted."); // Update a record on EMP table. statement.executeUpdate("update EMP set EMPLOYEENAME='Alex Deborie'" + " where EMPLOYEEID=2"); out.println("One record is updated."); // Verify the table EMP ResultSet resultSet = statement.executeQuery("select * from EMP"); out.println("\nNew table EMP contains:"); out.println("EMPLOYEEID" + " " + "EMPLOYEENAME"); out.println("--------------------------"); while (resultSet.next()) { out.println(resultSet.getInt(1) + " " + resultSet.getString(2)); } out.println("\nSuccessfully tested a connection to ATP using UCP"); } catch (Exception e) { response.setStatus(500); response.setHeader("Exception", e.toString()); out.print("\n Web Request failed"); out.print("\n "+e.toString()); e.printStackTrace(); } finally { // Clean-up after everything try (Statement statement = conn.createStatement()) { statement.execute("drop table EMP"); conn.close(); } catch (SQLException e) { System.out.println("UCPServlet - " + "doSQLWork()- SQLException occurred : " + e.getMessage()); } } } /* Get the appropriate datasource */ private PoolDataSource getPoolInstance() throws NamingException { Context ctx; ctx = new InitialContext(); Context envContext = (Context) ctx.lookup("java:/comp/env"); // Look up a data source javax.sql.DataSource ds = (javax.sql.DataSource) envContext.lookup ("tomcat/UCP_atp"); PoolDataSource pds=(PoolDataSource)ds; return pds; } public void destroy() { try { UniversalConnectionPoolManagerImpl.getUniversalConnectionPoolManager() .destroyConnectionPool(getPoolInstance().getConnectionPoolName()); System.out.println("Pool Destroyed"); } catch (Exception e) { System.out.println("destroy pool got Exception:"); e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
181129_12
/* * Copyright (c) 2024, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl. */ package com.tangosol.util.asm; import com.oracle.coherence.common.base.Logger; import java.io.IOException; import java.io.InputStream; /** * Base class for internal wrappers of ASM's ClassReader. * * @param <RT> the ClassReader type * @param <CVT> the ClassVisitor type * * @since 15.1.1.0 */ public abstract class BaseClassReaderInternal<RT, CVT> { // ----- constructors --------------------------------------------------- /** * @see org.objectweb.asm.ClassReader#ClassReader(InputStream) */ public BaseClassReaderInternal(InputStream streamIn) throws IOException { this(streamIn.readAllBytes()); } /** * @see org.objectweb.asm.ClassReader#ClassReader(byte[]) */ public BaseClassReaderInternal(byte[] abBytes) { m_abBytes = abBytes; } // ----- abstract methods ----------------------------------------------- /** * Create the module-specific ClassReader. * * @param abBytes the class bytes * * @return the module-specific ClassReader */ protected abstract RT createReader(byte[] abBytes); /** * Perform the accept operation on the module-specific ClassReader * * @param classReader the module-specific ClassReader * @param classVisitor the module-specific ClassVisitor * @param nParsingOptions the parsing options */ protected abstract void accept(RT classReader, CVT classVisitor, int nParsingOptions); // ----- api methods ---------------------------------------------------- /** * Makes the given visitor visit the Java Virtual Machine's class file * structure passed to the constructor of this {@code ClassReader}. * * @param classVisitor the visitor that must visit this class * @param nParsingOptions the options to use to parse this class * * @see org.objectweb.asm.ClassReader#accept(org.objectweb.asm.ClassVisitor, int) */ @SuppressWarnings("DuplicatedCode") public void accept(CVT classVisitor, int nParsingOptions) { byte[] abBytes = m_abBytes; int nOriginalVersion = getMajorVersion(abBytes); boolean fRevertVersion = false; if (nOriginalVersion > MAX_MAJOR_VERSION) { // temporarily downgrade version to bypass check in ASM setMajorVersion(MAX_MAJOR_VERSION, abBytes); fRevertVersion = true; Logger.warn(() -> String.format("Unsupported class file major version " + nOriginalVersion)); } RT classReader = createReader(abBytes); if (fRevertVersion) { // set version back setMajorVersion(nOriginalVersion, abBytes); } accept(classReader, classVisitor, nParsingOptions); } // ----- helper methods ------------------------------------------------- /** * Sets the major version number in given class bytes. * * @param nMajorVersion major version of bytecode to set * @param abBytes class bytes * * @see #getMajorVersion(byte[]) */ protected static void setMajorVersion(final int nMajorVersion, final byte[] abBytes) { abBytes[6] = (byte) (nMajorVersion >>> 8); abBytes[7] = (byte) nMajorVersion; } /** * Gets major version number from the given class bytes. * * @param abBytes class bytes * * @return the major version of bytecode */ protected static int getMajorVersion(final byte[] abBytes) { return ((abBytes[6] & 0xFF) << 8) | (abBytes[7] & 0xFF); } // ----- constants ------------------------------------------------------ /** * The max major version supported by the shaded ASM. */ /* * Implementation Note: This doesn't reference the constant to avoid * strange issues with moditect */ private static final int MAX_MAJOR_VERSION = 66; // Opcodes.V22 // ----- data members --------------------------------------------------- /** * The class bytes. */ protected byte[] m_abBytes; }
oracle/coherence
prj/coherence-core/src/main/java/com/tangosol/util/asm/BaseClassReaderInternal.java
1,199
// ----- helper methods -------------------------------------------------
line_comment
nl
/* * Copyright (c) 2024, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl. */ package com.tangosol.util.asm; import com.oracle.coherence.common.base.Logger; import java.io.IOException; import java.io.InputStream; /** * Base class for internal wrappers of ASM's ClassReader. * * @param <RT> the ClassReader type * @param <CVT> the ClassVisitor type * * @since 15.1.1.0 */ public abstract class BaseClassReaderInternal<RT, CVT> { // ----- constructors --------------------------------------------------- /** * @see org.objectweb.asm.ClassReader#ClassReader(InputStream) */ public BaseClassReaderInternal(InputStream streamIn) throws IOException { this(streamIn.readAllBytes()); } /** * @see org.objectweb.asm.ClassReader#ClassReader(byte[]) */ public BaseClassReaderInternal(byte[] abBytes) { m_abBytes = abBytes; } // ----- abstract methods ----------------------------------------------- /** * Create the module-specific ClassReader. * * @param abBytes the class bytes * * @return the module-specific ClassReader */ protected abstract RT createReader(byte[] abBytes); /** * Perform the accept operation on the module-specific ClassReader * * @param classReader the module-specific ClassReader * @param classVisitor the module-specific ClassVisitor * @param nParsingOptions the parsing options */ protected abstract void accept(RT classReader, CVT classVisitor, int nParsingOptions); // ----- api methods ---------------------------------------------------- /** * Makes the given visitor visit the Java Virtual Machine's class file * structure passed to the constructor of this {@code ClassReader}. * * @param classVisitor the visitor that must visit this class * @param nParsingOptions the options to use to parse this class * * @see org.objectweb.asm.ClassReader#accept(org.objectweb.asm.ClassVisitor, int) */ @SuppressWarnings("DuplicatedCode") public void accept(CVT classVisitor, int nParsingOptions) { byte[] abBytes = m_abBytes; int nOriginalVersion = getMajorVersion(abBytes); boolean fRevertVersion = false; if (nOriginalVersion > MAX_MAJOR_VERSION) { // temporarily downgrade version to bypass check in ASM setMajorVersion(MAX_MAJOR_VERSION, abBytes); fRevertVersion = true; Logger.warn(() -> String.format("Unsupported class file major version " + nOriginalVersion)); } RT classReader = createReader(abBytes); if (fRevertVersion) { // set version back setMajorVersion(nOriginalVersion, abBytes); } accept(classReader, classVisitor, nParsingOptions); } // ----- helper<SUF> /** * Sets the major version number in given class bytes. * * @param nMajorVersion major version of bytecode to set * @param abBytes class bytes * * @see #getMajorVersion(byte[]) */ protected static void setMajorVersion(final int nMajorVersion, final byte[] abBytes) { abBytes[6] = (byte) (nMajorVersion >>> 8); abBytes[7] = (byte) nMajorVersion; } /** * Gets major version number from the given class bytes. * * @param abBytes class bytes * * @return the major version of bytecode */ protected static int getMajorVersion(final byte[] abBytes) { return ((abBytes[6] & 0xFF) << 8) | (abBytes[7] & 0xFF); } // ----- constants ------------------------------------------------------ /** * The max major version supported by the shaded ASM. */ /* * Implementation Note: This doesn't reference the constant to avoid * strange issues with moditect */ private static final int MAX_MAJOR_VERSION = 66; // Opcodes.V22 // ----- data members --------------------------------------------------- /** * The class bytes. */ protected byte[] m_abBytes; }
51388_7
/* * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.graal.compiler.lir.amd64; import static jdk.vm.ci.amd64.AMD64Kind.QWORD; import static jdk.vm.ci.code.ValueUtil.asRegister; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexMRIOp.VEXTRACTI128; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexMoveOp.VMOVDQU32; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPBROADCASTD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXBD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXBQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXBW; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXDQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXWD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXWQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXBD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXBQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXBW; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXDQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXWD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXWQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRVMOp.VPADDB; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRVMOp.VPADDD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRVMOp.VPADDW; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRVMOp.VPHADDD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRVMOp.VPMULLD; import static jdk.graal.compiler.asm.amd64.AVXKind.AVXSize.XMM; import static jdk.graal.compiler.asm.amd64.AVXKind.AVXSize.YMM; import static jdk.graal.compiler.asm.amd64.AVXKind.AVXSize.ZMM; import static jdk.graal.compiler.lir.amd64.AMD64LIRHelper.pointerConstant; import static jdk.graal.compiler.lir.amd64.AMD64LIRHelper.recordExternalAddress; import java.util.EnumSet; import jdk.graal.compiler.asm.Label; import jdk.graal.compiler.asm.amd64.AMD64Address; import jdk.graal.compiler.asm.amd64.AMD64Assembler.ConditionFlag; import jdk.graal.compiler.asm.amd64.AMD64MacroAssembler; import jdk.graal.compiler.asm.amd64.AVXKind; import jdk.graal.compiler.core.common.Stride; import jdk.graal.compiler.debug.GraalError; import jdk.graal.compiler.lir.LIRInstructionClass; import jdk.graal.compiler.lir.Opcode; import jdk.graal.compiler.lir.SyncPort; import jdk.graal.compiler.lir.asm.ArrayDataPointerConstant; import jdk.graal.compiler.lir.asm.CompilationResultBuilder; import jdk.graal.compiler.lir.gen.LIRGeneratorTool; import jdk.vm.ci.amd64.AMD64.CPUFeature; import jdk.vm.ci.code.Register; import jdk.vm.ci.meta.AllocatableValue; import jdk.vm.ci.meta.JavaKind; import jdk.vm.ci.meta.Value; // @formatter:off @SyncPort(from = "https://github.com/openjdk/jdk/blob/7bb59dc8da0c61c5da5c3aab5d56a6e4880001ce/src/hotspot/cpu/x86/c2_MacroAssembler_x86.cpp#L2095-L2194", sha1 = "a93850c44f7e34fcec05226bae95fd695b2ea2f7") @SyncPort(from = "https://github.com/openjdk/jdk/blob/7bb59dc8da0c61c5da5c3aab5d56a6e4880001ce/src/hotspot/cpu/x86/c2_MacroAssembler_x86.cpp#L2316-L2362", sha1 = "9cbba8bd6c4037427fa46f067abb722b15aca90c") @SyncPort(from = "https://github.com/openjdk/jdk/blob/7bb59dc8da0c61c5da5c3aab5d56a6e4880001ce/src/hotspot/cpu/x86/c2_MacroAssembler_x86.cpp#L3634-L3821", sha1 = "2457cf3f9d3ff89c1515fa5d95cc7c8437a5318b") // @formatter:on @Opcode("VECTORIZED_HASHCODE") public final class AMD64VectorizedHashCodeOp extends AMD64ComplexVectorOp { public static final LIRInstructionClass<AMD64VectorizedHashCodeOp> TYPE = LIRInstructionClass.create(AMD64VectorizedHashCodeOp.class); @Def({OperandFlag.REG}) private Value resultValue; @Alive({OperandFlag.REG}) private Value arrayStart; @Alive({OperandFlag.REG}) private Value length; @Alive({OperandFlag.REG}) private Value initialValue; private final JavaKind arrayKind; @Temp({OperandFlag.REG}) Value[] temp; @Temp({OperandFlag.REG}) Value[] vectorTemp; public AMD64VectorizedHashCodeOp(LIRGeneratorTool tool, EnumSet<CPUFeature> runtimeCheckedCPUFeatures, AllocatableValue result, AllocatableValue arrayStart, AllocatableValue length, AllocatableValue initialValue, JavaKind arrayKind) { super(TYPE, tool, runtimeCheckedCPUFeatures, YMM); this.resultValue = result; this.arrayStart = arrayStart; this.length = length; this.initialValue = initialValue; this.arrayKind = arrayKind; this.temp = allocateTempRegisters(tool, QWORD, 5); this.vectorTemp = allocateVectorRegisters(tool, JavaKind.Byte, 13); } private static void arraysHashcodeElload(AMD64MacroAssembler masm, Register dst, AMD64Address src, JavaKind eltype) { switch (eltype) { case Boolean -> masm.movzbl(dst, src); case Byte -> masm.movsbl(dst, src); case Short -> masm.movswl(dst, src); case Char -> masm.movzwl(dst, src); case Int -> masm.movl(dst, src); default -> throw GraalError.shouldNotReachHere("Unsupported JavaKind " + eltype); } } private static void vectorUnsignedCast(AMD64MacroAssembler masm, Register dst, Register src, AVXKind.AVXSize avxSize, JavaKind fromElemBt, JavaKind toElemBt) { switch (fromElemBt) { case Byte -> { switch (toElemBt) { case Short -> masm.emit(VPMOVZXBW, dst, src, avxSize); case Int -> masm.emit(VPMOVZXBD, dst, src, avxSize); case Long -> masm.emit(VPMOVZXBQ, dst, src, avxSize); default -> throw GraalError.shouldNotReachHere("Unsupported unsigned vector cast from " + fromElemBt + " to " + toElemBt); } } case Short -> { switch (toElemBt) { case Int -> masm.emit(VPMOVZXWD, dst, src, avxSize); case Long -> masm.emit(VPMOVZXWQ, dst, src, avxSize); default -> throw GraalError.shouldNotReachHere("Unsupported unsigned vector cast from " + fromElemBt + " to " + toElemBt); } } case Int -> { GraalError.guarantee(toElemBt == JavaKind.Long, "Unsupported unsigned vector cast from %s to %s", fromElemBt, toElemBt); masm.emit(VPMOVZXDQ, dst, src, avxSize); } default -> throw GraalError.shouldNotReachHere("Unsupported unsigned vector cast from " + fromElemBt + " to " + toElemBt); } } private static void vectorSignedCast(AMD64MacroAssembler masm, Register dst, Register src, AVXKind.AVXSize avxSize, JavaKind fromElemBt, JavaKind toElemBt) { switch (fromElemBt) { case Byte -> { switch (toElemBt) { case Short -> masm.emit(VPMOVSXBW, dst, src, avxSize); case Int -> masm.emit(VPMOVSXBD, dst, src, avxSize); case Long -> masm.emit(VPMOVSXBQ, dst, src, avxSize); default -> throw GraalError.shouldNotReachHere("Unsupported signed vector cast from " + fromElemBt + " to " + toElemBt); } } case Short -> { switch (toElemBt) { case Int -> masm.emit(VPMOVSXWD, dst, src, avxSize); case Long -> masm.emit(VPMOVSXWQ, dst, src, avxSize); default -> throw GraalError.shouldNotReachHere("Unsupported signed vector cast from " + fromElemBt + " to " + toElemBt); } } case Int -> { GraalError.guarantee(toElemBt == JavaKind.Long, "Unsupported signed vector cast from %s to %s", fromElemBt, toElemBt); masm.emit(VPMOVSXDQ, dst, src, avxSize); } default -> throw GraalError.shouldNotReachHere("Unsupported signed vector cast from " + fromElemBt + " to " + toElemBt); } } private static void arraysHashcodeElvcast(AMD64MacroAssembler masm, Register dst, JavaKind eltype) { switch (eltype) { case Boolean -> vectorUnsignedCast(masm, dst, dst, YMM, JavaKind.Byte, JavaKind.Int); case Byte -> vectorSignedCast(masm, dst, dst, YMM, JavaKind.Byte, JavaKind.Int); case Short -> vectorSignedCast(masm, dst, dst, YMM, JavaKind.Short, JavaKind.Int); case Char -> vectorUnsignedCast(masm, dst, dst, YMM, JavaKind.Short, JavaKind.Int); case Int -> { // do nothing } default -> throw GraalError.shouldNotReachHere("Unsupported vector cast from " + eltype); } } private static void loadVector(AMD64MacroAssembler masm, Register dst, AMD64Address src, int vlenInBytes) { switch (vlenInBytes) { case 4 -> masm.movdl(dst, src); case 8 -> masm.movq(dst, src); case 16 -> masm.movdqu(dst, src); case 32 -> masm.vmovdqu(dst, src); case 64 -> masm.emit(VMOVDQU32, dst, src, ZMM); default -> throw GraalError.shouldNotReachHere("Unsupported vector load of size " + vlenInBytes); } } // we only port Op_AddReductionVI-related code private static void reduce(AMD64MacroAssembler masm, AVXKind.AVXSize avxSize, JavaKind eleType, Register dst, Register src1, Register src2) { switch (eleType) { case Byte -> masm.emit(VPADDB, dst, src1, src2, avxSize); case Short -> masm.emit(VPADDW, dst, src1, src2, avxSize); case Int -> masm.emit(VPADDD, dst, src1, src2, avxSize); default -> throw GraalError.shouldNotReachHere("Unsupported reduce type " + eleType); } } private static void reduce2I(AMD64MacroAssembler masm, Register dst, Register src1, Register src2, Register vtmp1, Register vtmp2) { if (vtmp1.equals(src2)) { masm.movdqu(vtmp1, src2); } masm.emit(VPHADDD, vtmp1, vtmp1, vtmp1, XMM); masm.movdl(vtmp2, src1); reduce(masm, XMM, JavaKind.Int, vtmp1, vtmp1, vtmp2); masm.movdl(dst, vtmp1); } private static void reduce4I(AMD64MacroAssembler masm, Register dst, Register src1, Register src2, Register vtmp1, Register vtmp2) { if (vtmp1.equals(src2)) { masm.movdqu(vtmp1, src2); } masm.emit(VPHADDD, vtmp1, vtmp1, src2, XMM); reduce2I(masm, dst, src1, vtmp1, vtmp1, vtmp2); } private static void reduce8I(AMD64MacroAssembler masm, Register dst, Register src1, Register src2, Register vtmp1, Register vtmp2) { masm.emit(VPHADDD, vtmp1, src2, src2, YMM); masm.emit(VEXTRACTI128, vtmp2, vtmp1, 1, YMM); masm.emit(VPADDD, vtmp1, vtmp1, vtmp2, YMM); reduce2I(masm, dst, src1, vtmp1, vtmp1, vtmp2); } private static void reduceI(AMD64MacroAssembler masm, int vlen, Register dst, Register src1, Register src2, Register vtmp1, Register vtmp2) { switch (vlen) { case 2 -> reduce2I(masm, dst, src1, src2, vtmp1, vtmp2); case 4 -> reduce4I(masm, dst, src1, src2, vtmp1, vtmp2); case 8 -> reduce8I(masm, dst, src1, src2, vtmp1, vtmp2); default -> throw GraalError.shouldNotReachHere("Unsupported vector length " + vlen); } } private static ArrayDataPointerConstant powersOf31 = pointerConstant(16, new int[]{ 2111290369, -2010103841, 350799937, 11316127, 693101697, -254736545, 961614017, 31019807, -2077209343, -67006753, 1244764481, -2038056289, 211350913, -408824225, -844471871, -997072353, 1353309697, -510534177, 1507551809, -505558625, -293403007, 129082719, -1796951359, -196513505, -1807454463, 1742810335, 887503681, 28629151, 923521, 29791, 961, 31, 1, }); @Override public void emitCode(CompilationResultBuilder crb, AMD64MacroAssembler masm) { Label labelShortUnrolledBegin = new Label(); Label labelShortUnrolledLoopBegin = new Label(); Label labelShortUnrolledLoopExit = new Label(); Label labelUnrolledVectorLoopBegin = new Label(); Label labelEnd = new Label(); Register result = asRegister(resultValue); Register ary1 = asRegister(temp[0]); Register cnt1 = asRegister(temp[1]); Register tmp2 = asRegister(temp[2]); Register tmp3 = asRegister(temp[3]); Register index = asRegister(temp[4]); masm.movq(ary1, asRegister(arrayStart)); masm.movl(cnt1, asRegister(length)); masm.movl(result, asRegister(initialValue)); // For "renaming" for readability of the code Register vnext = asRegister(vectorTemp[0]); Register[] vcoef = {asRegister(vectorTemp[1]), asRegister(vectorTemp[2]), asRegister(vectorTemp[3]), asRegister(vectorTemp[4])}; Register[] vresult = {asRegister(vectorTemp[5]), asRegister(vectorTemp[6]), asRegister(vectorTemp[7]), asRegister(vectorTemp[8])}; Register[] vtmp = {asRegister(vectorTemp[9]), asRegister(vectorTemp[10]), asRegister(vectorTemp[11]), asRegister(vectorTemp[12])}; Stride stride = Stride.fromJavaKind(arrayKind); int elsize = arrayKind.getByteCount(); // @formatter:off // if (cnt1 >= 2) { // if (cnt1 >= 32) { // UNROLLED VECTOR LOOP // } // UNROLLED SCALAR LOOP // } // SINGLE SCALAR // @formatter:on masm.cmplAndJcc(cnt1, 32, ConditionFlag.Less, labelShortUnrolledBegin, false); // cnt1 >= 32 && generate_vectorized_loop masm.xorl(index, index); // vresult = IntVector.zero(I256); for (int idx = 0; idx < 4; idx++) { masm.vpxor(vresult[idx], vresult[idx], vresult[idx], YMM); } // vnext = IntVector.broadcast(I256, power_of_31_backwards[0]); Register bound = tmp2; Register next = tmp3; masm.leaq(tmp2, recordExternalAddress(crb, powersOf31)); masm.movl(next, new AMD64Address(tmp2)); masm.movdl(vnext, next); masm.emit(VPBROADCASTD, vnext, vnext, YMM); // index = 0; // bound = cnt1 & ~(32 - 1); masm.movl(bound, cnt1); masm.andl(bound, ~(32 - 1)); // for (; index < bound; index += 32) { masm.bind(labelUnrolledVectorLoopBegin); // result *= next; masm.imull(result, next); /* * Load the next 32 data elements into 4 vector registers. By grouping the loads and * fetching from memory up front (loop fission), out-of-order execution can hopefully do a * better job of prefetching, while also allowing subsequent instructions to be executed * while data are still being fetched. */ for (int idx = 0; idx < 4; idx++) { loadVector(masm, vtmp[idx], new AMD64Address(ary1, index, stride, 8 * idx * elsize), elsize * 8); } // vresult = vresult * vnext + ary1[index+8*idx:index+8*idx+7]; for (int idx = 0; idx < 4; idx++) { masm.emit(VPMULLD, vresult[idx], vresult[idx], vnext, YMM); arraysHashcodeElvcast(masm, vtmp[idx], arrayKind); masm.emit(VPADDD, vresult[idx], vresult[idx], vtmp[idx], YMM); } // index += 32; masm.addl(index, 32); // index < bound; masm.cmplAndJcc(index, bound, ConditionFlag.Less, labelUnrolledVectorLoopBegin, false); // } masm.leaq(ary1, new AMD64Address(ary1, bound, stride)); masm.subl(cnt1, bound); // release bound // vresult *= IntVector.fromArray(I256, power_of_31_backwards, 1); masm.leaq(tmp2, recordExternalAddress(crb, powersOf31)); for (int idx = 0; idx < 4; idx++) { loadVector(masm, vcoef[idx], new AMD64Address(tmp2, 0x04 + idx * JavaKind.Int.getByteCount() * 8), JavaKind.Int.getByteCount() * 8); masm.emit(VPMULLD, vresult[idx], vresult[idx], vcoef[idx], YMM); } // result += vresult.reduceLanes(ADD); for (int idx = 0; idx < 4; idx++) { reduceI(masm, YMM.getBytes() / JavaKind.Int.getByteCount(), result, result, vresult[idx], vtmp[(idx * 2 + 0) % 4], vtmp[(idx * 2 + 1) % 4]); } // } else if (cnt1 < 32) { masm.bind(labelShortUnrolledBegin); // int i = 1; masm.movl(index, 1); masm.cmplAndJcc(index, cnt1, ConditionFlag.GreaterEqual, labelShortUnrolledLoopExit, false); // for (; i < cnt1 ; i += 2) { masm.bind(labelShortUnrolledLoopBegin); masm.movl(tmp3, 961); masm.imull(result, tmp3); arraysHashcodeElload(masm, tmp2, new AMD64Address(ary1, index, stride, -elsize), arrayKind); masm.movl(tmp3, tmp2); masm.shll(tmp3, 5); masm.subl(tmp3, tmp2); masm.addl(result, tmp3); arraysHashcodeElload(masm, tmp3, new AMD64Address(ary1, index, stride), arrayKind); masm.addl(result, tmp3); masm.addl(index, 2); masm.cmplAndJcc(index, cnt1, ConditionFlag.Less, labelShortUnrolledLoopBegin, false); // } // if (i >= cnt1) { masm.bind(labelShortUnrolledLoopExit); masm.jccb(ConditionFlag.Greater, labelEnd); masm.movl(tmp2, result); masm.shll(result, 5); masm.subl(result, tmp2); arraysHashcodeElload(masm, tmp3, new AMD64Address(ary1, index, stride, -elsize), arrayKind); masm.addl(result, tmp3); // } masm.bind(labelEnd); } }
oracle/graal
compiler/src/jdk.graal.compiler/src/jdk/graal/compiler/lir/amd64/AMD64VectorizedHashCodeOp.java
6,757
// cnt1 >= 32 && generate_vectorized_loop
line_comment
nl
/* * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.graal.compiler.lir.amd64; import static jdk.vm.ci.amd64.AMD64Kind.QWORD; import static jdk.vm.ci.code.ValueUtil.asRegister; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexMRIOp.VEXTRACTI128; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexMoveOp.VMOVDQU32; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPBROADCASTD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXBD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXBQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXBW; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXDQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXWD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVSXWQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXBD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXBQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXBW; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXDQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXWD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRMOp.VPMOVZXWQ; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRVMOp.VPADDB; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRVMOp.VPADDD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRVMOp.VPADDW; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRVMOp.VPHADDD; import static jdk.graal.compiler.asm.amd64.AMD64Assembler.VexRVMOp.VPMULLD; import static jdk.graal.compiler.asm.amd64.AVXKind.AVXSize.XMM; import static jdk.graal.compiler.asm.amd64.AVXKind.AVXSize.YMM; import static jdk.graal.compiler.asm.amd64.AVXKind.AVXSize.ZMM; import static jdk.graal.compiler.lir.amd64.AMD64LIRHelper.pointerConstant; import static jdk.graal.compiler.lir.amd64.AMD64LIRHelper.recordExternalAddress; import java.util.EnumSet; import jdk.graal.compiler.asm.Label; import jdk.graal.compiler.asm.amd64.AMD64Address; import jdk.graal.compiler.asm.amd64.AMD64Assembler.ConditionFlag; import jdk.graal.compiler.asm.amd64.AMD64MacroAssembler; import jdk.graal.compiler.asm.amd64.AVXKind; import jdk.graal.compiler.core.common.Stride; import jdk.graal.compiler.debug.GraalError; import jdk.graal.compiler.lir.LIRInstructionClass; import jdk.graal.compiler.lir.Opcode; import jdk.graal.compiler.lir.SyncPort; import jdk.graal.compiler.lir.asm.ArrayDataPointerConstant; import jdk.graal.compiler.lir.asm.CompilationResultBuilder; import jdk.graal.compiler.lir.gen.LIRGeneratorTool; import jdk.vm.ci.amd64.AMD64.CPUFeature; import jdk.vm.ci.code.Register; import jdk.vm.ci.meta.AllocatableValue; import jdk.vm.ci.meta.JavaKind; import jdk.vm.ci.meta.Value; // @formatter:off @SyncPort(from = "https://github.com/openjdk/jdk/blob/7bb59dc8da0c61c5da5c3aab5d56a6e4880001ce/src/hotspot/cpu/x86/c2_MacroAssembler_x86.cpp#L2095-L2194", sha1 = "a93850c44f7e34fcec05226bae95fd695b2ea2f7") @SyncPort(from = "https://github.com/openjdk/jdk/blob/7bb59dc8da0c61c5da5c3aab5d56a6e4880001ce/src/hotspot/cpu/x86/c2_MacroAssembler_x86.cpp#L2316-L2362", sha1 = "9cbba8bd6c4037427fa46f067abb722b15aca90c") @SyncPort(from = "https://github.com/openjdk/jdk/blob/7bb59dc8da0c61c5da5c3aab5d56a6e4880001ce/src/hotspot/cpu/x86/c2_MacroAssembler_x86.cpp#L3634-L3821", sha1 = "2457cf3f9d3ff89c1515fa5d95cc7c8437a5318b") // @formatter:on @Opcode("VECTORIZED_HASHCODE") public final class AMD64VectorizedHashCodeOp extends AMD64ComplexVectorOp { public static final LIRInstructionClass<AMD64VectorizedHashCodeOp> TYPE = LIRInstructionClass.create(AMD64VectorizedHashCodeOp.class); @Def({OperandFlag.REG}) private Value resultValue; @Alive({OperandFlag.REG}) private Value arrayStart; @Alive({OperandFlag.REG}) private Value length; @Alive({OperandFlag.REG}) private Value initialValue; private final JavaKind arrayKind; @Temp({OperandFlag.REG}) Value[] temp; @Temp({OperandFlag.REG}) Value[] vectorTemp; public AMD64VectorizedHashCodeOp(LIRGeneratorTool tool, EnumSet<CPUFeature> runtimeCheckedCPUFeatures, AllocatableValue result, AllocatableValue arrayStart, AllocatableValue length, AllocatableValue initialValue, JavaKind arrayKind) { super(TYPE, tool, runtimeCheckedCPUFeatures, YMM); this.resultValue = result; this.arrayStart = arrayStart; this.length = length; this.initialValue = initialValue; this.arrayKind = arrayKind; this.temp = allocateTempRegisters(tool, QWORD, 5); this.vectorTemp = allocateVectorRegisters(tool, JavaKind.Byte, 13); } private static void arraysHashcodeElload(AMD64MacroAssembler masm, Register dst, AMD64Address src, JavaKind eltype) { switch (eltype) { case Boolean -> masm.movzbl(dst, src); case Byte -> masm.movsbl(dst, src); case Short -> masm.movswl(dst, src); case Char -> masm.movzwl(dst, src); case Int -> masm.movl(dst, src); default -> throw GraalError.shouldNotReachHere("Unsupported JavaKind " + eltype); } } private static void vectorUnsignedCast(AMD64MacroAssembler masm, Register dst, Register src, AVXKind.AVXSize avxSize, JavaKind fromElemBt, JavaKind toElemBt) { switch (fromElemBt) { case Byte -> { switch (toElemBt) { case Short -> masm.emit(VPMOVZXBW, dst, src, avxSize); case Int -> masm.emit(VPMOVZXBD, dst, src, avxSize); case Long -> masm.emit(VPMOVZXBQ, dst, src, avxSize); default -> throw GraalError.shouldNotReachHere("Unsupported unsigned vector cast from " + fromElemBt + " to " + toElemBt); } } case Short -> { switch (toElemBt) { case Int -> masm.emit(VPMOVZXWD, dst, src, avxSize); case Long -> masm.emit(VPMOVZXWQ, dst, src, avxSize); default -> throw GraalError.shouldNotReachHere("Unsupported unsigned vector cast from " + fromElemBt + " to " + toElemBt); } } case Int -> { GraalError.guarantee(toElemBt == JavaKind.Long, "Unsupported unsigned vector cast from %s to %s", fromElemBt, toElemBt); masm.emit(VPMOVZXDQ, dst, src, avxSize); } default -> throw GraalError.shouldNotReachHere("Unsupported unsigned vector cast from " + fromElemBt + " to " + toElemBt); } } private static void vectorSignedCast(AMD64MacroAssembler masm, Register dst, Register src, AVXKind.AVXSize avxSize, JavaKind fromElemBt, JavaKind toElemBt) { switch (fromElemBt) { case Byte -> { switch (toElemBt) { case Short -> masm.emit(VPMOVSXBW, dst, src, avxSize); case Int -> masm.emit(VPMOVSXBD, dst, src, avxSize); case Long -> masm.emit(VPMOVSXBQ, dst, src, avxSize); default -> throw GraalError.shouldNotReachHere("Unsupported signed vector cast from " + fromElemBt + " to " + toElemBt); } } case Short -> { switch (toElemBt) { case Int -> masm.emit(VPMOVSXWD, dst, src, avxSize); case Long -> masm.emit(VPMOVSXWQ, dst, src, avxSize); default -> throw GraalError.shouldNotReachHere("Unsupported signed vector cast from " + fromElemBt + " to " + toElemBt); } } case Int -> { GraalError.guarantee(toElemBt == JavaKind.Long, "Unsupported signed vector cast from %s to %s", fromElemBt, toElemBt); masm.emit(VPMOVSXDQ, dst, src, avxSize); } default -> throw GraalError.shouldNotReachHere("Unsupported signed vector cast from " + fromElemBt + " to " + toElemBt); } } private static void arraysHashcodeElvcast(AMD64MacroAssembler masm, Register dst, JavaKind eltype) { switch (eltype) { case Boolean -> vectorUnsignedCast(masm, dst, dst, YMM, JavaKind.Byte, JavaKind.Int); case Byte -> vectorSignedCast(masm, dst, dst, YMM, JavaKind.Byte, JavaKind.Int); case Short -> vectorSignedCast(masm, dst, dst, YMM, JavaKind.Short, JavaKind.Int); case Char -> vectorUnsignedCast(masm, dst, dst, YMM, JavaKind.Short, JavaKind.Int); case Int -> { // do nothing } default -> throw GraalError.shouldNotReachHere("Unsupported vector cast from " + eltype); } } private static void loadVector(AMD64MacroAssembler masm, Register dst, AMD64Address src, int vlenInBytes) { switch (vlenInBytes) { case 4 -> masm.movdl(dst, src); case 8 -> masm.movq(dst, src); case 16 -> masm.movdqu(dst, src); case 32 -> masm.vmovdqu(dst, src); case 64 -> masm.emit(VMOVDQU32, dst, src, ZMM); default -> throw GraalError.shouldNotReachHere("Unsupported vector load of size " + vlenInBytes); } } // we only port Op_AddReductionVI-related code private static void reduce(AMD64MacroAssembler masm, AVXKind.AVXSize avxSize, JavaKind eleType, Register dst, Register src1, Register src2) { switch (eleType) { case Byte -> masm.emit(VPADDB, dst, src1, src2, avxSize); case Short -> masm.emit(VPADDW, dst, src1, src2, avxSize); case Int -> masm.emit(VPADDD, dst, src1, src2, avxSize); default -> throw GraalError.shouldNotReachHere("Unsupported reduce type " + eleType); } } private static void reduce2I(AMD64MacroAssembler masm, Register dst, Register src1, Register src2, Register vtmp1, Register vtmp2) { if (vtmp1.equals(src2)) { masm.movdqu(vtmp1, src2); } masm.emit(VPHADDD, vtmp1, vtmp1, vtmp1, XMM); masm.movdl(vtmp2, src1); reduce(masm, XMM, JavaKind.Int, vtmp1, vtmp1, vtmp2); masm.movdl(dst, vtmp1); } private static void reduce4I(AMD64MacroAssembler masm, Register dst, Register src1, Register src2, Register vtmp1, Register vtmp2) { if (vtmp1.equals(src2)) { masm.movdqu(vtmp1, src2); } masm.emit(VPHADDD, vtmp1, vtmp1, src2, XMM); reduce2I(masm, dst, src1, vtmp1, vtmp1, vtmp2); } private static void reduce8I(AMD64MacroAssembler masm, Register dst, Register src1, Register src2, Register vtmp1, Register vtmp2) { masm.emit(VPHADDD, vtmp1, src2, src2, YMM); masm.emit(VEXTRACTI128, vtmp2, vtmp1, 1, YMM); masm.emit(VPADDD, vtmp1, vtmp1, vtmp2, YMM); reduce2I(masm, dst, src1, vtmp1, vtmp1, vtmp2); } private static void reduceI(AMD64MacroAssembler masm, int vlen, Register dst, Register src1, Register src2, Register vtmp1, Register vtmp2) { switch (vlen) { case 2 -> reduce2I(masm, dst, src1, src2, vtmp1, vtmp2); case 4 -> reduce4I(masm, dst, src1, src2, vtmp1, vtmp2); case 8 -> reduce8I(masm, dst, src1, src2, vtmp1, vtmp2); default -> throw GraalError.shouldNotReachHere("Unsupported vector length " + vlen); } } private static ArrayDataPointerConstant powersOf31 = pointerConstant(16, new int[]{ 2111290369, -2010103841, 350799937, 11316127, 693101697, -254736545, 961614017, 31019807, -2077209343, -67006753, 1244764481, -2038056289, 211350913, -408824225, -844471871, -997072353, 1353309697, -510534177, 1507551809, -505558625, -293403007, 129082719, -1796951359, -196513505, -1807454463, 1742810335, 887503681, 28629151, 923521, 29791, 961, 31, 1, }); @Override public void emitCode(CompilationResultBuilder crb, AMD64MacroAssembler masm) { Label labelShortUnrolledBegin = new Label(); Label labelShortUnrolledLoopBegin = new Label(); Label labelShortUnrolledLoopExit = new Label(); Label labelUnrolledVectorLoopBegin = new Label(); Label labelEnd = new Label(); Register result = asRegister(resultValue); Register ary1 = asRegister(temp[0]); Register cnt1 = asRegister(temp[1]); Register tmp2 = asRegister(temp[2]); Register tmp3 = asRegister(temp[3]); Register index = asRegister(temp[4]); masm.movq(ary1, asRegister(arrayStart)); masm.movl(cnt1, asRegister(length)); masm.movl(result, asRegister(initialValue)); // For "renaming" for readability of the code Register vnext = asRegister(vectorTemp[0]); Register[] vcoef = {asRegister(vectorTemp[1]), asRegister(vectorTemp[2]), asRegister(vectorTemp[3]), asRegister(vectorTemp[4])}; Register[] vresult = {asRegister(vectorTemp[5]), asRegister(vectorTemp[6]), asRegister(vectorTemp[7]), asRegister(vectorTemp[8])}; Register[] vtmp = {asRegister(vectorTemp[9]), asRegister(vectorTemp[10]), asRegister(vectorTemp[11]), asRegister(vectorTemp[12])}; Stride stride = Stride.fromJavaKind(arrayKind); int elsize = arrayKind.getByteCount(); // @formatter:off // if (cnt1 >= 2) { // if (cnt1 >= 32) { // UNROLLED VECTOR LOOP // } // UNROLLED SCALAR LOOP // } // SINGLE SCALAR // @formatter:on masm.cmplAndJcc(cnt1, 32, ConditionFlag.Less, labelShortUnrolledBegin, false); // cnt1 >=<SUF> masm.xorl(index, index); // vresult = IntVector.zero(I256); for (int idx = 0; idx < 4; idx++) { masm.vpxor(vresult[idx], vresult[idx], vresult[idx], YMM); } // vnext = IntVector.broadcast(I256, power_of_31_backwards[0]); Register bound = tmp2; Register next = tmp3; masm.leaq(tmp2, recordExternalAddress(crb, powersOf31)); masm.movl(next, new AMD64Address(tmp2)); masm.movdl(vnext, next); masm.emit(VPBROADCASTD, vnext, vnext, YMM); // index = 0; // bound = cnt1 & ~(32 - 1); masm.movl(bound, cnt1); masm.andl(bound, ~(32 - 1)); // for (; index < bound; index += 32) { masm.bind(labelUnrolledVectorLoopBegin); // result *= next; masm.imull(result, next); /* * Load the next 32 data elements into 4 vector registers. By grouping the loads and * fetching from memory up front (loop fission), out-of-order execution can hopefully do a * better job of prefetching, while also allowing subsequent instructions to be executed * while data are still being fetched. */ for (int idx = 0; idx < 4; idx++) { loadVector(masm, vtmp[idx], new AMD64Address(ary1, index, stride, 8 * idx * elsize), elsize * 8); } // vresult = vresult * vnext + ary1[index+8*idx:index+8*idx+7]; for (int idx = 0; idx < 4; idx++) { masm.emit(VPMULLD, vresult[idx], vresult[idx], vnext, YMM); arraysHashcodeElvcast(masm, vtmp[idx], arrayKind); masm.emit(VPADDD, vresult[idx], vresult[idx], vtmp[idx], YMM); } // index += 32; masm.addl(index, 32); // index < bound; masm.cmplAndJcc(index, bound, ConditionFlag.Less, labelUnrolledVectorLoopBegin, false); // } masm.leaq(ary1, new AMD64Address(ary1, bound, stride)); masm.subl(cnt1, bound); // release bound // vresult *= IntVector.fromArray(I256, power_of_31_backwards, 1); masm.leaq(tmp2, recordExternalAddress(crb, powersOf31)); for (int idx = 0; idx < 4; idx++) { loadVector(masm, vcoef[idx], new AMD64Address(tmp2, 0x04 + idx * JavaKind.Int.getByteCount() * 8), JavaKind.Int.getByteCount() * 8); masm.emit(VPMULLD, vresult[idx], vresult[idx], vcoef[idx], YMM); } // result += vresult.reduceLanes(ADD); for (int idx = 0; idx < 4; idx++) { reduceI(masm, YMM.getBytes() / JavaKind.Int.getByteCount(), result, result, vresult[idx], vtmp[(idx * 2 + 0) % 4], vtmp[(idx * 2 + 1) % 4]); } // } else if (cnt1 < 32) { masm.bind(labelShortUnrolledBegin); // int i = 1; masm.movl(index, 1); masm.cmplAndJcc(index, cnt1, ConditionFlag.GreaterEqual, labelShortUnrolledLoopExit, false); // for (; i < cnt1 ; i += 2) { masm.bind(labelShortUnrolledLoopBegin); masm.movl(tmp3, 961); masm.imull(result, tmp3); arraysHashcodeElload(masm, tmp2, new AMD64Address(ary1, index, stride, -elsize), arrayKind); masm.movl(tmp3, tmp2); masm.shll(tmp3, 5); masm.subl(tmp3, tmp2); masm.addl(result, tmp3); arraysHashcodeElload(masm, tmp3, new AMD64Address(ary1, index, stride), arrayKind); masm.addl(result, tmp3); masm.addl(index, 2); masm.cmplAndJcc(index, cnt1, ConditionFlag.Less, labelShortUnrolledLoopBegin, false); // } // if (i >= cnt1) { masm.bind(labelShortUnrolledLoopExit); masm.jccb(ConditionFlag.Greater, labelEnd); masm.movl(tmp2, result); masm.shll(result, 5); masm.subl(result, tmp2); arraysHashcodeElload(masm, tmp3, new AMD64Address(ary1, index, stride, -elsize), arrayKind); masm.addl(result, tmp3); // } masm.bind(labelEnd); } }
19246_4
/* ***** BEGIN LICENSE BLOCK ***** * Version: EPL 2.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Eclipse Public * 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.eclipse.org/legal/epl-v20.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the EPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the EPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.truffleruby.algorithms; public final class Randomizer { private static final int N = 624; private static final int M = 397; private static final int MATRIX_A = 0x9908b0df; /* constant vector a */ private static final int UMASK = 0x80000000; /* most significant w-r bits */ private static final int LMASK = 0x7fffffff; /* least significant r bits */ private final int[] state = new int[N]; private int left = 1; private final Object seed; public Randomizer() { this(0L, 0); } public Randomizer(Object seed, int s) { this.seed = seed; state[0] = s; for (int j = 1; j < N; j++) { state[j] = (1812433253 * (state[j - 1] ^ (state[j - 1] >>> 30)) + j); } } public Randomizer(Object seed, int[] initKey) { this(seed, 19650218); int len = initKey.length; int i = 1; int j = 0; int k = Math.max(N, len); for (; k > 0; k--) { state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >>> 30)) * 1664525)) + initKey[j] + j; i++; j++; if (i >= N) { state[0] = state[N - 1]; i = 1; } if (j >= len) { j = 0; } } for (k = N - 1; k > 0; k--) { state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >>> 30)) * 1566083941)) - i; i++; if (i >= N) { state[0] = state[N - 1]; i = 1; } } state[0] = 0x80000000; } public Object getSeed() { return seed; } // MRI: genrand_int32 of mt19937.c public int unsynchronizedGenrandInt32() { if (--left <= 0) { nextState(); } int y = state[N - left]; /* Tempering */ y ^= (y >>> 11); y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= (y >>> 18); return y; } private void nextState() { int p = 0; left = N; for (int j = N - M + 1; --j > 0; p++) { state[p] = state[p + M] ^ twist(state[p], state[p + 1]); } for (int j = M; --j > 0; p++) { state[p] = state[p + M - N] ^ twist(state[p], state[p + 1]); } state[p] = state[p + M - N] ^ twist(state[p], state[0]); } private static int mixbits(int u, int v) { return (u & UMASK) | (v & LMASK); } private static int twist(int u, int v) { return (mixbits(u, v) >>> 1) ^ (((v & 1) != 0) ? MATRIX_A : 0); } }
oracle/truffleruby
src/main/java/org/truffleruby/algorithms/Randomizer.java
1,362
// MRI: genrand_int32 of mt19937.c
line_comment
nl
/* ***** BEGIN LICENSE BLOCK ***** * Version: EPL 2.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Eclipse Public * 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.eclipse.org/legal/epl-v20.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the EPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the EPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.truffleruby.algorithms; public final class Randomizer { private static final int N = 624; private static final int M = 397; private static final int MATRIX_A = 0x9908b0df; /* constant vector a */ private static final int UMASK = 0x80000000; /* most significant w-r bits */ private static final int LMASK = 0x7fffffff; /* least significant r bits */ private final int[] state = new int[N]; private int left = 1; private final Object seed; public Randomizer() { this(0L, 0); } public Randomizer(Object seed, int s) { this.seed = seed; state[0] = s; for (int j = 1; j < N; j++) { state[j] = (1812433253 * (state[j - 1] ^ (state[j - 1] >>> 30)) + j); } } public Randomizer(Object seed, int[] initKey) { this(seed, 19650218); int len = initKey.length; int i = 1; int j = 0; int k = Math.max(N, len); for (; k > 0; k--) { state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >>> 30)) * 1664525)) + initKey[j] + j; i++; j++; if (i >= N) { state[0] = state[N - 1]; i = 1; } if (j >= len) { j = 0; } } for (k = N - 1; k > 0; k--) { state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >>> 30)) * 1566083941)) - i; i++; if (i >= N) { state[0] = state[N - 1]; i = 1; } } state[0] = 0x80000000; } public Object getSeed() { return seed; } // MRI: genrand_int32<SUF> public int unsynchronizedGenrandInt32() { if (--left <= 0) { nextState(); } int y = state[N - left]; /* Tempering */ y ^= (y >>> 11); y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= (y >>> 18); return y; } private void nextState() { int p = 0; left = N; for (int j = N - M + 1; --j > 0; p++) { state[p] = state[p + M] ^ twist(state[p], state[p + 1]); } for (int j = M; --j > 0; p++) { state[p] = state[p + M - N] ^ twist(state[p], state[p + 1]); } state[p] = state[p + M - N] ^ twist(state[p], state[0]); } private static int mixbits(int u, int v) { return (u & UMASK) | (v & LMASK); } private static int twist(int u, int v) { return (mixbits(u, v) >>> 1) ^ (((v & 1) != 0) ? MATRIX_A : 0); } }
162838_9
/* * * Copyright (C) 2015-2020 Anarchy Engine Open Source Contributors (see CONTRIBUTORS.md) * * 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 https://mozilla.org/MPL/2.0/. * */ package engine.gl.mesh; import java.util.Arrays; import org.joml.Vector3f; public class Vertex { // Vertex data private float[] v_xyz = new float[] {0f, 0f, 0f}; private float[] n_xyz = new float[] {0f, 0f, 1f}; private float[] t_xyz = new float[] {0f, 0f, 0f}; private float[] rgba = new float[] {1f, 1f, 1f, 1f}; private float[] st = new float[] {0f, 0f}; // The amount of bytes an element has public static final int elementBytes = 4; // Elements per parameter public static final int positionElementCount = 3; public static final int normalElementCount = 3; public static final int tangentElementCount = 3; public static final int textureElementCount = 2; public static final int colorElementCount = 4; // Bytes per parameter public static final int positionByteCount = positionElementCount * elementBytes; public static final int normalByteCount = normalElementCount * elementBytes; public static final int tangentByteCount = tangentElementCount * elementBytes; public static final int textureByteCount = textureElementCount * elementBytes; public static final int colorByteCount = colorElementCount * elementBytes; // Byte offsets per parameter public static final int positionByteOffset = 0; public static final int normalByteOffset = positionByteOffset + positionByteCount; public static final int tangetByteOffset = normalByteOffset + tangentByteCount; public static final int textureByteOffset = tangetByteOffset + normalByteCount; public static final int colorByteOffset = textureByteOffset + textureByteCount; // The amount of elements that a vertex has public static final int elementCount = positionElementCount + normalElementCount + tangentElementCount + textureElementCount + colorElementCount; // The size of a vertex in bytes, like in C/C++: sizeof(Vertex) public static final int stride = positionByteCount + normalByteCount + tangentByteCount + textureByteCount + colorByteCount; public Vertex() { // } public Vertex(float x, float y, float z, float nx, float ny, float nz, float tx, float ty, float tz, float s, float t, float r, float g, float b, float a) { setXYZ(x, y, z); setNormalXYZ(nx, ny, nz); setRGBA(r, g, b, a); setST(s, t); } public Vertex(float x, float y, float z, float nx, float ny, float nz, float s, float t, float r, float g, float b, float a) { this(x, y, z, nx, ny, nz, 0, 0, 0, s, t, r, g, b, a); } public Vertex(float x, float y, float z, float nx, float ny, float nz, float s, float t) { this(x, y, z, nx, ny, nz, s, t, 1, 1, 1, 1); } public Vertex( Vertex vertex ) { setXYZ(vertex.getXYZ()[0], vertex.getXYZ()[1], vertex.getXYZ()[2]); setNormalXYZ(vertex.getNormalXYZ()[0], vertex.getNormalXYZ()[1], vertex.getNormalXYZ()[2]); setRGBA(vertex.getRGBA()[0], vertex.getRGBA()[1], vertex.getRGBA()[2], vertex.getRGBA()[3]); setST(vertex.getST()[0], vertex.getST()[1]); } // Setters public Vertex setXYZ(float x, float y, float z) { this.v_xyz = new float[] { x, y, z}; return this; } public Vertex setTangentXYZ(float x, float y, float z) { this.t_xyz = new float[] {x, y, z}; return this; } public Vertex setST(float s, float t) { this.st = new float[] {s, t}; return this; } public Vertex setNormalXYZ(float x, float y, float z) { this.n_xyz = new float[] {x, y, z}; return this; } public void setRGBA(float r, float g, float b, float a) { this.rgba = new float[] {r, g, b, a}; } // Getters public float[] getElements() { float[] out = new float[Vertex.elementCount]; int i = 0; // Insert XYZ elements out[i++] = this.v_xyz[0]; out[i++] = this.v_xyz[1]; out[i++] = this.v_xyz[2]; // Insert NORMAL elements out[i++] = this.n_xyz[0]; out[i++] = this.n_xyz[1]; out[i++] = this.n_xyz[2]; // Insert TANGENT elements out[i++] = this.t_xyz[0]; out[i++] = this.t_xyz[1]; out[i++] = this.t_xyz[2]; // Insert ST elements out[i++] = this.st[0]; out[i++] = this.st[1]; // Insert RGBA elements out[i++] = this.rgba[0]; out[i++] = this.rgba[1]; out[i++] = this.rgba[2]; out[i++] = this.rgba[3]; return out; } public float[] getTangentXYZ() { return new float[] {this.t_xyz[0], this.t_xyz[1], this.t_xyz[2]}; } public float[] ST() { return new float[] {this.v_xyz[0], this.v_xyz[1], this.v_xyz[2]}; } public float[] getST() { return new float[] {this.st[0], this.st[1]}; } public float[] getNormalXYZ() { return new float[] {this.n_xyz[0], this.n_xyz[1], this.n_xyz[2]}; } public float[] getXYZ() { return new float[] {this.v_xyz[0], this.v_xyz[1], this.v_xyz[2]}; } public float[] getRGBA() { return new float[] {this.rgba[0], this.rgba[1], this.rgba[2], this.rgba[3]}; } public Vertex clone() { return new Vertex(v_xyz[0], v_xyz[1], v_xyz[2], n_xyz[0], n_xyz[1], n_xyz[2], st[0], st[1], rgba[0], rgba[1], rgba[2], rgba[3]); } public String toString() { return "(" + Float.toString(v_xyz[0]) + "," + Float.toString(v_xyz[1]) + "," + Float.toString(v_xyz[2]) + ")"; } public boolean equalsLoose(Vertex vertex) { return Arrays.equals(v_xyz, vertex.v_xyz); } public Vertex add(Vector3f offset) { v_xyz[0] += offset.x; v_xyz[1] += offset.y; v_xyz[2] += offset.z; return this; } }
orange451/AnarchyEngine
src/main/java/engine/gl/mesh/Vertex.java
2,155
// Insert NORMAL elements
line_comment
nl
/* * * Copyright (C) 2015-2020 Anarchy Engine Open Source Contributors (see CONTRIBUTORS.md) * * 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 https://mozilla.org/MPL/2.0/. * */ package engine.gl.mesh; import java.util.Arrays; import org.joml.Vector3f; public class Vertex { // Vertex data private float[] v_xyz = new float[] {0f, 0f, 0f}; private float[] n_xyz = new float[] {0f, 0f, 1f}; private float[] t_xyz = new float[] {0f, 0f, 0f}; private float[] rgba = new float[] {1f, 1f, 1f, 1f}; private float[] st = new float[] {0f, 0f}; // The amount of bytes an element has public static final int elementBytes = 4; // Elements per parameter public static final int positionElementCount = 3; public static final int normalElementCount = 3; public static final int tangentElementCount = 3; public static final int textureElementCount = 2; public static final int colorElementCount = 4; // Bytes per parameter public static final int positionByteCount = positionElementCount * elementBytes; public static final int normalByteCount = normalElementCount * elementBytes; public static final int tangentByteCount = tangentElementCount * elementBytes; public static final int textureByteCount = textureElementCount * elementBytes; public static final int colorByteCount = colorElementCount * elementBytes; // Byte offsets per parameter public static final int positionByteOffset = 0; public static final int normalByteOffset = positionByteOffset + positionByteCount; public static final int tangetByteOffset = normalByteOffset + tangentByteCount; public static final int textureByteOffset = tangetByteOffset + normalByteCount; public static final int colorByteOffset = textureByteOffset + textureByteCount; // The amount of elements that a vertex has public static final int elementCount = positionElementCount + normalElementCount + tangentElementCount + textureElementCount + colorElementCount; // The size of a vertex in bytes, like in C/C++: sizeof(Vertex) public static final int stride = positionByteCount + normalByteCount + tangentByteCount + textureByteCount + colorByteCount; public Vertex() { // } public Vertex(float x, float y, float z, float nx, float ny, float nz, float tx, float ty, float tz, float s, float t, float r, float g, float b, float a) { setXYZ(x, y, z); setNormalXYZ(nx, ny, nz); setRGBA(r, g, b, a); setST(s, t); } public Vertex(float x, float y, float z, float nx, float ny, float nz, float s, float t, float r, float g, float b, float a) { this(x, y, z, nx, ny, nz, 0, 0, 0, s, t, r, g, b, a); } public Vertex(float x, float y, float z, float nx, float ny, float nz, float s, float t) { this(x, y, z, nx, ny, nz, s, t, 1, 1, 1, 1); } public Vertex( Vertex vertex ) { setXYZ(vertex.getXYZ()[0], vertex.getXYZ()[1], vertex.getXYZ()[2]); setNormalXYZ(vertex.getNormalXYZ()[0], vertex.getNormalXYZ()[1], vertex.getNormalXYZ()[2]); setRGBA(vertex.getRGBA()[0], vertex.getRGBA()[1], vertex.getRGBA()[2], vertex.getRGBA()[3]); setST(vertex.getST()[0], vertex.getST()[1]); } // Setters public Vertex setXYZ(float x, float y, float z) { this.v_xyz = new float[] { x, y, z}; return this; } public Vertex setTangentXYZ(float x, float y, float z) { this.t_xyz = new float[] {x, y, z}; return this; } public Vertex setST(float s, float t) { this.st = new float[] {s, t}; return this; } public Vertex setNormalXYZ(float x, float y, float z) { this.n_xyz = new float[] {x, y, z}; return this; } public void setRGBA(float r, float g, float b, float a) { this.rgba = new float[] {r, g, b, a}; } // Getters public float[] getElements() { float[] out = new float[Vertex.elementCount]; int i = 0; // Insert XYZ elements out[i++] = this.v_xyz[0]; out[i++] = this.v_xyz[1]; out[i++] = this.v_xyz[2]; // Insert NORMAL<SUF> out[i++] = this.n_xyz[0]; out[i++] = this.n_xyz[1]; out[i++] = this.n_xyz[2]; // Insert TANGENT elements out[i++] = this.t_xyz[0]; out[i++] = this.t_xyz[1]; out[i++] = this.t_xyz[2]; // Insert ST elements out[i++] = this.st[0]; out[i++] = this.st[1]; // Insert RGBA elements out[i++] = this.rgba[0]; out[i++] = this.rgba[1]; out[i++] = this.rgba[2]; out[i++] = this.rgba[3]; return out; } public float[] getTangentXYZ() { return new float[] {this.t_xyz[0], this.t_xyz[1], this.t_xyz[2]}; } public float[] ST() { return new float[] {this.v_xyz[0], this.v_xyz[1], this.v_xyz[2]}; } public float[] getST() { return new float[] {this.st[0], this.st[1]}; } public float[] getNormalXYZ() { return new float[] {this.n_xyz[0], this.n_xyz[1], this.n_xyz[2]}; } public float[] getXYZ() { return new float[] {this.v_xyz[0], this.v_xyz[1], this.v_xyz[2]}; } public float[] getRGBA() { return new float[] {this.rgba[0], this.rgba[1], this.rgba[2], this.rgba[3]}; } public Vertex clone() { return new Vertex(v_xyz[0], v_xyz[1], v_xyz[2], n_xyz[0], n_xyz[1], n_xyz[2], st[0], st[1], rgba[0], rgba[1], rgba[2], rgba[3]); } public String toString() { return "(" + Float.toString(v_xyz[0]) + "," + Float.toString(v_xyz[1]) + "," + Float.toString(v_xyz[2]) + ")"; } public boolean equalsLoose(Vertex vertex) { return Arrays.equals(v_xyz, vertex.v_xyz); } public Vertex add(Vector3f offset) { v_xyz[0] += offset.x; v_xyz[1] += offset.y; v_xyz[2] += offset.z; return this; } }
17940_10
package io.github.terra121.dataset; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.IOUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.github.terra121.TerraConfig; import io.github.terra121.TerraMod; import io.github.terra121.projection.GeographicProjection; public class OpenStreetMaps { private static final double CHUNK_SIZE = 16; public static final double TILE_SIZE = 1 / 60.0;//250*(360.0/40075000.0); private static final double NOTHING = 0.01; private static final String OVERPASS_INSTANCE = "https://overpass-api.de";//"https://overpass.kumi.systems"; private static final String URL_PREFACE = TerraConfig.serverOverpass + "/api/interpreter?data=[out:json];way("; private String URL_A = ")"; private static final String URL_B = ")%20tags%20qt;(._<;);out%20body%20qt;"; private static final String URL_C = "is_in("; private String URL_SUFFIX = ");area._[~\"natural|waterway\"~\"water|riverbank\"];out%20ids;"; private HashMap<Coord, Set<Edge>> chunks; public LinkedHashMap<Coord, Region> regions; public Water water; private int numcache = TerraConfig.osmCacheSize; private ArrayList<Edge> allEdges; private Gson gson; private GeographicProjection projection; public static enum Type { IGNORE, ROAD, MINOR, SIDE, MAIN, INTERCHANGE, LIMITEDACCESS, FREEWAY, STREAM, RIVER, BUILDING, RAIL // ranges from minor to freeway for roads, use road if not known } public static enum Attributes { ISBRIDGE, ISTUNNEL, NONE } public static class noneBoolAttributes { public static String layer; } Type wayType; byte wayLanes; boolean doRoad; boolean doWater; boolean doBuildings; public OpenStreetMaps(GeographicProjection proj, boolean doRoad, boolean doWater, boolean doBuildings) { gson = new GsonBuilder().create(); chunks = new LinkedHashMap<Coord, Set<Edge>>(); allEdges = new ArrayList<Edge>(); regions = new LinkedHashMap<Coord, Region>(); projection = proj; try { water = new Water(this, 256); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.doRoad = doRoad; this.doWater = doWater; this.doBuildings = doBuildings; if (!doBuildings) URL_A += "[!\"building\"]"; if (!doRoad) URL_A += "[!\"highway\"]"; if (!doWater) URL_A += "[!\"water\"][!\"natural\"][!\"waterway\"]"; URL_A += ";out%20geom("; } public Coord getRegion(double lon, double lat) { return new Coord((int) Math.floor(lon / TILE_SIZE), (int) Math.floor(lat / TILE_SIZE)); } public Set<Edge> chunkStructures(int x, int z) { Coord coord = new Coord(x, z); if (regionCache(projection.toGeo(x * CHUNK_SIZE, z * CHUNK_SIZE)) == null) return null; if (regionCache(projection.toGeo((x + 1) * CHUNK_SIZE, z * CHUNK_SIZE)) == null) return null; if (regionCache(projection.toGeo((x + 1) * CHUNK_SIZE, (z + 1) * CHUNK_SIZE)) == null) return null; if (regionCache(projection.toGeo(x * CHUNK_SIZE, (z + 1) * CHUNK_SIZE)) == null) return null; return chunks.get(coord); } public Region regionCache(double[] corner) { //bound check if(!(corner[0]>=-180 && corner[0]<=180 && corner[1]>=-80 && corner[1]<=80)) return null; Coord coord = getRegion(corner[0], corner[1]); Region region; if ((region = regions.get(coord)) == null) { region = new Region(coord, water); int i; for (i = 0; i < 5 && !regiondownload(region); i++) ; regions.put(coord, region); if (regions.size() > numcache) { //TODO: delete beter Iterator<Region> it = regions.values().iterator(); Region delete = it.next(); it.remove(); removeRegion(delete); } if (i == 5) { region.failedDownload = true; TerraMod.LOGGER.error("OSM region" + region.coord.x + " " + region.coord.y + " failed to download several times, no structures will spawn"); return null; } } else if (region.failedDownload) return null; //don't return dummy regions return region; } public boolean regiondownload(Region region) { double X = region.coord.x * TILE_SIZE; double Y = region.coord.y * TILE_SIZE; //limit extreme (a.k.a. way too clustered on some projections) requests and out of bounds requests if (Y > 80 || Y < -80 || X < -180 || X > 180 - TILE_SIZE) { region.failedDownload = true; return false; } try { String bottomleft = Y + "," + X; String bbox = bottomleft + "," + (Y + TILE_SIZE) + "," + (X + TILE_SIZE); String urltext = URL_PREFACE + bbox + URL_A + bbox + URL_B; if (doWater) urltext += URL_C + bottomleft + URL_SUFFIX; TerraMod.LOGGER.info(urltext); //kumi systems request a meaningful user-agent URL url = new URL(urltext); URLConnection c = url.openConnection(); c.addRequestProperty("User-Agent", TerraMod.USERAGENT); InputStream is = c.getInputStream(); doGson(is, region); is.close(); } catch (Exception e) { TerraMod.LOGGER.error("Osm region download failed, no osm features will spawn, " + e); e.printStackTrace(); return false; } double[] ll = projection.fromGeo(X, Y); double[] lr = projection.fromGeo(X + TILE_SIZE, Y); double[] ur = projection.fromGeo(X + TILE_SIZE, Y + TILE_SIZE); double[] ul = projection.fromGeo(X, Y + TILE_SIZE); //estimate bounds of region in terms of chunks int lowX = (int) Math.floor(Math.min(Math.min(ll[0], ul[0]), Math.min(lr[0], ur[0])) / CHUNK_SIZE); int highX = (int) Math.ceil(Math.max(Math.max(ll[0], ul[0]), Math.max(lr[0], ur[0])) / CHUNK_SIZE); int lowZ = (int) Math.floor(Math.min(Math.min(ll[1], ul[1]), Math.min(lr[1], ur[1])) / CHUNK_SIZE); int highZ = (int) Math.ceil(Math.max(Math.max(ll[1], ul[1]), Math.max(lr[1], ur[1])) / CHUNK_SIZE); for (Edge e : allEdges) relevantChunks(lowX, lowZ, highX, highZ, e); allEdges.clear(); return true; } private void doGson(InputStream is, Region region) throws IOException { StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, StandardCharsets.UTF_8); String str = writer.toString(); Data data = gson.fromJson(str.toString(), Data.class); Map<Long, Element> allWays = new HashMap<Long, Element>(); Set<Element> unusedWays = new HashSet<Element>(); Set<Long> ground = new HashSet<Long>(); for (Element elem : data.elements) { Attributes attributes = Attributes.NONE; if (elem.type == EType.way) { allWays.put(elem.id, elem); if (elem.tags == null) { unusedWays.add(elem); continue; } String naturalv = null, highway = null, waterway = null, building = null, istunnel = null, isbridge = null; if (doWater) { naturalv = elem.tags.get("natural"); waterway = elem.tags.get("waterway"); } if (doRoad) { highway = elem.tags.get("highway"); istunnel = elem.tags.get("tunnel"); // to be implemented isbridge = elem.tags.get("bridge"); } if (doBuildings) { building = elem.tags.get("building"); } if (naturalv != null && naturalv.equals("coastline")) { waterway(elem, -1, region, null); } else if (highway != null || (waterway != null && (waterway.equals("river") || waterway.equals("canal") || waterway.equals("stream"))) || building != null) { //TODO: fewer equals Type type = Type.ROAD; if (waterway != null) { type = Type.STREAM; if (waterway.equals("river") || waterway.equals("canal")) type = Type.RIVER; } if (building != null) type = Type.BUILDING; if (istunnel != null && istunnel.equals("yes")) { attributes = Attributes.ISTUNNEL; } else if (isbridge != null && isbridge.equals("yes")) { attributes = Attributes.ISBRIDGE; } else { // totally skip classification if it's a tunnel or bridge. this should make it more efficient. if (highway != null && attributes == Attributes.NONE) { switch (highway) { case "motorway": type = Type.FREEWAY; break; case "trunk": type = Type.LIMITEDACCESS; break; case "motorway_link": case "trunk_link": type = Type.INTERCHANGE; break; case "secondary": type = Type.SIDE; break; case "primary": case "raceway": type = Type.MAIN; break; case "tertiary": case "residential": type = Type.MINOR; break; default: if (highway.equals("primary_link") || highway.equals("secondary_link") || highway.equals("living_street") || highway.equals("bus_guideway") || highway.equals("service") || highway.equals("unclassified")) type = Type.SIDE; break; } } } //get lane number (default is 2) String slanes = elem.tags.get("lanes"); String slayer = elem.tags.get("layers"); byte lanes = 2; byte layer = 1; if (slayer != null) { try { layer = Byte.parseByte(slayer); } catch (NumberFormatException e) { // default to layer 1 if bad format } } if (slanes != null) { try { lanes = Byte.parseByte(slanes); } catch (NumberFormatException e) { } //default to 2, if bad format } //prevent super high # of lanes to prevent ridiculous results (prly a mistake if its this high anyways) if (lanes > 8) lanes = 8; // an interchange that doesn't have any lane tag should be defaulted to 2 lanes if (lanes < 2 && type == Type.INTERCHANGE) { lanes = 2; } // upgrade road type if many lanes (and the road was important enough to include a lanes tag) if (lanes > 2 && type == Type.MINOR) type = Type.MAIN; addWay(elem, type, lanes, region, attributes, layer); } else unusedWays.add(elem); } else if (elem.type == EType.relation && elem.members != null && elem.tags != null) { if(doWater) { String naturalv = elem.tags.get("natural"); String waterv = elem.tags.get("water"); String wway = elem.tags.get("waterway"); if (waterv != null || (naturalv != null && naturalv.equals("water")) || (wway != null && wway.equals("riverbank"))) { for (Member member : elem.members) { if (member.type == EType.way) { Element way = allWays.get(member.ref); if (way != null) { waterway(way, elem.id + 3600000000L, region, null); unusedWays.remove(way); } } } continue; } } if(doBuildings && elem.tags.get("building")!=null) { for (Member member : elem.members) { if (member.type == EType.way) { Element way = allWays.get(member.ref); if (way != null) { addWay(way, Type.BUILDING, (byte) 1, region, Attributes.NONE, (byte) 0); unusedWays.remove(way); } } } } } else if (elem.type == EType.area) { ground.add(elem.id); } } if (doWater) { for (Element way : unusedWays) { if (way.tags != null) { String naturalv = way.tags.get("natural"); String waterv = way.tags.get("water"); String wway = way.tags.get("waterway"); if (waterv != null || (naturalv != null && naturalv.equals("water")) || (wway != null && wway.equals("riverbank"))) waterway(way, way.id + 2400000000L, region, null); } } if (water.grounding.state(region.coord.x, region.coord.y) == 0) { ground.add(-1L); } region.renderWater(ground); } } void addWay(Element elem, Type type, byte lanes, Region region, Attributes attributes, byte layer) { double[] lastProj = null; if(elem.geometry != null) for (Geometry geom : elem.geometry) { if (geom == null) lastProj = null; else { double[] proj = projection.fromGeo(geom.lon, geom.lat); if (lastProj != null) { //register as a road edge allEdges.add(new Edge(lastProj[0], lastProj[1], proj[0], proj[1], type, lanes, region, attributes, layer)); } lastProj = proj; } } } Geometry waterway(Element way, long id, Region region, Geometry last) { if (way.geometry != null) for (Geometry geom : way.geometry) { if (geom != null && last != null) { region.addWaterEdge(last.lon, last.lat, geom.lon, geom.lat, id); } last = geom; } return last; } private void relevantChunks(int lowX, int lowZ, int highX, int highZ, Edge edge) { Coord start = new Coord((int) Math.floor(edge.slon / CHUNK_SIZE), (int) Math.floor(edge.slat / CHUNK_SIZE)); Coord end = new Coord((int) Math.floor(edge.elon / CHUNK_SIZE), (int) Math.floor(edge.elat / CHUNK_SIZE)); double startx = edge.slon; double endx = edge.elon; if (startx > endx) { Coord tmp = start; start = end; end = tmp; startx = endx; endx = edge.slon; } highX = Math.min(highX, end.x + 1); for (int x = Math.max(lowX, start.x); x < highX; x++) { double X = x * CHUNK_SIZE; int from = (int) Math.floor((edge.slope * Math.max(X, startx) + edge.offset) / CHUNK_SIZE); int to = (int) Math.floor((edge.slope * Math.min(X + CHUNK_SIZE, endx) + edge.offset) / CHUNK_SIZE); if (from > to) { int tmp = from; from = to; to = tmp; } for (int y = Math.max(from, lowZ); y <= to && y < highZ; y++) { assoiateWithChunk(new Coord(x, y), edge); } } } private void assoiateWithChunk(Coord c, Edge edge) { Set<Edge> list = chunks.get(c); if (list == null) { list = new HashSet<Edge>(); chunks.put(c, list); } list.add(edge); } //TODO: this algorithm is untested and may have some memory leak issues and also strait up copies code from earlier private void removeRegion(Region delete) { double X = delete.coord.x * TILE_SIZE; double Y = delete.coord.y * TILE_SIZE; double[] ll = projection.fromGeo(X, Y); double[] lr = projection.fromGeo(X + TILE_SIZE, Y); double[] ur = projection.fromGeo(X + TILE_SIZE, Y + TILE_SIZE); double[] ul = projection.fromGeo(X, Y + TILE_SIZE); //estimate bounds of region in terms of chunks int lowX = (int) Math.floor(Math.min(Math.min(ll[0], ul[0]), Math.min(lr[0], ur[0])) / CHUNK_SIZE); int highX = (int) Math.ceil(Math.max(Math.max(ll[0], ul[0]), Math.max(lr[0], ur[0])) / CHUNK_SIZE); int lowZ = (int) Math.floor(Math.min(Math.min(ll[1], ul[1]), Math.min(lr[1], ur[1])) / CHUNK_SIZE); int highZ = (int) Math.ceil(Math.max(Math.max(ll[1], ul[1]), Math.max(lr[1], ur[1])) / CHUNK_SIZE); for (int x = lowX; x < highX; x++) { for (int z = lowZ; z < highZ; z++) { Set<Edge> edges = chunks.get(new Coord(x, z)); if (edges != null) { Iterator<Edge> it = edges.iterator(); while (it.hasNext()) if (it.next().region.equals(delete)) it.remove(); if (edges.size() <= 0) chunks.remove(new Coord(x, z)); } } } } //integer coordinate class public static class Coord { public int x; public int y; private Coord(int x, int y) { this.x = x; this.y = y; } public int hashCode() { return (x * 79399) + (y * 100000); } public boolean equals(Object o) { Coord c = (Coord) o; return c.x == x && c.y == y; } public String toString() { return "(" + x + ", " + y + ")"; } } public static class Edge { public Type type; public double slat; public double slon; public double elat; public double elon; public Attributes attribute; public byte layer_number; public double slope; public double offset; public byte lanes; Region region; private double squareLength() { double dlat = elat - slat; double dlon = elon - slon; return dlat * dlat + dlon * dlon; } private Edge(double slon, double slat, double elon, double elat, Type type, byte lanes, Region region, Attributes att, byte ly) { //slope must not be infinity, slight inaccuracy shouldn't even be noticible unless you go looking for it double dif = elon - slon; if (-NOTHING <= dif && dif <= NOTHING) { if (dif < 0) { elon -= NOTHING; } else { elon += NOTHING; } } this.slat = slat; this.slon = slon; this.elat = elat; this.elon = elon; this.type = type; this.attribute = att; this.lanes = lanes; this.region = region; this.layer_number = ly; slope = (elat - slat) / (elon - slon); offset = slat - slope * slon; } public int hashCode() { return (int) ((slon * 79399) + (slat * 100000) + (elat * 13467) + (elon * 103466)); } public boolean equals(Object o) { Edge e = (Edge) o; return e.slat == slat && e.slon == slon && e.elat == elat && e.elon == e.elon; } public String toString() { return "(" + slat + ", " + slon + "," + elat + "," + elon + ")"; } } public static enum EType { invalid, node, way, relation, area } public static class Member { EType type; long ref; String role; } public static class Geometry { double lat; double lon; } public static class Element { EType type; long id; Map<String, String> tags; long[] nodes; Member[] members; Geometry[] geometry; } public static class Data { float version; String generator; Map<String, String> osm3s; List<Element> elements; } public static void main(String[] args) { } }
orangeadam3/terra121
src/main/java/io/github/terra121/dataset/OpenStreetMaps.java
6,461
//get lane number (default is 2)
line_comment
nl
package io.github.terra121.dataset; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.IOUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import io.github.terra121.TerraConfig; import io.github.terra121.TerraMod; import io.github.terra121.projection.GeographicProjection; public class OpenStreetMaps { private static final double CHUNK_SIZE = 16; public static final double TILE_SIZE = 1 / 60.0;//250*(360.0/40075000.0); private static final double NOTHING = 0.01; private static final String OVERPASS_INSTANCE = "https://overpass-api.de";//"https://overpass.kumi.systems"; private static final String URL_PREFACE = TerraConfig.serverOverpass + "/api/interpreter?data=[out:json];way("; private String URL_A = ")"; private static final String URL_B = ")%20tags%20qt;(._<;);out%20body%20qt;"; private static final String URL_C = "is_in("; private String URL_SUFFIX = ");area._[~\"natural|waterway\"~\"water|riverbank\"];out%20ids;"; private HashMap<Coord, Set<Edge>> chunks; public LinkedHashMap<Coord, Region> regions; public Water water; private int numcache = TerraConfig.osmCacheSize; private ArrayList<Edge> allEdges; private Gson gson; private GeographicProjection projection; public static enum Type { IGNORE, ROAD, MINOR, SIDE, MAIN, INTERCHANGE, LIMITEDACCESS, FREEWAY, STREAM, RIVER, BUILDING, RAIL // ranges from minor to freeway for roads, use road if not known } public static enum Attributes { ISBRIDGE, ISTUNNEL, NONE } public static class noneBoolAttributes { public static String layer; } Type wayType; byte wayLanes; boolean doRoad; boolean doWater; boolean doBuildings; public OpenStreetMaps(GeographicProjection proj, boolean doRoad, boolean doWater, boolean doBuildings) { gson = new GsonBuilder().create(); chunks = new LinkedHashMap<Coord, Set<Edge>>(); allEdges = new ArrayList<Edge>(); regions = new LinkedHashMap<Coord, Region>(); projection = proj; try { water = new Water(this, 256); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.doRoad = doRoad; this.doWater = doWater; this.doBuildings = doBuildings; if (!doBuildings) URL_A += "[!\"building\"]"; if (!doRoad) URL_A += "[!\"highway\"]"; if (!doWater) URL_A += "[!\"water\"][!\"natural\"][!\"waterway\"]"; URL_A += ";out%20geom("; } public Coord getRegion(double lon, double lat) { return new Coord((int) Math.floor(lon / TILE_SIZE), (int) Math.floor(lat / TILE_SIZE)); } public Set<Edge> chunkStructures(int x, int z) { Coord coord = new Coord(x, z); if (regionCache(projection.toGeo(x * CHUNK_SIZE, z * CHUNK_SIZE)) == null) return null; if (regionCache(projection.toGeo((x + 1) * CHUNK_SIZE, z * CHUNK_SIZE)) == null) return null; if (regionCache(projection.toGeo((x + 1) * CHUNK_SIZE, (z + 1) * CHUNK_SIZE)) == null) return null; if (regionCache(projection.toGeo(x * CHUNK_SIZE, (z + 1) * CHUNK_SIZE)) == null) return null; return chunks.get(coord); } public Region regionCache(double[] corner) { //bound check if(!(corner[0]>=-180 && corner[0]<=180 && corner[1]>=-80 && corner[1]<=80)) return null; Coord coord = getRegion(corner[0], corner[1]); Region region; if ((region = regions.get(coord)) == null) { region = new Region(coord, water); int i; for (i = 0; i < 5 && !regiondownload(region); i++) ; regions.put(coord, region); if (regions.size() > numcache) { //TODO: delete beter Iterator<Region> it = regions.values().iterator(); Region delete = it.next(); it.remove(); removeRegion(delete); } if (i == 5) { region.failedDownload = true; TerraMod.LOGGER.error("OSM region" + region.coord.x + " " + region.coord.y + " failed to download several times, no structures will spawn"); return null; } } else if (region.failedDownload) return null; //don't return dummy regions return region; } public boolean regiondownload(Region region) { double X = region.coord.x * TILE_SIZE; double Y = region.coord.y * TILE_SIZE; //limit extreme (a.k.a. way too clustered on some projections) requests and out of bounds requests if (Y > 80 || Y < -80 || X < -180 || X > 180 - TILE_SIZE) { region.failedDownload = true; return false; } try { String bottomleft = Y + "," + X; String bbox = bottomleft + "," + (Y + TILE_SIZE) + "," + (X + TILE_SIZE); String urltext = URL_PREFACE + bbox + URL_A + bbox + URL_B; if (doWater) urltext += URL_C + bottomleft + URL_SUFFIX; TerraMod.LOGGER.info(urltext); //kumi systems request a meaningful user-agent URL url = new URL(urltext); URLConnection c = url.openConnection(); c.addRequestProperty("User-Agent", TerraMod.USERAGENT); InputStream is = c.getInputStream(); doGson(is, region); is.close(); } catch (Exception e) { TerraMod.LOGGER.error("Osm region download failed, no osm features will spawn, " + e); e.printStackTrace(); return false; } double[] ll = projection.fromGeo(X, Y); double[] lr = projection.fromGeo(X + TILE_SIZE, Y); double[] ur = projection.fromGeo(X + TILE_SIZE, Y + TILE_SIZE); double[] ul = projection.fromGeo(X, Y + TILE_SIZE); //estimate bounds of region in terms of chunks int lowX = (int) Math.floor(Math.min(Math.min(ll[0], ul[0]), Math.min(lr[0], ur[0])) / CHUNK_SIZE); int highX = (int) Math.ceil(Math.max(Math.max(ll[0], ul[0]), Math.max(lr[0], ur[0])) / CHUNK_SIZE); int lowZ = (int) Math.floor(Math.min(Math.min(ll[1], ul[1]), Math.min(lr[1], ur[1])) / CHUNK_SIZE); int highZ = (int) Math.ceil(Math.max(Math.max(ll[1], ul[1]), Math.max(lr[1], ur[1])) / CHUNK_SIZE); for (Edge e : allEdges) relevantChunks(lowX, lowZ, highX, highZ, e); allEdges.clear(); return true; } private void doGson(InputStream is, Region region) throws IOException { StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, StandardCharsets.UTF_8); String str = writer.toString(); Data data = gson.fromJson(str.toString(), Data.class); Map<Long, Element> allWays = new HashMap<Long, Element>(); Set<Element> unusedWays = new HashSet<Element>(); Set<Long> ground = new HashSet<Long>(); for (Element elem : data.elements) { Attributes attributes = Attributes.NONE; if (elem.type == EType.way) { allWays.put(elem.id, elem); if (elem.tags == null) { unusedWays.add(elem); continue; } String naturalv = null, highway = null, waterway = null, building = null, istunnel = null, isbridge = null; if (doWater) { naturalv = elem.tags.get("natural"); waterway = elem.tags.get("waterway"); } if (doRoad) { highway = elem.tags.get("highway"); istunnel = elem.tags.get("tunnel"); // to be implemented isbridge = elem.tags.get("bridge"); } if (doBuildings) { building = elem.tags.get("building"); } if (naturalv != null && naturalv.equals("coastline")) { waterway(elem, -1, region, null); } else if (highway != null || (waterway != null && (waterway.equals("river") || waterway.equals("canal") || waterway.equals("stream"))) || building != null) { //TODO: fewer equals Type type = Type.ROAD; if (waterway != null) { type = Type.STREAM; if (waterway.equals("river") || waterway.equals("canal")) type = Type.RIVER; } if (building != null) type = Type.BUILDING; if (istunnel != null && istunnel.equals("yes")) { attributes = Attributes.ISTUNNEL; } else if (isbridge != null && isbridge.equals("yes")) { attributes = Attributes.ISBRIDGE; } else { // totally skip classification if it's a tunnel or bridge. this should make it more efficient. if (highway != null && attributes == Attributes.NONE) { switch (highway) { case "motorway": type = Type.FREEWAY; break; case "trunk": type = Type.LIMITEDACCESS; break; case "motorway_link": case "trunk_link": type = Type.INTERCHANGE; break; case "secondary": type = Type.SIDE; break; case "primary": case "raceway": type = Type.MAIN; break; case "tertiary": case "residential": type = Type.MINOR; break; default: if (highway.equals("primary_link") || highway.equals("secondary_link") || highway.equals("living_street") || highway.equals("bus_guideway") || highway.equals("service") || highway.equals("unclassified")) type = Type.SIDE; break; } } } //get lane<SUF> String slanes = elem.tags.get("lanes"); String slayer = elem.tags.get("layers"); byte lanes = 2; byte layer = 1; if (slayer != null) { try { layer = Byte.parseByte(slayer); } catch (NumberFormatException e) { // default to layer 1 if bad format } } if (slanes != null) { try { lanes = Byte.parseByte(slanes); } catch (NumberFormatException e) { } //default to 2, if bad format } //prevent super high # of lanes to prevent ridiculous results (prly a mistake if its this high anyways) if (lanes > 8) lanes = 8; // an interchange that doesn't have any lane tag should be defaulted to 2 lanes if (lanes < 2 && type == Type.INTERCHANGE) { lanes = 2; } // upgrade road type if many lanes (and the road was important enough to include a lanes tag) if (lanes > 2 && type == Type.MINOR) type = Type.MAIN; addWay(elem, type, lanes, region, attributes, layer); } else unusedWays.add(elem); } else if (elem.type == EType.relation && elem.members != null && elem.tags != null) { if(doWater) { String naturalv = elem.tags.get("natural"); String waterv = elem.tags.get("water"); String wway = elem.tags.get("waterway"); if (waterv != null || (naturalv != null && naturalv.equals("water")) || (wway != null && wway.equals("riverbank"))) { for (Member member : elem.members) { if (member.type == EType.way) { Element way = allWays.get(member.ref); if (way != null) { waterway(way, elem.id + 3600000000L, region, null); unusedWays.remove(way); } } } continue; } } if(doBuildings && elem.tags.get("building")!=null) { for (Member member : elem.members) { if (member.type == EType.way) { Element way = allWays.get(member.ref); if (way != null) { addWay(way, Type.BUILDING, (byte) 1, region, Attributes.NONE, (byte) 0); unusedWays.remove(way); } } } } } else if (elem.type == EType.area) { ground.add(elem.id); } } if (doWater) { for (Element way : unusedWays) { if (way.tags != null) { String naturalv = way.tags.get("natural"); String waterv = way.tags.get("water"); String wway = way.tags.get("waterway"); if (waterv != null || (naturalv != null && naturalv.equals("water")) || (wway != null && wway.equals("riverbank"))) waterway(way, way.id + 2400000000L, region, null); } } if (water.grounding.state(region.coord.x, region.coord.y) == 0) { ground.add(-1L); } region.renderWater(ground); } } void addWay(Element elem, Type type, byte lanes, Region region, Attributes attributes, byte layer) { double[] lastProj = null; if(elem.geometry != null) for (Geometry geom : elem.geometry) { if (geom == null) lastProj = null; else { double[] proj = projection.fromGeo(geom.lon, geom.lat); if (lastProj != null) { //register as a road edge allEdges.add(new Edge(lastProj[0], lastProj[1], proj[0], proj[1], type, lanes, region, attributes, layer)); } lastProj = proj; } } } Geometry waterway(Element way, long id, Region region, Geometry last) { if (way.geometry != null) for (Geometry geom : way.geometry) { if (geom != null && last != null) { region.addWaterEdge(last.lon, last.lat, geom.lon, geom.lat, id); } last = geom; } return last; } private void relevantChunks(int lowX, int lowZ, int highX, int highZ, Edge edge) { Coord start = new Coord((int) Math.floor(edge.slon / CHUNK_SIZE), (int) Math.floor(edge.slat / CHUNK_SIZE)); Coord end = new Coord((int) Math.floor(edge.elon / CHUNK_SIZE), (int) Math.floor(edge.elat / CHUNK_SIZE)); double startx = edge.slon; double endx = edge.elon; if (startx > endx) { Coord tmp = start; start = end; end = tmp; startx = endx; endx = edge.slon; } highX = Math.min(highX, end.x + 1); for (int x = Math.max(lowX, start.x); x < highX; x++) { double X = x * CHUNK_SIZE; int from = (int) Math.floor((edge.slope * Math.max(X, startx) + edge.offset) / CHUNK_SIZE); int to = (int) Math.floor((edge.slope * Math.min(X + CHUNK_SIZE, endx) + edge.offset) / CHUNK_SIZE); if (from > to) { int tmp = from; from = to; to = tmp; } for (int y = Math.max(from, lowZ); y <= to && y < highZ; y++) { assoiateWithChunk(new Coord(x, y), edge); } } } private void assoiateWithChunk(Coord c, Edge edge) { Set<Edge> list = chunks.get(c); if (list == null) { list = new HashSet<Edge>(); chunks.put(c, list); } list.add(edge); } //TODO: this algorithm is untested and may have some memory leak issues and also strait up copies code from earlier private void removeRegion(Region delete) { double X = delete.coord.x * TILE_SIZE; double Y = delete.coord.y * TILE_SIZE; double[] ll = projection.fromGeo(X, Y); double[] lr = projection.fromGeo(X + TILE_SIZE, Y); double[] ur = projection.fromGeo(X + TILE_SIZE, Y + TILE_SIZE); double[] ul = projection.fromGeo(X, Y + TILE_SIZE); //estimate bounds of region in terms of chunks int lowX = (int) Math.floor(Math.min(Math.min(ll[0], ul[0]), Math.min(lr[0], ur[0])) / CHUNK_SIZE); int highX = (int) Math.ceil(Math.max(Math.max(ll[0], ul[0]), Math.max(lr[0], ur[0])) / CHUNK_SIZE); int lowZ = (int) Math.floor(Math.min(Math.min(ll[1], ul[1]), Math.min(lr[1], ur[1])) / CHUNK_SIZE); int highZ = (int) Math.ceil(Math.max(Math.max(ll[1], ul[1]), Math.max(lr[1], ur[1])) / CHUNK_SIZE); for (int x = lowX; x < highX; x++) { for (int z = lowZ; z < highZ; z++) { Set<Edge> edges = chunks.get(new Coord(x, z)); if (edges != null) { Iterator<Edge> it = edges.iterator(); while (it.hasNext()) if (it.next().region.equals(delete)) it.remove(); if (edges.size() <= 0) chunks.remove(new Coord(x, z)); } } } } //integer coordinate class public static class Coord { public int x; public int y; private Coord(int x, int y) { this.x = x; this.y = y; } public int hashCode() { return (x * 79399) + (y * 100000); } public boolean equals(Object o) { Coord c = (Coord) o; return c.x == x && c.y == y; } public String toString() { return "(" + x + ", " + y + ")"; } } public static class Edge { public Type type; public double slat; public double slon; public double elat; public double elon; public Attributes attribute; public byte layer_number; public double slope; public double offset; public byte lanes; Region region; private double squareLength() { double dlat = elat - slat; double dlon = elon - slon; return dlat * dlat + dlon * dlon; } private Edge(double slon, double slat, double elon, double elat, Type type, byte lanes, Region region, Attributes att, byte ly) { //slope must not be infinity, slight inaccuracy shouldn't even be noticible unless you go looking for it double dif = elon - slon; if (-NOTHING <= dif && dif <= NOTHING) { if (dif < 0) { elon -= NOTHING; } else { elon += NOTHING; } } this.slat = slat; this.slon = slon; this.elat = elat; this.elon = elon; this.type = type; this.attribute = att; this.lanes = lanes; this.region = region; this.layer_number = ly; slope = (elat - slat) / (elon - slon); offset = slat - slope * slon; } public int hashCode() { return (int) ((slon * 79399) + (slat * 100000) + (elat * 13467) + (elon * 103466)); } public boolean equals(Object o) { Edge e = (Edge) o; return e.slat == slat && e.slon == slon && e.elat == elat && e.elon == e.elon; } public String toString() { return "(" + slat + ", " + slon + "," + elat + "," + elon + ")"; } } public static enum EType { invalid, node, way, relation, area } public static class Member { EType type; long ref; String role; } public static class Geometry { double lat; double lon; } public static class Element { EType type; long id; Map<String, String> tags; long[] nodes; Member[] members; Geometry[] geometry; } public static class Data { float version; String generator; Map<String, String> osm3s; List<Element> elements; } public static void main(String[] args) { } }
140953_15
package de.andlabs.teleporter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Handler; import android.os.Parcelable; import android.util.Log; import de.andlabs.teleporter.plugin.ITeleporterPlugIn; public class QueryMultiplexer { private static final String TAG = "Multiplexer"; private Place orig; private Place dest; public ArrayList<Ride> rides; public ArrayList<ITeleporterPlugIn> plugIns; private ArrayList<Ride> nextRides; private Map<String, Integer> priorities; private long mLastSearchTimestamp; private BroadcastReceiver mPluginResponseReceiver; private final Context ctx; private Handler mUpdateHandler; private Thread worker; public QueryMultiplexer(Context ctx, Place o, Place d) { this.ctx = ctx; orig = o; dest = d; nextRides = new ArrayList<Ride>(); rides = new ArrayList<Ride>() { @Override public boolean add(Ride object) { if(!contains(object)) return super.add(object); else return false; } @Override public boolean addAll(Collection<? extends Ride> collection) { for(Ride r : collection) if(!contains(r)) super.add(r); return true; } @Override public void add(int index, Ride object) { if(!contains(object)) super.add(index, object); } }; plugIns = new ArrayList<ITeleporterPlugIn>(); SharedPreferences plugInSettings = ctx.getSharedPreferences("plugIns", ctx.MODE_PRIVATE); try { for (String p : plugInSettings.getAll().keySet()) { Log.d(TAG, "plugin "+p); if (plugInSettings.getBoolean(p, false)){ Log.d(TAG, "add plugin "+p); plugIns.add((ITeleporterPlugIn) Class.forName("de.andlabs.teleporter.plugin."+p).newInstance()); } } } catch (Exception e) { Log.e(TAG, "Schade!"); e.printStackTrace(); } priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll(); this.mUpdateHandler = new Handler(); this.mPluginResponseReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "Plugin Response Received."); final int duration = intent.getIntExtra("dur", -1); final Ride ride = new Ride(); ride.duration = duration; ride.orig = orig; ride.dest = dest; ride.mode = Ride.MODE_DRIVE; ride.fun = 1; ride.eco = 1; ride.fast = 5; ride.social = 1; ride.green = 1; mUpdateHandler.post(new Runnable() { @Override public void run() { nextRides.add(ride); } }); } }; this.ctx.registerReceiver(this.mPluginResponseReceiver, new IntentFilter("org.teleporter.intent.action.RECEIVE_RESPONSE")); } public boolean searchLater() { // TODO just query just plugins that ... // TODO use ThreadPoolExecutor ... if (worker != null && worker.isAlive()) return false; worker = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub for (ITeleporterPlugIn p : plugIns) { Log.d(TAG, "query plugin "+p); final long requestTimestamp; if(mLastSearchTimestamp == 0 ) { requestTimestamp = System.currentTimeMillis(); } else { requestTimestamp = mLastSearchTimestamp + 300000; // 5 Minutes } nextRides.addAll(p.find(orig, dest, new Date(requestTimestamp))); mLastSearchTimestamp = requestTimestamp; mUpdateHandler.post(new Runnable() { @Override public void run() { rides.addAll(nextRides); nextRides.clear(); ((RidesActivity)ctx).datasetChanged(); } }); } Intent requestIntent = new Intent("org.teleporter.intent.action.RECEIVE_REQUEST"); requestIntent.putExtra("origLatitude", orig.lat); requestIntent.putExtra("origLongitude", orig.lon); requestIntent.putExtra("destLatitude", dest.lat); requestIntent.putExtra("destLongitude", dest.lon); ctx.sendBroadcast(requestIntent); } }); worker.start(); return true; } public void sort() { priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll(); // Collections.sort(rides, new Comparator<Ride>() { // // @Override // public int compare(Ride r1, Ride r2) { // // TODO Neue Faktor für Score: "Quickness" (Abfahrtszeit minus Jetzt) // // TODO Faktoren normalisieren // int score1= r1.fun * priorities.get("fun") + // r1.eco * priorities.get("eco") + // r1.fast * priorities.get("fast") + // r1.green * priorities.get("green") + // r1.social * priorities.get("social"); // int score2= r2.fun * priorities.get("fun") + // r2.eco * priorities.get("eco") + // r2.fast * priorities.get("fast") + // r2.green * priorities.get("green") + // r2.social * priorities.get("social"); // // Log.d("aha", "score1: "+score1 + ", score2: "+score2); // if (score1 < score2) // return 1; // else if (score1 > score2) // return -1; // else { // if (r1.dep.after(r2.dep)) // return 1; // if (r1.dep.before(r2.dep)) // return -1; // return 0; // } // } // }); } }
orangeman/teleportr
src/de/andlabs/teleporter/QueryMultiplexer.java
1,965
// r2.green * priorities.get("green") +
line_comment
nl
package de.andlabs.teleporter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Handler; import android.os.Parcelable; import android.util.Log; import de.andlabs.teleporter.plugin.ITeleporterPlugIn; public class QueryMultiplexer { private static final String TAG = "Multiplexer"; private Place orig; private Place dest; public ArrayList<Ride> rides; public ArrayList<ITeleporterPlugIn> plugIns; private ArrayList<Ride> nextRides; private Map<String, Integer> priorities; private long mLastSearchTimestamp; private BroadcastReceiver mPluginResponseReceiver; private final Context ctx; private Handler mUpdateHandler; private Thread worker; public QueryMultiplexer(Context ctx, Place o, Place d) { this.ctx = ctx; orig = o; dest = d; nextRides = new ArrayList<Ride>(); rides = new ArrayList<Ride>() { @Override public boolean add(Ride object) { if(!contains(object)) return super.add(object); else return false; } @Override public boolean addAll(Collection<? extends Ride> collection) { for(Ride r : collection) if(!contains(r)) super.add(r); return true; } @Override public void add(int index, Ride object) { if(!contains(object)) super.add(index, object); } }; plugIns = new ArrayList<ITeleporterPlugIn>(); SharedPreferences plugInSettings = ctx.getSharedPreferences("plugIns", ctx.MODE_PRIVATE); try { for (String p : plugInSettings.getAll().keySet()) { Log.d(TAG, "plugin "+p); if (plugInSettings.getBoolean(p, false)){ Log.d(TAG, "add plugin "+p); plugIns.add((ITeleporterPlugIn) Class.forName("de.andlabs.teleporter.plugin."+p).newInstance()); } } } catch (Exception e) { Log.e(TAG, "Schade!"); e.printStackTrace(); } priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll(); this.mUpdateHandler = new Handler(); this.mPluginResponseReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "Plugin Response Received."); final int duration = intent.getIntExtra("dur", -1); final Ride ride = new Ride(); ride.duration = duration; ride.orig = orig; ride.dest = dest; ride.mode = Ride.MODE_DRIVE; ride.fun = 1; ride.eco = 1; ride.fast = 5; ride.social = 1; ride.green = 1; mUpdateHandler.post(new Runnable() { @Override public void run() { nextRides.add(ride); } }); } }; this.ctx.registerReceiver(this.mPluginResponseReceiver, new IntentFilter("org.teleporter.intent.action.RECEIVE_RESPONSE")); } public boolean searchLater() { // TODO just query just plugins that ... // TODO use ThreadPoolExecutor ... if (worker != null && worker.isAlive()) return false; worker = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub for (ITeleporterPlugIn p : plugIns) { Log.d(TAG, "query plugin "+p); final long requestTimestamp; if(mLastSearchTimestamp == 0 ) { requestTimestamp = System.currentTimeMillis(); } else { requestTimestamp = mLastSearchTimestamp + 300000; // 5 Minutes } nextRides.addAll(p.find(orig, dest, new Date(requestTimestamp))); mLastSearchTimestamp = requestTimestamp; mUpdateHandler.post(new Runnable() { @Override public void run() { rides.addAll(nextRides); nextRides.clear(); ((RidesActivity)ctx).datasetChanged(); } }); } Intent requestIntent = new Intent("org.teleporter.intent.action.RECEIVE_REQUEST"); requestIntent.putExtra("origLatitude", orig.lat); requestIntent.putExtra("origLongitude", orig.lon); requestIntent.putExtra("destLatitude", dest.lat); requestIntent.putExtra("destLongitude", dest.lon); ctx.sendBroadcast(requestIntent); } }); worker.start(); return true; } public void sort() { priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll(); // Collections.sort(rides, new Comparator<Ride>() { // // @Override // public int compare(Ride r1, Ride r2) { // // TODO Neue Faktor für Score: "Quickness" (Abfahrtszeit minus Jetzt) // // TODO Faktoren normalisieren // int score1= r1.fun * priorities.get("fun") + // r1.eco * priorities.get("eco") + // r1.fast * priorities.get("fast") + // r1.green * priorities.get("green") + // r1.social * priorities.get("social"); // int score2= r2.fun * priorities.get("fun") + // r2.eco * priorities.get("eco") + // r2.fast * priorities.get("fast") + // r2.green *<SUF> // r2.social * priorities.get("social"); // // Log.d("aha", "score1: "+score1 + ", score2: "+score2); // if (score1 < score2) // return 1; // else if (score1 > score2) // return -1; // else { // if (r1.dep.after(r2.dep)) // return 1; // if (r1.dep.before(r2.dep)) // return -1; // return 0; // } // } // }); } }
93688_25
package app.organicmaps.util; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.style.AbsoluteSizeSpan; import android.util.AndroidRuntimeException; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.DimenRes; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.core.app.NavUtils; import androidx.core.os.BundleCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import com.google.android.material.snackbar.Snackbar; import app.organicmaps.BuildConfig; import app.organicmaps.MwmActivity; import app.organicmaps.MwmApplication; import app.organicmaps.R; import app.organicmaps.util.concurrency.UiThread; import app.organicmaps.util.log.Logger; import app.organicmaps.util.log.LogsManager; import java.io.Closeable; import java.io.IOException; import java.lang.ref.WeakReference; import java.text.DecimalFormatSymbols; import java.util.Currency; import java.util.Locale; import java.util.Map; @Keep public class Utils { private static final String TAG = Utils.class.getSimpleName(); @StringRes public static final int INVALID_ID = 0; public static final String UTF_8 = "utf-8"; public static final String TEXT_HTML = "text/html; charset=utf-8"; private Utils() { } /** * Enable to keep screen on. * Disable to let system turn it off automatically. */ public static void keepScreenOn(boolean enable, Window w) { Logger.i(TAG, "KeepScreenOn = " + enable + " window = " + w); if (enable) w.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); else w.clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private static void showOnLockScreenOld(boolean enable, Activity activity) { if (enable) activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); else activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); } public static void showOnLockScreen(boolean enable, Activity activity) { Logger.i(TAG, "showOnLockScreen = " + enable + " window = " + activity.getWindow()); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O_MR1) showOnLockScreenOld(enable, activity); else activity.setShowWhenLocked(enable); } public static void showSnackbar(@NonNull View view, @NonNull String message) { Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG); setSnackbarMaxLines(snackbar, 3); snackbar.show(); } public static void showSnackbarAbove(@NonNull View view, @NonNull View viewAbove, @NonNull String message) { Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG); setSnackbarMaxLines(snackbar, 3); snackbar.setAnchorView(viewAbove); snackbar.show(); } private static void setSnackbarMaxLines(@NonNull final Snackbar snackbar, final int maxLinesCount) { TextView snackTextView = snackbar.getView().findViewById(com.google.android.material.R.id.snackbar_text); snackTextView.setMaxLines(maxLinesCount); } public static void showSnackbar(@NonNull Context context, @NonNull View view, int messageResId) { showSnackbar(context, view, null, messageResId); } public static void showSnackbar(@NonNull Context context, @NonNull View view, @Nullable View viewAbove, int messageResId) { final String message = context.getString(messageResId); if (viewAbove == null) showSnackbar(view, message); else showSnackbarAbove(view, viewAbove, message); } @SuppressWarnings("deprecated") private static @Nullable ResolveInfo resolveActivity(@NonNull PackageManager pm, @NonNull Intent intent, int flags) { return pm.resolveActivity(intent, flags); } public static boolean isIntentSupported(@NonNull Context context, @NonNull Intent intent) { final PackageManager pm = context.getPackageManager(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return resolveActivity(pm, intent, 0) != null; return pm.resolveActivity(intent, PackageManager.ResolveInfoFlags.of(0)) != null; } public static @Nullable Intent makeSystemLocationSettingIntent(@NonNull Context context) { Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); if (isIntentSupported(context, intent)) return intent; intent = new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS); if (isIntentSupported(context, intent)) return intent; intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", context.getPackageName(), null); intent.setData(uri); if (isIntentSupported(context, intent)) return intent; return null; } public static void checkNotNull(Object object) { if (null == object) throw new NullPointerException("Argument here must not be NULL"); } public static void copyTextToClipboard(Context context, String text) { final android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); final ClipData clip = ClipData.newPlainText("Organic Maps: " + text, text); clipboard.setPrimaryClip(clip); } public static <K, V> String mapPrettyPrint(Map<K, V> map) { if (map == null) return "[null]"; if (map.isEmpty()) return "[]"; String joined = ""; for (final K key : map.keySet()) { final String keyVal = key + "=" + map.get(key); if (!joined.isEmpty()) joined = TextUtils.join(",", new Object[]{joined, keyVal}); else joined = keyVal; } return "[" + joined + "]"; } public static Uri buildMailUri(String to, String subject, String body) { String uriString = Constants.Url.MAILTO_SCHEME + Uri.encode(to) + Constants.Url.MAIL_SUBJECT + Uri.encode(subject) + Constants.Url.MAIL_BODY + Uri.encode(body); return Uri.parse(uriString); } public static void openAppInMarket(Activity activity, String url) { final Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); try { activity.startActivity(marketIntent); } catch (ActivityNotFoundException e) { Logger.e(TAG, "Failed to start activity", e); } } public static void showFacebookPage(Activity activity) { try { // Exception is thrown if we don't have installed Facebook application. getPackageInfo(activity.getPackageManager(), Constants.Package.FB_PACKAGE, 0); activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.Url.FB_OM_COMMUNITY_NATIVE))); } catch (final Exception e) { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.Url.FB_OM_COMMUNITY_HTTP))); } } public static void openUrl(@NonNull Context context, @Nullable String url) { if (TextUtils.isEmpty(url)) return; final Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = isHttpOrHttpsScheme(url) ? Uri.parse(url) : new Uri.Builder().scheme("http").appendEncodedPath(url).build(); intent.setData(uri); try { context.startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(context, context.getString(R.string.browser_not_available), Toast.LENGTH_LONG).show(); Logger.e(TAG, "ActivityNotFoundException", e); } catch (AndroidRuntimeException e) { Logger.e(TAG, "AndroidRuntimeException", e); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } public static boolean openUri(@NonNull Context context, @NonNull Uri uri) { final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(uri); try { context.startActivity(intent); return true; } catch (ActivityNotFoundException e) { Logger.e(TAG, "ActivityNotFoundException", e); return false; } catch (AndroidRuntimeException e) { Logger.e(TAG, "AndroidRuntimeException", e); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); return false; } } private static boolean isHttpOrHttpsScheme(@NonNull String url) { return url.startsWith("http://") || url.startsWith("https://"); } public static void closeSafely(@NonNull Closeable... closeable) { for (Closeable each : closeable) { if (each != null) { try { each.close(); } catch (IOException e) { Logger.e(TAG, "Failed to close '" + each + "'", e); } } } } // subject is optional (could be an empty string). /** * @param subject could be an empty string */ public static void sendBugReport(@NonNull Activity activity, @NonNull String subject, @NonNull String body) { subject = "Organic Maps Bugreport" + (TextUtils.isEmpty(subject) ? "" : ": " + subject); LogsManager.INSTANCE.zipLogs(new SupportInfoWithLogsCallback(activity, subject, body, Constants.Email.SUPPORT)); } // TODO: Don't send logs with general feedback, send system information only (version, device name, connectivity, etc.) public static void sendFeedback(@NonNull Activity activity) { LogsManager.INSTANCE.zipLogs(new SupportInfoWithLogsCallback(activity, "Organic Maps Feedback", "", Constants.Email.SUPPORT)); } public static void navigateToParent(@NonNull Activity activity) { if (activity instanceof MwmActivity) ((MwmActivity) activity).customOnNavigateUp(); else NavUtils.navigateUpFromSameTask(activity); } public static SpannableStringBuilder formatTime(Context context, @DimenRes int size, @DimenRes int units, String dimension, String unitText) { final SpannableStringBuilder res = new SpannableStringBuilder(dimension).append("\u00A0").append(unitText); res.setSpan(new AbsoluteSizeSpan(UiUtils.dimen(context, size), false), 0, dimension.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); res.setSpan(new AbsoluteSizeSpan(UiUtils.dimen(context, units), false), dimension.length(), res.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return res; } @NonNull public static Spannable formatDistance(Context context, @NonNull Distance distance) { final SpannableStringBuilder res = new SpannableStringBuilder(distance.toString(context)); res.setSpan( new AbsoluteSizeSpan(UiUtils.dimen(context, R.dimen.text_size_nav_number), false), 0, distance.mDistanceStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); res.setSpan( new AbsoluteSizeSpan(UiUtils.dimen(context, R.dimen.text_size_nav_dimension), false), distance.mDistanceStr.length(), res.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return res; } public static void sendTo(@NonNull Context context, @NonNull String email) { sendTo(context, email, "", ""); } public static void sendTo(@NonNull Context context, @NonNull String email, @NonNull String subject) { sendTo(context, email, subject, ""); } public static void sendTo(@NonNull Context context, @NonNull String email, @NonNull String subject, @NonNull String body) { Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setData(Utils.buildMailUri(email, subject, body)); context.startActivity(intent); } public static void callPhone(@NonNull Context context, @NonNull String phone) { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phone)); try { context.startActivity(intent); } catch (ActivityNotFoundException e) { Logger.e(TAG, "Failed to call phone", e); } } // Called from JNI. @Keep @SuppressWarnings("unused") @Nullable public static String getCurrencyCode() { Locale[] locales = { Locale.getDefault(), Locale.US }; for (Locale locale : locales) { Currency currency = getCurrencyForLocale(locale); if (currency != null) return currency.getCurrencyCode(); } return null; } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getCountryCode() { return Locale.getDefault().getCountry(); } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getLanguageCode() { return Locale.getDefault().getLanguage(); } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getDecimalSeparator() { return String.valueOf(DecimalFormatSymbols.getInstance().getDecimalSeparator()); } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getGroupingSeparator() { return String.valueOf(DecimalFormatSymbols.getInstance().getGroupingSeparator()); } @Nullable public static Currency getCurrencyForLocale(@NonNull Locale locale) { try { return Currency.getInstance(locale); } catch (Throwable e) { Logger.e(TAG, "Failed to obtain a currency for locale: " + locale, e); return null; } } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getCurrencySymbol(@NonNull String currencyCode) { try { return Currency.getInstance(currencyCode).getSymbol(Locale.getDefault()); } catch (Throwable e) { Logger.e(TAG, "Failed to obtain currency symbol by currency code = " + currencyCode, e); } return currencyCode; } static String makeUrlSafe(@NonNull final String url) { return url.replaceAll("(token|password|key)=([^&]+)", "***"); } @StringRes @SuppressLint("DiscouragedApi") public static int getStringIdByKey(@NonNull Context context, @NonNull String key) { try { Resources res = context.getResources(); @StringRes int nameId = res.getIdentifier(key, "string", context.getPackageName()); if (nameId == INVALID_ID || nameId == View.NO_ID) throw new Resources.NotFoundException("String id '" + key + "' is not found"); return nameId; } catch (RuntimeException e) { Logger.e(TAG, "Failed to get string with id '" + key + "'", e); if (BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("beta")) { Toast.makeText(context, "Add string id for '" + key + "'!", Toast.LENGTH_LONG).show(); } } return INVALID_ID; } /** * Returns a string value for the specified key. If the value is not found then its key will be * returned. * * @return string value or its key if there is no string for the specified key. */ // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getStringValueByKey(@NonNull Context context, @NonNull String key) { try { return context.getString(getStringIdByKey(context, key)); } catch (Resources.NotFoundException e) { Logger.e(TAG, "Failed to get value for string '" + key + "'", e); } return key; } /** * Returns a name for a new bookmark created off the current GPS location. * The name includes current time and date in locale-specific format. * * @return bookmark name with time and date. */ // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getMyPositionBookmarkName(@NonNull Context context) { return DateUtils.formatDateTime(context, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR); } // Called from JNI. @NonNull @Keep @SuppressWarnings("unused") public static String getDeviceName() { return Build.MANUFACTURER; } // Called from JNI. @NonNull @Keep @SuppressWarnings("unused") public static String getDeviceModel() { return Build.MODEL; } // Called from JNI. @NonNull @Keep @SuppressWarnings("unused") public static String getVersion() { return BuildConfig.VERSION_NAME; } // Called from JNI. @Keep @SuppressWarnings("unused") public static int getIntVersion() { // Please sync with getVersion() in build.gradle // - % 100000000 removes prefix for special markets, e.g Huawei. // - / 100 removes the number of commits in the current day. return (BuildConfig.VERSION_CODE % 1_00_00_00_00) / 100; } public static void detachFragmentIfCoreNotInitialized(@NonNull Context context, @NonNull Fragment fragment) { if (MwmApplication.from(context).arePlatformAndCoreInitialized()) return; FragmentManager manager = fragment.getFragmentManager(); if (manager == null) return; manager.beginTransaction().detach(fragment).commit(); } public static String capitalize(@Nullable String src) { if (TextUtils.isEmpty(src)) return src; if (src.length() == 1) return Character.toString(Character.toUpperCase(src.charAt(0))); return Character.toUpperCase(src.charAt(0)) + src.substring(1); } public static String unCapitalize(@Nullable String src) { if (TextUtils.isEmpty(src)) return src; if (src.length() == 1) return Character.toString(Character.toLowerCase(src.charAt(0))); return Character.toLowerCase(src.charAt(0)) + src.substring(1); } public interface Proc<T> { void invoke(@NonNull T param); } @NonNull private static String getLocalizedFeatureByKey(@NonNull Context context, @NonNull String key) { return getStringValueByKey(context, key); } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getLocalizedFeatureType(@NonNull Context context, @Nullable String type) { if (TextUtils.isEmpty(type)) return ""; String key = "type." + type.replace('-', '.') .replace(':', '_'); return getLocalizedFeatureByKey(context, key); } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getLocalizedBrand(@NonNull Context context, @Nullable String brand) { if (TextUtils.isEmpty(brand)) return ""; try { @StringRes int nameId = context.getResources().getIdentifier("brand." + brand, "string", context.getPackageName()); if (nameId == INVALID_ID || nameId == View.NO_ID) return brand; return context.getString(nameId); } catch (Resources.NotFoundException e) { } return brand; } private static class SupportInfoWithLogsCallback implements LogsManager.OnZipCompletedListener { @NonNull private final WeakReference<Activity> mActivityRef; @NonNull private final String mSubject; @NonNull private final String mBody; @NonNull private final String mEmail; private SupportInfoWithLogsCallback(@NonNull Activity activity, @NonNull String subject, @NonNull String body, @NonNull String email) { mActivityRef = new WeakReference<>(activity); mSubject = subject; mBody = body; mEmail = email; } @Override public void onCompleted(final boolean success, @Nullable final String zipPath) { // TODO: delete zip file after its sent. UiThread.run(() -> { final Activity activity = mActivityRef.get(); if (activity == null) return; final Intent intent = new Intent(Intent.ACTION_SEND); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { mEmail }); intent.putExtra(Intent.EXTRA_SUBJECT, "[" + BuildConfig.VERSION_NAME + "] " + mSubject); // TODO: Send a short text attachment with system info and logs if zipping logs failed if (success) { final Uri uri = StorageUtils.getUriForFilePath(activity, zipPath); intent.putExtra(Intent.EXTRA_STREAM, uri); // Properly set permissions for intent, see // https://developer.android.com/reference/androidx/core/content/FileProvider#include-the-permission-in-an-intent intent.setDataAndType(uri, "message/rfc822"); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { intent.setClipData(ClipData.newRawUri("", uri)); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } } else { intent.setType("message/rfc822"); } // Do this so some email clients don't complain about empty body. intent.putExtra(Intent.EXTRA_TEXT, mBody); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Logger.w(TAG, "No activities found which can handle sending a support message.", e); } }); } } public static <T> T getParcelable(@NonNull Bundle in, @Nullable String key, @NonNull Class<T> clazz) { in.setClassLoader(clazz.getClassLoader()); return BundleCompat.getParcelable(in, key, clazz); } @SuppressWarnings("deprecation") private static Spanned fromHtmlOld(@NonNull String htmlDescription) { return Html.fromHtml(htmlDescription); } public static Spanned fromHtml(@NonNull String htmlDescription) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) return fromHtmlOld(htmlDescription); return Html.fromHtml(htmlDescription, Html.FROM_HTML_MODE_LEGACY); } @SuppressWarnings("deprecation") private static ApplicationInfo getApplicationInfoOld(@NonNull PackageManager manager, @NonNull String packageName, int flags) throws PackageManager.NameNotFoundException { return manager.getApplicationInfo(packageName, flags); } public static ApplicationInfo getApplicationInfo(@NonNull PackageManager manager, @NonNull String packageName, int flags) throws PackageManager.NameNotFoundException { if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return getApplicationInfoOld(manager, packageName, flags); return manager.getApplicationInfo(packageName, PackageManager.ApplicationInfoFlags.of(flags)); } @SuppressWarnings("deprecation") private static PackageInfo getPackageInfoOld(@NonNull PackageManager manager, @NonNull String packageName, int flags) throws PackageManager.NameNotFoundException { return manager.getPackageInfo(packageName, flags); } public static PackageInfo getPackageInfo(@NonNull PackageManager manager, @NonNull String packageName, int flags) throws PackageManager.NameNotFoundException { if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return getPackageInfoOld(manager, packageName, flags); return manager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flags)); } }
organicmaps/organicmaps
android/app/src/main/java/app/organicmaps/util/Utils.java
7,639
// TODO: delete zip file after its sent.
line_comment
nl
package app.organicmaps.util; import android.annotation.SuppressLint; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.style.AbsoluteSizeSpan; import android.util.AndroidRuntimeException; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.DimenRes; import androidx.annotation.Keep; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import androidx.core.app.NavUtils; import androidx.core.os.BundleCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import com.google.android.material.snackbar.Snackbar; import app.organicmaps.BuildConfig; import app.organicmaps.MwmActivity; import app.organicmaps.MwmApplication; import app.organicmaps.R; import app.organicmaps.util.concurrency.UiThread; import app.organicmaps.util.log.Logger; import app.organicmaps.util.log.LogsManager; import java.io.Closeable; import java.io.IOException; import java.lang.ref.WeakReference; import java.text.DecimalFormatSymbols; import java.util.Currency; import java.util.Locale; import java.util.Map; @Keep public class Utils { private static final String TAG = Utils.class.getSimpleName(); @StringRes public static final int INVALID_ID = 0; public static final String UTF_8 = "utf-8"; public static final String TEXT_HTML = "text/html; charset=utf-8"; private Utils() { } /** * Enable to keep screen on. * Disable to let system turn it off automatically. */ public static void keepScreenOn(boolean enable, Window w) { Logger.i(TAG, "KeepScreenOn = " + enable + " window = " + w); if (enable) w.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); else w.clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } private static void showOnLockScreenOld(boolean enable, Activity activity) { if (enable) activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); else activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); } public static void showOnLockScreen(boolean enable, Activity activity) { Logger.i(TAG, "showOnLockScreen = " + enable + " window = " + activity.getWindow()); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O_MR1) showOnLockScreenOld(enable, activity); else activity.setShowWhenLocked(enable); } public static void showSnackbar(@NonNull View view, @NonNull String message) { Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG); setSnackbarMaxLines(snackbar, 3); snackbar.show(); } public static void showSnackbarAbove(@NonNull View view, @NonNull View viewAbove, @NonNull String message) { Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG); setSnackbarMaxLines(snackbar, 3); snackbar.setAnchorView(viewAbove); snackbar.show(); } private static void setSnackbarMaxLines(@NonNull final Snackbar snackbar, final int maxLinesCount) { TextView snackTextView = snackbar.getView().findViewById(com.google.android.material.R.id.snackbar_text); snackTextView.setMaxLines(maxLinesCount); } public static void showSnackbar(@NonNull Context context, @NonNull View view, int messageResId) { showSnackbar(context, view, null, messageResId); } public static void showSnackbar(@NonNull Context context, @NonNull View view, @Nullable View viewAbove, int messageResId) { final String message = context.getString(messageResId); if (viewAbove == null) showSnackbar(view, message); else showSnackbarAbove(view, viewAbove, message); } @SuppressWarnings("deprecated") private static @Nullable ResolveInfo resolveActivity(@NonNull PackageManager pm, @NonNull Intent intent, int flags) { return pm.resolveActivity(intent, flags); } public static boolean isIntentSupported(@NonNull Context context, @NonNull Intent intent) { final PackageManager pm = context.getPackageManager(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return resolveActivity(pm, intent, 0) != null; return pm.resolveActivity(intent, PackageManager.ResolveInfoFlags.of(0)) != null; } public static @Nullable Intent makeSystemLocationSettingIntent(@NonNull Context context) { Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); if (isIntentSupported(context, intent)) return intent; intent = new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS); if (isIntentSupported(context, intent)) return intent; intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", context.getPackageName(), null); intent.setData(uri); if (isIntentSupported(context, intent)) return intent; return null; } public static void checkNotNull(Object object) { if (null == object) throw new NullPointerException("Argument here must not be NULL"); } public static void copyTextToClipboard(Context context, String text) { final android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); final ClipData clip = ClipData.newPlainText("Organic Maps: " + text, text); clipboard.setPrimaryClip(clip); } public static <K, V> String mapPrettyPrint(Map<K, V> map) { if (map == null) return "[null]"; if (map.isEmpty()) return "[]"; String joined = ""; for (final K key : map.keySet()) { final String keyVal = key + "=" + map.get(key); if (!joined.isEmpty()) joined = TextUtils.join(",", new Object[]{joined, keyVal}); else joined = keyVal; } return "[" + joined + "]"; } public static Uri buildMailUri(String to, String subject, String body) { String uriString = Constants.Url.MAILTO_SCHEME + Uri.encode(to) + Constants.Url.MAIL_SUBJECT + Uri.encode(subject) + Constants.Url.MAIL_BODY + Uri.encode(body); return Uri.parse(uriString); } public static void openAppInMarket(Activity activity, String url) { final Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); try { activity.startActivity(marketIntent); } catch (ActivityNotFoundException e) { Logger.e(TAG, "Failed to start activity", e); } } public static void showFacebookPage(Activity activity) { try { // Exception is thrown if we don't have installed Facebook application. getPackageInfo(activity.getPackageManager(), Constants.Package.FB_PACKAGE, 0); activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.Url.FB_OM_COMMUNITY_NATIVE))); } catch (final Exception e) { activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.Url.FB_OM_COMMUNITY_HTTP))); } } public static void openUrl(@NonNull Context context, @Nullable String url) { if (TextUtils.isEmpty(url)) return; final Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = isHttpOrHttpsScheme(url) ? Uri.parse(url) : new Uri.Builder().scheme("http").appendEncodedPath(url).build(); intent.setData(uri); try { context.startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(context, context.getString(R.string.browser_not_available), Toast.LENGTH_LONG).show(); Logger.e(TAG, "ActivityNotFoundException", e); } catch (AndroidRuntimeException e) { Logger.e(TAG, "AndroidRuntimeException", e); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } public static boolean openUri(@NonNull Context context, @NonNull Uri uri) { final Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(uri); try { context.startActivity(intent); return true; } catch (ActivityNotFoundException e) { Logger.e(TAG, "ActivityNotFoundException", e); return false; } catch (AndroidRuntimeException e) { Logger.e(TAG, "AndroidRuntimeException", e); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); return false; } } private static boolean isHttpOrHttpsScheme(@NonNull String url) { return url.startsWith("http://") || url.startsWith("https://"); } public static void closeSafely(@NonNull Closeable... closeable) { for (Closeable each : closeable) { if (each != null) { try { each.close(); } catch (IOException e) { Logger.e(TAG, "Failed to close '" + each + "'", e); } } } } // subject is optional (could be an empty string). /** * @param subject could be an empty string */ public static void sendBugReport(@NonNull Activity activity, @NonNull String subject, @NonNull String body) { subject = "Organic Maps Bugreport" + (TextUtils.isEmpty(subject) ? "" : ": " + subject); LogsManager.INSTANCE.zipLogs(new SupportInfoWithLogsCallback(activity, subject, body, Constants.Email.SUPPORT)); } // TODO: Don't send logs with general feedback, send system information only (version, device name, connectivity, etc.) public static void sendFeedback(@NonNull Activity activity) { LogsManager.INSTANCE.zipLogs(new SupportInfoWithLogsCallback(activity, "Organic Maps Feedback", "", Constants.Email.SUPPORT)); } public static void navigateToParent(@NonNull Activity activity) { if (activity instanceof MwmActivity) ((MwmActivity) activity).customOnNavigateUp(); else NavUtils.navigateUpFromSameTask(activity); } public static SpannableStringBuilder formatTime(Context context, @DimenRes int size, @DimenRes int units, String dimension, String unitText) { final SpannableStringBuilder res = new SpannableStringBuilder(dimension).append("\u00A0").append(unitText); res.setSpan(new AbsoluteSizeSpan(UiUtils.dimen(context, size), false), 0, dimension.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); res.setSpan(new AbsoluteSizeSpan(UiUtils.dimen(context, units), false), dimension.length(), res.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return res; } @NonNull public static Spannable formatDistance(Context context, @NonNull Distance distance) { final SpannableStringBuilder res = new SpannableStringBuilder(distance.toString(context)); res.setSpan( new AbsoluteSizeSpan(UiUtils.dimen(context, R.dimen.text_size_nav_number), false), 0, distance.mDistanceStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); res.setSpan( new AbsoluteSizeSpan(UiUtils.dimen(context, R.dimen.text_size_nav_dimension), false), distance.mDistanceStr.length(), res.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return res; } public static void sendTo(@NonNull Context context, @NonNull String email) { sendTo(context, email, "", ""); } public static void sendTo(@NonNull Context context, @NonNull String email, @NonNull String subject) { sendTo(context, email, subject, ""); } public static void sendTo(@NonNull Context context, @NonNull String email, @NonNull String subject, @NonNull String body) { Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setData(Utils.buildMailUri(email, subject, body)); context.startActivity(intent); } public static void callPhone(@NonNull Context context, @NonNull String phone) { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse("tel:" + phone)); try { context.startActivity(intent); } catch (ActivityNotFoundException e) { Logger.e(TAG, "Failed to call phone", e); } } // Called from JNI. @Keep @SuppressWarnings("unused") @Nullable public static String getCurrencyCode() { Locale[] locales = { Locale.getDefault(), Locale.US }; for (Locale locale : locales) { Currency currency = getCurrencyForLocale(locale); if (currency != null) return currency.getCurrencyCode(); } return null; } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getCountryCode() { return Locale.getDefault().getCountry(); } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getLanguageCode() { return Locale.getDefault().getLanguage(); } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getDecimalSeparator() { return String.valueOf(DecimalFormatSymbols.getInstance().getDecimalSeparator()); } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getGroupingSeparator() { return String.valueOf(DecimalFormatSymbols.getInstance().getGroupingSeparator()); } @Nullable public static Currency getCurrencyForLocale(@NonNull Locale locale) { try { return Currency.getInstance(locale); } catch (Throwable e) { Logger.e(TAG, "Failed to obtain a currency for locale: " + locale, e); return null; } } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getCurrencySymbol(@NonNull String currencyCode) { try { return Currency.getInstance(currencyCode).getSymbol(Locale.getDefault()); } catch (Throwable e) { Logger.e(TAG, "Failed to obtain currency symbol by currency code = " + currencyCode, e); } return currencyCode; } static String makeUrlSafe(@NonNull final String url) { return url.replaceAll("(token|password|key)=([^&]+)", "***"); } @StringRes @SuppressLint("DiscouragedApi") public static int getStringIdByKey(@NonNull Context context, @NonNull String key) { try { Resources res = context.getResources(); @StringRes int nameId = res.getIdentifier(key, "string", context.getPackageName()); if (nameId == INVALID_ID || nameId == View.NO_ID) throw new Resources.NotFoundException("String id '" + key + "' is not found"); return nameId; } catch (RuntimeException e) { Logger.e(TAG, "Failed to get string with id '" + key + "'", e); if (BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("beta")) { Toast.makeText(context, "Add string id for '" + key + "'!", Toast.LENGTH_LONG).show(); } } return INVALID_ID; } /** * Returns a string value for the specified key. If the value is not found then its key will be * returned. * * @return string value or its key if there is no string for the specified key. */ // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getStringValueByKey(@NonNull Context context, @NonNull String key) { try { return context.getString(getStringIdByKey(context, key)); } catch (Resources.NotFoundException e) { Logger.e(TAG, "Failed to get value for string '" + key + "'", e); } return key; } /** * Returns a name for a new bookmark created off the current GPS location. * The name includes current time and date in locale-specific format. * * @return bookmark name with time and date. */ // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getMyPositionBookmarkName(@NonNull Context context) { return DateUtils.formatDateTime(context, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR); } // Called from JNI. @NonNull @Keep @SuppressWarnings("unused") public static String getDeviceName() { return Build.MANUFACTURER; } // Called from JNI. @NonNull @Keep @SuppressWarnings("unused") public static String getDeviceModel() { return Build.MODEL; } // Called from JNI. @NonNull @Keep @SuppressWarnings("unused") public static String getVersion() { return BuildConfig.VERSION_NAME; } // Called from JNI. @Keep @SuppressWarnings("unused") public static int getIntVersion() { // Please sync with getVersion() in build.gradle // - % 100000000 removes prefix for special markets, e.g Huawei. // - / 100 removes the number of commits in the current day. return (BuildConfig.VERSION_CODE % 1_00_00_00_00) / 100; } public static void detachFragmentIfCoreNotInitialized(@NonNull Context context, @NonNull Fragment fragment) { if (MwmApplication.from(context).arePlatformAndCoreInitialized()) return; FragmentManager manager = fragment.getFragmentManager(); if (manager == null) return; manager.beginTransaction().detach(fragment).commit(); } public static String capitalize(@Nullable String src) { if (TextUtils.isEmpty(src)) return src; if (src.length() == 1) return Character.toString(Character.toUpperCase(src.charAt(0))); return Character.toUpperCase(src.charAt(0)) + src.substring(1); } public static String unCapitalize(@Nullable String src) { if (TextUtils.isEmpty(src)) return src; if (src.length() == 1) return Character.toString(Character.toLowerCase(src.charAt(0))); return Character.toLowerCase(src.charAt(0)) + src.substring(1); } public interface Proc<T> { void invoke(@NonNull T param); } @NonNull private static String getLocalizedFeatureByKey(@NonNull Context context, @NonNull String key) { return getStringValueByKey(context, key); } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getLocalizedFeatureType(@NonNull Context context, @Nullable String type) { if (TextUtils.isEmpty(type)) return ""; String key = "type." + type.replace('-', '.') .replace(':', '_'); return getLocalizedFeatureByKey(context, key); } // Called from JNI. @Keep @SuppressWarnings("unused") @NonNull public static String getLocalizedBrand(@NonNull Context context, @Nullable String brand) { if (TextUtils.isEmpty(brand)) return ""; try { @StringRes int nameId = context.getResources().getIdentifier("brand." + brand, "string", context.getPackageName()); if (nameId == INVALID_ID || nameId == View.NO_ID) return brand; return context.getString(nameId); } catch (Resources.NotFoundException e) { } return brand; } private static class SupportInfoWithLogsCallback implements LogsManager.OnZipCompletedListener { @NonNull private final WeakReference<Activity> mActivityRef; @NonNull private final String mSubject; @NonNull private final String mBody; @NonNull private final String mEmail; private SupportInfoWithLogsCallback(@NonNull Activity activity, @NonNull String subject, @NonNull String body, @NonNull String email) { mActivityRef = new WeakReference<>(activity); mSubject = subject; mBody = body; mEmail = email; } @Override public void onCompleted(final boolean success, @Nullable final String zipPath) { // TODO: delete<SUF> UiThread.run(() -> { final Activity activity = mActivityRef.get(); if (activity == null) return; final Intent intent = new Intent(Intent.ACTION_SEND); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { mEmail }); intent.putExtra(Intent.EXTRA_SUBJECT, "[" + BuildConfig.VERSION_NAME + "] " + mSubject); // TODO: Send a short text attachment with system info and logs if zipping logs failed if (success) { final Uri uri = StorageUtils.getUriForFilePath(activity, zipPath); intent.putExtra(Intent.EXTRA_STREAM, uri); // Properly set permissions for intent, see // https://developer.android.com/reference/androidx/core/content/FileProvider#include-the-permission-in-an-intent intent.setDataAndType(uri, "message/rfc822"); intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { intent.setClipData(ClipData.newRawUri("", uri)); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } } else { intent.setType("message/rfc822"); } // Do this so some email clients don't complain about empty body. intent.putExtra(Intent.EXTRA_TEXT, mBody); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Logger.w(TAG, "No activities found which can handle sending a support message.", e); } }); } } public static <T> T getParcelable(@NonNull Bundle in, @Nullable String key, @NonNull Class<T> clazz) { in.setClassLoader(clazz.getClassLoader()); return BundleCompat.getParcelable(in, key, clazz); } @SuppressWarnings("deprecation") private static Spanned fromHtmlOld(@NonNull String htmlDescription) { return Html.fromHtml(htmlDescription); } public static Spanned fromHtml(@NonNull String htmlDescription) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) return fromHtmlOld(htmlDescription); return Html.fromHtml(htmlDescription, Html.FROM_HTML_MODE_LEGACY); } @SuppressWarnings("deprecation") private static ApplicationInfo getApplicationInfoOld(@NonNull PackageManager manager, @NonNull String packageName, int flags) throws PackageManager.NameNotFoundException { return manager.getApplicationInfo(packageName, flags); } public static ApplicationInfo getApplicationInfo(@NonNull PackageManager manager, @NonNull String packageName, int flags) throws PackageManager.NameNotFoundException { if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return getApplicationInfoOld(manager, packageName, flags); return manager.getApplicationInfo(packageName, PackageManager.ApplicationInfoFlags.of(flags)); } @SuppressWarnings("deprecation") private static PackageInfo getPackageInfoOld(@NonNull PackageManager manager, @NonNull String packageName, int flags) throws PackageManager.NameNotFoundException { return manager.getPackageInfo(packageName, flags); } public static PackageInfo getPackageInfo(@NonNull PackageManager manager, @NonNull String packageName, int flags) throws PackageManager.NameNotFoundException { if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return getPackageInfoOld(manager, packageName, flags); return manager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flags)); } }
142834_1
package net.rhizomik.rhizomer.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.net.*; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.persistence.CascadeType; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import lombok.Data; import net.rhizomik.rhizomer.service.Queries.QueryType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by http://rhizomik.net/~roberto/ */ @Entity @Data public class Dataset { private static final Logger logger = LoggerFactory.getLogger(Dataset.class); @Id private String id; private QueryType queryType = QueryType.OPTIMIZED; private boolean inferenceEnabled = false; private int sampleSize = 0; private double coverage = 0.0; private boolean isPublic = false; @ElementCollection private Set<String> datasetOntologies = new HashSet<>(); @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "dataset", cascade = CascadeType.ALL) @OrderBy("instanceCount DESC") private List<Class> classes = new ArrayList<>(); private String owner; public Dataset() {} public Dataset(String id) { this.id = id; } public Dataset(String id, Set<String> ontologies) throws MalformedURLException { this.id = id; this.datasetOntologies = ontologies; } @JsonIgnore public List<Class> getClasses() { return new ArrayList<>(classes); } public List<Class> getClasses(int top) { int max = Integer.min(top, classes.size()); return new ArrayList<>(classes.subList(0, max)); } public List<Class> getClassesContaining(String containing) { return getClassesContaining(containing, -1); } public List<Class> getClassesContaining(String containing, int top) { Stream<Class> selected = classes.stream(); if (!containing.isEmpty()) selected = classes.stream() .filter(c -> c.getUri().toString().toLowerCase().contains(containing.toLowerCase()) || c.getLabel().toLowerCase().contains(containing.toLowerCase())); if (top >= 0) selected = selected.sorted(Comparator.comparingInt(Class::getInstanceCount).reversed()).limit(top); return selected.collect(Collectors.toList()); } public void setClasses(List<Class> classes) { this.classes.clear(); this.classes.addAll(classes); } public void addClass(Class aClass) { classes.add(aClass); } public void removeClass(Class aClass) { classes.remove(aClass); } public void addDatasetOntology(String ontology) { this.datasetOntologies.add(ontology); } @JsonIgnore public List<String> getDatasetOntologies() { return new ArrayList<>(datasetOntologies); } public void setDatasetOntologies(Set<String> datasetOntologies) { this.datasetOntologies = datasetOntologies; } @JsonIgnore public URI getDatasetUri() { URI datasetURI = null; try { datasetURI = new URI("http://" + InetAddress.getLocalHost().getHostName() + "/dataset/"+getId()); } catch (Exception e) { logger.error(e.getMessage()); } return datasetURI; } @JsonIgnore public URI getDatasetOntologiesGraph() { URI datasetOntologiesGraphURI = null; try { datasetOntologiesGraphURI = new URI(getDatasetUri()+"/ontologies"); } catch (URISyntaxException e) { logger.error(e.getMessage()); } return datasetOntologiesGraphURI; } @JsonIgnore public URI getDatasetInferenceGraph() { URI datasetInferenceGraphURI = null; try { datasetInferenceGraphURI = new URI(getDatasetUri()+"/inference"); } catch (URISyntaxException e) { logger.error(e.getMessage()); } return datasetInferenceGraphURI; } }
oriolaguilar/rhizomerAPI
src/main/java/net/rhizomik/rhizomer/model/Dataset.java
1,207
//" + InetAddress.getLocalHost().getHostName() + "/dataset/"+getId());
line_comment
nl
package net.rhizomik.rhizomer.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.net.*; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.persistence.CascadeType; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import lombok.Data; import net.rhizomik.rhizomer.service.Queries.QueryType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by http://rhizomik.net/~roberto/ */ @Entity @Data public class Dataset { private static final Logger logger = LoggerFactory.getLogger(Dataset.class); @Id private String id; private QueryType queryType = QueryType.OPTIMIZED; private boolean inferenceEnabled = false; private int sampleSize = 0; private double coverage = 0.0; private boolean isPublic = false; @ElementCollection private Set<String> datasetOntologies = new HashSet<>(); @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "dataset", cascade = CascadeType.ALL) @OrderBy("instanceCount DESC") private List<Class> classes = new ArrayList<>(); private String owner; public Dataset() {} public Dataset(String id) { this.id = id; } public Dataset(String id, Set<String> ontologies) throws MalformedURLException { this.id = id; this.datasetOntologies = ontologies; } @JsonIgnore public List<Class> getClasses() { return new ArrayList<>(classes); } public List<Class> getClasses(int top) { int max = Integer.min(top, classes.size()); return new ArrayList<>(classes.subList(0, max)); } public List<Class> getClassesContaining(String containing) { return getClassesContaining(containing, -1); } public List<Class> getClassesContaining(String containing, int top) { Stream<Class> selected = classes.stream(); if (!containing.isEmpty()) selected = classes.stream() .filter(c -> c.getUri().toString().toLowerCase().contains(containing.toLowerCase()) || c.getLabel().toLowerCase().contains(containing.toLowerCase())); if (top >= 0) selected = selected.sorted(Comparator.comparingInt(Class::getInstanceCount).reversed()).limit(top); return selected.collect(Collectors.toList()); } public void setClasses(List<Class> classes) { this.classes.clear(); this.classes.addAll(classes); } public void addClass(Class aClass) { classes.add(aClass); } public void removeClass(Class aClass) { classes.remove(aClass); } public void addDatasetOntology(String ontology) { this.datasetOntologies.add(ontology); } @JsonIgnore public List<String> getDatasetOntologies() { return new ArrayList<>(datasetOntologies); } public void setDatasetOntologies(Set<String> datasetOntologies) { this.datasetOntologies = datasetOntologies; } @JsonIgnore public URI getDatasetUri() { URI datasetURI = null; try { datasetURI = new URI("http://" +<SUF> } catch (Exception e) { logger.error(e.getMessage()); } return datasetURI; } @JsonIgnore public URI getDatasetOntologiesGraph() { URI datasetOntologiesGraphURI = null; try { datasetOntologiesGraphURI = new URI(getDatasetUri()+"/ontologies"); } catch (URISyntaxException e) { logger.error(e.getMessage()); } return datasetOntologiesGraphURI; } @JsonIgnore public URI getDatasetInferenceGraph() { URI datasetInferenceGraphURI = null; try { datasetInferenceGraphURI = new URI(getDatasetUri()+"/inference"); } catch (URISyntaxException e) { logger.error(e.getMessage()); } return datasetInferenceGraphURI; } }
10253_0
package com.eu.habbo.habbohotel.guilds.forums; import com.eu.habbo.Emulator; import com.eu.habbo.habbohotel.guilds.Guild; import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.messages.ISerialize; import com.eu.habbo.messages.ServerMessage; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TObjectProcedure; import java.sql.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class GuildForum implements ISerialize { private final int guild; private int totalThreads; private final TIntObjectHashMap<GuildForumThread> threads; private int lastRequested = Emulator.getIntUnixTimestamp(); public GuildForum(int guild) { this.guild = guild; this.threads = new TIntObjectHashMap<GuildForumThread>(); try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT author.username as author_name, author.look as look, COALESCE(admin.username, '') as admin_name, guilds_forums.id as thread_id, 0 as row_number, guilds_forums.* FROM guilds_forums " + "INNER JOIN users AS author ON author.id = user_id " + "LEFT JOIN users AS admin ON guilds_forums.admin_id = admin.id " + "WHERE guild_id = ?")) { statement.setInt(1, this.guild); try (ResultSet set = statement.executeQuery()) { while (set.next()) { this.threads.put(set.getInt("id"), new GuildForumThread(set)); } } } catch (SQLException e) { Emulator.getLogging().logSQLException(e); } } public GuildForumComment getLastComment() { if (!this.threads.valueCollection().isEmpty()) { GuildForumThread thread = Collections.max(this.threads.valueCollection(), Comparator.comparing(GuildForumThread::getLastCommentTimestamp)); if (thread != null && thread.comments.size() > 0) { return thread.comments.get(thread.comments.size() - 1); } } return null; } public List<GuildForumThread> getThreads() { return new ArrayList<>(this.threads.valueCollection()); } public List<GuildForumThread> getThreadsByAuthor(int userId) { return this.threads.valueCollection().stream().filter(p -> p.getAuthorId() == userId).collect(Collectors.toList()); } public GuildForumThread getThread(int threadId) { return threads.get(threadId); } public GuildForumThread createThread(Habbo habbo, String subject, String message) { int timestamp = Emulator.getIntUnixTimestamp(); GuildForumThread thread = null; try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO guilds_forums (guild_id, user_id, subject, message, timestamp) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { statement.setInt(1, this.guild); statement.setInt(2, habbo.getClient().getHabbo().getHabboInfo().getId()); statement.setString(3, subject); statement.setString(4, message); statement.setInt(5, timestamp); statement.execute(); try (ResultSet set = statement.getGeneratedKeys()) { if (set.next()) { thread = new GuildForumThread(habbo, set.getInt(1), this.guild, subject, message, timestamp); this.threads.put(set.getInt(1), //Thread id thread); } } } catch (SQLException e) { Emulator.getLogging().logSQLException(e); } return thread; } //TODO: /* Verwijderen door guild admin -> state naar HIDDEN_BY_ADMIN Guild admins moeten nog wel forum kunnen bekijken. Verwijderen door staff -> state naar HIDDEN_BY_STAFF Guild admins kunnen de thread niet zien. Staff wel. Thread wordt nooit uit de database verwijderd, alleen als de groep verwijderd wordt. */ public void hideThread(int threadId) { this.threads.get(threadId).setState(ThreadState.HIDDEN_BY_ADMIN); } public int getGuild() { return this.guild; } int getLastRequestedTime() { return this.lastRequested; } @Override public void serialize(ServerMessage message) { } public void serializeThreads(final ServerMessage message) { synchronized (this.threads) { message.appendInt(this.threads.size()); this.threads.forEachValue(new TObjectProcedure<GuildForumThread>() { @Override public boolean execute(GuildForumThread thread) { thread.serialize(message); return true; } }); } } public int threadSize() { synchronized (this.threads) { return this.threads.size(); } } void updateLastRequested() { this.lastRequested = Emulator.getIntUnixTimestamp(); } public enum ThreadState { CLOSED(0), OPEN(1), HIDDEN_BY_ADMIN(10), //DELETED HIDDEN_BY_STAFF(20); public final int state; ThreadState(int state) { this.state = state; } public static ThreadState fromValue(int state) { switch (state) { case 0: return CLOSED; case 1: return OPEN; case 10: return HIDDEN_BY_ADMIN; case 20: return HIDDEN_BY_STAFF; } return OPEN; } } public void serializeUserForum(ServerMessage response, Habbo habbo) { Guild guild = Emulator.getGameEnvironment().getGuildManager().getGuild(this.guild); GuildForum forum = Emulator.getGameEnvironment().getGuildForumManager().getGuildForum(this.guild); Integer amountOfComments = forum.getThreads().stream().map(GuildForumThread::getAmountOfComments).mapToInt(Integer::intValue).sum(); response.appendInt(guild.getId()); response.appendString(guild.getName()); response.appendString(guild.getDescription()); response.appendString(guild.getBadge()); response.appendInt(0); response.appendInt(0); //Rating response.appendInt(amountOfComments); response.appendInt(0); //New Messages GuildForumComment comment = this.getLastComment(); if (comment != null) { response.appendInt(comment.getThreadId()); response.appendInt(comment.getUserId()); response.appendString(comment.getUserName()); response.appendInt(Emulator.getIntUnixTimestamp() - comment.getTimestamp()); return; } response.appendInt(-1); response.appendInt(-1); response.appendString(""); response.appendInt(0); } }
orracosta/ArcturusEmulatorOld
src/main/java/com/eu/habbo/habbohotel/guilds/forums/GuildForum.java
2,099
/* Verwijderen door guild admin -> state naar HIDDEN_BY_ADMIN Guild admins moeten nog wel forum kunnen bekijken. Verwijderen door staff -> state naar HIDDEN_BY_STAFF Guild admins kunnen de thread niet zien. Staff wel. Thread wordt nooit uit de database verwijderd, alleen als de groep verwijderd wordt. */
block_comment
nl
package com.eu.habbo.habbohotel.guilds.forums; import com.eu.habbo.Emulator; import com.eu.habbo.habbohotel.guilds.Guild; import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.messages.ISerialize; import com.eu.habbo.messages.ServerMessage; import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.procedure.TObjectProcedure; import java.sql.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class GuildForum implements ISerialize { private final int guild; private int totalThreads; private final TIntObjectHashMap<GuildForumThread> threads; private int lastRequested = Emulator.getIntUnixTimestamp(); public GuildForum(int guild) { this.guild = guild; this.threads = new TIntObjectHashMap<GuildForumThread>(); try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT author.username as author_name, author.look as look, COALESCE(admin.username, '') as admin_name, guilds_forums.id as thread_id, 0 as row_number, guilds_forums.* FROM guilds_forums " + "INNER JOIN users AS author ON author.id = user_id " + "LEFT JOIN users AS admin ON guilds_forums.admin_id = admin.id " + "WHERE guild_id = ?")) { statement.setInt(1, this.guild); try (ResultSet set = statement.executeQuery()) { while (set.next()) { this.threads.put(set.getInt("id"), new GuildForumThread(set)); } } } catch (SQLException e) { Emulator.getLogging().logSQLException(e); } } public GuildForumComment getLastComment() { if (!this.threads.valueCollection().isEmpty()) { GuildForumThread thread = Collections.max(this.threads.valueCollection(), Comparator.comparing(GuildForumThread::getLastCommentTimestamp)); if (thread != null && thread.comments.size() > 0) { return thread.comments.get(thread.comments.size() - 1); } } return null; } public List<GuildForumThread> getThreads() { return new ArrayList<>(this.threads.valueCollection()); } public List<GuildForumThread> getThreadsByAuthor(int userId) { return this.threads.valueCollection().stream().filter(p -> p.getAuthorId() == userId).collect(Collectors.toList()); } public GuildForumThread getThread(int threadId) { return threads.get(threadId); } public GuildForumThread createThread(Habbo habbo, String subject, String message) { int timestamp = Emulator.getIntUnixTimestamp(); GuildForumThread thread = null; try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO guilds_forums (guild_id, user_id, subject, message, timestamp) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) { statement.setInt(1, this.guild); statement.setInt(2, habbo.getClient().getHabbo().getHabboInfo().getId()); statement.setString(3, subject); statement.setString(4, message); statement.setInt(5, timestamp); statement.execute(); try (ResultSet set = statement.getGeneratedKeys()) { if (set.next()) { thread = new GuildForumThread(habbo, set.getInt(1), this.guild, subject, message, timestamp); this.threads.put(set.getInt(1), //Thread id thread); } } } catch (SQLException e) { Emulator.getLogging().logSQLException(e); } return thread; } //TODO: /* Verwijderen door guild<SUF>*/ public void hideThread(int threadId) { this.threads.get(threadId).setState(ThreadState.HIDDEN_BY_ADMIN); } public int getGuild() { return this.guild; } int getLastRequestedTime() { return this.lastRequested; } @Override public void serialize(ServerMessage message) { } public void serializeThreads(final ServerMessage message) { synchronized (this.threads) { message.appendInt(this.threads.size()); this.threads.forEachValue(new TObjectProcedure<GuildForumThread>() { @Override public boolean execute(GuildForumThread thread) { thread.serialize(message); return true; } }); } } public int threadSize() { synchronized (this.threads) { return this.threads.size(); } } void updateLastRequested() { this.lastRequested = Emulator.getIntUnixTimestamp(); } public enum ThreadState { CLOSED(0), OPEN(1), HIDDEN_BY_ADMIN(10), //DELETED HIDDEN_BY_STAFF(20); public final int state; ThreadState(int state) { this.state = state; } public static ThreadState fromValue(int state) { switch (state) { case 0: return CLOSED; case 1: return OPEN; case 10: return HIDDEN_BY_ADMIN; case 20: return HIDDEN_BY_STAFF; } return OPEN; } } public void serializeUserForum(ServerMessage response, Habbo habbo) { Guild guild = Emulator.getGameEnvironment().getGuildManager().getGuild(this.guild); GuildForum forum = Emulator.getGameEnvironment().getGuildForumManager().getGuildForum(this.guild); Integer amountOfComments = forum.getThreads().stream().map(GuildForumThread::getAmountOfComments).mapToInt(Integer::intValue).sum(); response.appendInt(guild.getId()); response.appendString(guild.getName()); response.appendString(guild.getDescription()); response.appendString(guild.getBadge()); response.appendInt(0); response.appendInt(0); //Rating response.appendInt(amountOfComments); response.appendInt(0); //New Messages GuildForumComment comment = this.getLastComment(); if (comment != null) { response.appendInt(comment.getThreadId()); response.appendInt(comment.getUserId()); response.appendString(comment.getUserName()); response.appendInt(Emulator.getIntUnixTimestamp() - comment.getTimestamp()); return; } response.appendInt(-1); response.appendInt(-1); response.appendString(""); response.appendInt(0); } }
167698_1
package org.daniils.vloerinspection.ui.login; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import android.content.Context; import android.content.SharedPreferences; import android.util.Patterns; import org.daniils.vloerinspection.data.api.VloerAPI; import org.daniils.vloerinspection.R; public class LoginViewModel extends ViewModel { private MutableLiveData<LoginFormState> loginFormState = new MutableLiveData<>(); private MutableLiveData<LoginResult> loginResult = new MutableLiveData<>(); LiveData<LoginFormState> getLoginFormState() { return loginFormState; } LiveData<LoginResult> getLoginResult() { return loginResult; } public void login(String username, String password, boolean remember, Context context) { new VloerAPI(context).getUser(username, password, user -> { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(context.getString(R.string.pref_remember), remember); if (remember) { editor.putString(context.getString(R.string.username), username); editor.putString(context.getString(R.string.password), password); } editor.apply(); loginResult.setValue(new LoginResult(user)); }, error -> { loginResult.setValue(new LoginResult(R.string.login_failed)); error.printStackTrace(); }); } private SharedPreferences getSharedPreferences(Context context) { return context.getSharedPreferences(context.getString(R.string.app_preferences), Context.MODE_PRIVATE); } public void loadFormIfRemembered(Context context) { SharedPreferences sharedPreferences = getSharedPreferences(context); boolean remember = sharedPreferences.getBoolean(context.getString(R.string.pref_remember), false); if (remember) { String username = sharedPreferences.getString(context.getString(R.string.username), ""); String password = sharedPreferences.getString(context.getString(R.string.password), ""); loginFormState.setValue(new LoginFormState(username, password, true)); } } public void loginDataChanged(String username, String password) { if (!isUserNameValid(username)) { loginFormState.setValue(new LoginFormState(R.string.invalid_username, null)); } else if (!isPasswordValid(password)) { loginFormState.setValue(new LoginFormState(null, R.string.invalid_password)); } else { loginFormState.setValue(new LoginFormState(true)); } } // A placeholder username validation check private boolean isUserNameValid(String username) { if (username == null) { return false; } if (username.contains("@")) { return Patterns.EMAIL_ADDRESS.matcher(username).matches(); } else { return !username.trim().isEmpty(); } } // A placeholder password validation check private boolean isPasswordValid(String password) { return password != null && password.length() > 0; } }
ortemios/VloerInspection
app/src/main/java/org/daniils/vloerinspection/ui/login/LoginViewModel.java
882
// A placeholder password validation check
line_comment
nl
package org.daniils.vloerinspection.ui.login; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import android.content.Context; import android.content.SharedPreferences; import android.util.Patterns; import org.daniils.vloerinspection.data.api.VloerAPI; import org.daniils.vloerinspection.R; public class LoginViewModel extends ViewModel { private MutableLiveData<LoginFormState> loginFormState = new MutableLiveData<>(); private MutableLiveData<LoginResult> loginResult = new MutableLiveData<>(); LiveData<LoginFormState> getLoginFormState() { return loginFormState; } LiveData<LoginResult> getLoginResult() { return loginResult; } public void login(String username, String password, boolean remember, Context context) { new VloerAPI(context).getUser(username, password, user -> { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(context.getString(R.string.pref_remember), remember); if (remember) { editor.putString(context.getString(R.string.username), username); editor.putString(context.getString(R.string.password), password); } editor.apply(); loginResult.setValue(new LoginResult(user)); }, error -> { loginResult.setValue(new LoginResult(R.string.login_failed)); error.printStackTrace(); }); } private SharedPreferences getSharedPreferences(Context context) { return context.getSharedPreferences(context.getString(R.string.app_preferences), Context.MODE_PRIVATE); } public void loadFormIfRemembered(Context context) { SharedPreferences sharedPreferences = getSharedPreferences(context); boolean remember = sharedPreferences.getBoolean(context.getString(R.string.pref_remember), false); if (remember) { String username = sharedPreferences.getString(context.getString(R.string.username), ""); String password = sharedPreferences.getString(context.getString(R.string.password), ""); loginFormState.setValue(new LoginFormState(username, password, true)); } } public void loginDataChanged(String username, String password) { if (!isUserNameValid(username)) { loginFormState.setValue(new LoginFormState(R.string.invalid_username, null)); } else if (!isPasswordValid(password)) { loginFormState.setValue(new LoginFormState(null, R.string.invalid_password)); } else { loginFormState.setValue(new LoginFormState(true)); } } // A placeholder username validation check private boolean isUserNameValid(String username) { if (username == null) { return false; } if (username.contains("@")) { return Patterns.EMAIL_ADDRESS.matcher(username).matches(); } else { return !username.trim().isEmpty(); } } // A placeholder<SUF> private boolean isPasswordValid(String password) { return password != null && password.length() > 0; } }
36774_104
import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import javax.media.opengl.GL; import com.sun.opengl.util.GLUT; /** * The class which governs the Nyan Cat * * @author Lennie de Roo * */ public class NyanCat extends GameObject implements VisibleObject { private double horAngle; // sets the direction in which Nyan looks // private Control Nyancontrol=null; // the code to tell Nyan what to do private double speed = 0.05; // the speed of Nyan private int i = 0; // hulp integer for floating up and down private int j = 0; // hulp integer for floating up and down private int traillength = 30; // amount of rainbow blocks following Nyan private double[] lastX = new double[traillength]; // for saving the last // locations of Nyan private double[] lastZ = new double[traillength]; private double[] lastY = new double[traillength]; float NyanColor[] = { (float) Math.random(), (float) Math.random(), (float) Math.random(), (float) Math.random() }; // color Nyan, // randomized for // funz. private int HP = 100; // HealthPoints :D private boolean goal = false; // has Nyan reached its goal yet? public double goalX = Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE; // where Nyan wants to go public double goalZ = Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE; boolean dead = false; // whether Nyan is dead or not. private Player player; private ArrayList<RainbowBlock> rainbows = new ArrayList<RainbowBlock>(); // private MazeRunner.maze MazeRunner.maze; private TimerTask timertask; private Timer timer = new Timer(); private double HPoff = 0; private int t = 0; // makes a NyanCat on the location x, y , z, looking in direction h public NyanCat(double x, double y, double z, double h, Player play) { super(x, y, z); System.out.println("nyan aangemaakt"); horAngle = h; player = play; // MazeRunner.maze = m; // init the last locations: for (int i = 0; i < traillength; i++) { lastX[i] = getLocationX(); lastZ[i] = getLocationZ(); lastY[i] = getLocationY(); } } public int getHP() { return HP; // healthpoints } public double getHorAngle() { return horAngle + 90; // plus 90, omdat Nyancat scheef is gebouwd. } /** * Sets the horizontal angle of the orientation. * * @param horAngle * the horAngle to set */ public void setHorAngle(double horangle) { this.horAngle = horangle; } /** * Returns the speed. * * @return the speed */ public double getSpeed() { return speed; } /** * Sets the speed. * * @param speed * the speed to set */ public void setSpeed(double speed) { this.speed = speed; } /** * Updates the physical location and orientation of the NyanCat. * * @param deltaTime * The time in milliseconds since the last update. */ public void update(int deltaTime) { boolean up = false; if ((i >= 0) && (i < 70)) { setLocationY(getLocationY() + 0.5 * getSpeed()); i = i + 1; up = true; } // fly down 70 times: if ((i >= 70) && (!up)) { setLocationY(getLocationY() - 0.5 * getSpeed()); j = j + 1; if ((j > 69)) { i = 0; j = 0; } } if (goal) { goal(Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE, Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE); } if (SeePlayer()) { // checks if player is seen goal(player.getLocationX(), player.getLocationZ()); // if player is // seen, set // goal to // players // location } if (!goal) { if (!SeePlayer()) { if (MazeRunner.maze.isWall(goalX,goalZ) || MazeRunner.maze.isWall(this.getLocationX() - 2 * speed * Math.sin(Math.toRadians(horAngle)), this.getLocationZ() - 2 * speed * Math.cos(Math.toRadians(horAngle)))) { goal(Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE, Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE); } if (t > 350) { goal(Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE, Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE); t = 0; } } // move to goalX,goalZ moveTo(goalX, goalZ); t = t + 1; } // when goal is reached choose randomly a new goal: if ((Math.abs(getLocationX() - goalX) < speed) && (Math.abs(getLocationZ() - goalZ) < speed)) { goal = true; if ((Math.abs(getLocationX() - goalX) < speed) && (Math.abs(getLocationZ() - goalZ) < speed)) { goal = true; } } fireRainbow(10); for (int i = 0; i < rainbows.size(); i++) { rainbows.get(i).update(); if (rainbows.get(i).CollisionCheck(player)) { HPoff = HPoff + 5; rainbows.remove(i); } } } private void fireRainbow(int rof) { if (SeePlayer()) { // when player is seen, shoot rainbowblocks. if (timertask != null) return; timertask = new TimerTask() { @Override public void run() { if (SeePlayer()) { RainbowBlock Rainbow = new RainbowBlock( NyanCat.this.getLocationX(), NyanCat.this.getLocationY(), NyanCat.this.getLocationZ(), goalX, NyanCat.this.getLocationY(), goalZ, MazeRunner.maze); rainbows.add(Rainbow); } } }; timer.scheduleAtFixedRate(timertask, 0, 1000 + Math.round((Math.random() * 100))); } } public void goal(double X, double Y) { goalX = X; goalZ = Y; goal = false; } /** * Check if the Nyancat can see the player. It does so by checking whether a * line from the Nyan cat intersects with the Z-axis of the player. This * line has a field of view of 70 degrees. Anything outside this cannot be * seen by nyan * * @return true if seen, false if not */ public boolean SeePlayer() { // Checks whether the Nyan can see the player. // It does this by checking whether the angle the line from player to // Nyan makes with the Z-axis // and whether this angle is between Nyans looking angle +-70 degrees. double hoekPlayer = Math.toDegrees(Math.atan2(player.getLocationX() - this.getLocationX(), player.getLocationZ() - this.getLocationZ())); if (hoekPlayer < 0) { hoekPlayer = hoekPlayer + 360; // for better comparison } double HorAngle = this.getHorAngle(); if (this.getHorAngle() < 0) { HorAngle = HorAngle + 360; // for better comparison } // double deltaX = (player.getLocationX() - this.getLocationX()) // / Math.sqrt(Math.pow(player.getLocationX() - getLocationX(), 2) // + Math.pow(player.getLocationZ() - getLocationZ(), 2)); // double deltaZ = (player.getLocationZ() - getLocationZ()) // / Math.sqrt(Math.pow(player.getLocationX() - getLocationX(), 2) // + Math.pow(player.getLocationZ() - getLocationZ(), 2)); // if (HorAngle - 85 <= hoekPlayer) { if (HorAngle + 85 >= hoekPlayer) { // double x = player.getLocationX() - this.getLocationX(); // double z = player.getLocationZ() - this.getLocationZ(); // double length = Math.sqrt(x*x + z*z); // double hoev = Math.floor(length / 2.5); // double hoek = Math.tan(x / z); // for (int i = 0; i < hoev; i++) { // if (MazeRunner.maze.isWall(this.getLocationX() + Math.sqrt(12.5) * Math.asin(hoek) , // this.getLocationZ() + Math.sqrt(12.5)*Math.acos(hoek))) { // if (Math.abs(x) > Math.abs(z)) { // for (double i = 0; i < x; i = i + 10) { // if (MazeRunner.maze.isWall(this.getLocationX() + i, // this.getLocationZ() + (z / x) * i )) { // return false; // } // } // } // if (Math.abs(z) > Math.abs(x)) { // for (double i = 0; i < z; i = i + 2.5) { // if (MazeRunner.maze.isWall(this.getLocationX() + (x / z) * i, // this.getLocationZ() - 2.5 + i )) { // return false; // } // } // } // for (double i = 0; i < Math.abs(player.getLocationX() - this.getLocationX()); i = i + MazeRunner.maze.SQUARE_SIZE / 2) { for (double j = 0; j < Math.abs(player.getLocationZ() - this.getLocationZ()); j = j + MazeRunner.maze.SQUARE_SIZE / 2) { if (MazeRunner.maze.isWall(this.getLocationX() + i, this.getLocationZ() + j)) { return false; } } } return true; } } return false; } /** * Sets the location to where the nyancat should move to. * * @param X * the X location * @param Z * the Z location */ public void moveTo(double X, double Z) { // genormaliseerde richtingsvector: double deltaX = (X - getLocationX()) / Math.sqrt(Math.pow(X - getLocationX(), 2) + Math.pow(Z - getLocationZ(), 2)); double deltaZ = (Z - getLocationZ()) / Math.sqrt(Math.pow(X - getLocationX(), 2) + Math.pow(Z - getLocationZ(), 2)); if (MazeRunner.maze.isWall(this.getLocationX() + deltaX * speed, this.getLocationZ() + deltaZ * speed)) { if (!MazeRunner.maze.isWall(this.getLocationX() - deltaX * speed, this.getLocationZ() + deltaZ * speed)) { moveTo(this.getLocationX() - deltaX * speed, this.getLocationZ() + deltaZ * speed); } else if (!MazeRunner.maze.isWall(this.getLocationX() + deltaX * speed, this.getLocationZ() - deltaZ * speed)) { moveTo(this.getLocationX() + deltaX * speed, this.getLocationZ() - deltaZ * speed); } else if (!MazeRunner.maze.isWall(this.getLocationX() - deltaX * speed, this.getLocationZ() - deltaZ * speed)) { moveTo(this.getLocationX() - deltaX * speed, this.getLocationZ() - deltaZ * speed); } } if (!goal) { this.setLocationX(getLocationX() + deltaX * speed); this.setLocationZ(getLocationZ() + deltaZ * speed); double hoek = Math .atan(Math.abs(((this.getLocationX() - this.lastX[1]) / (this .getLocationZ() - this.lastZ[1])))); hoek = (hoek / Math.PI) * 180; // van rad naar degrees. // 4 kwadranten afzonderlijk bekijken vanwege oscillaties rond 0, en // range atan: if ((-this.lastX[1] + this.getLocationX() >= 0) && (-this.lastZ[1] + this.getLocationZ() >= 0)) { // hoek=hoek; } if ((-this.lastX[1] + this.getLocationX() < 0) && (-this.lastZ[1] + this.getLocationZ() >= 0)) { hoek = -hoek; } if ((-this.lastX[1] + this.getLocationX() >= 0) && (-this.lastZ[1] + this.getLocationZ() < 0)) { hoek = 180 - hoek; } if ((-this.lastX[1] + this.getLocationX() < 0) && (-this.lastZ[1] + this.getLocationZ() < 0)) { hoek = 180 + hoek; } hoek = hoek - 90; // offset vanwege rare assendefinities. this.setHorAngle(hoek); } } @Override public void display(GL gl) { // When Nyan is not dead, display him: if (!dead) { GLUT glut = new GLUT(); // Coords for NyanLocation: double X = this.getLocationX(); double Y = this.getLocationY() + 5 / 4; // Nyan is build around this // point, it is the center double Z = this.getLocationZ(); gl.glPushMatrix(); // slaat het coordinatenstelsel van nu op. // display the Nyan (its poptart) on its new location: gl.glTranslated(X, Y, Z); // X,Y,Z are the coordinates of the // middlepoint of the poptart of Nyan gl.glRotated(this.horAngle, 0, 1, 0); // rotate around Y-axis for // the right orientation, // System.out.println(horAngle); // make Nyan look to the right direction. // the appearance of Nyan: int roundness = 10; // how round are the spheres and cones? Less // round-> faster rendering. float size = 1; // measure for the size of Nyan float scalefactor = 2; // measure for scaling of the poptart gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, NyanColor, 0); // Nyan // material. // POPTART: gl.glScaled(scalefactor, scalefactor, 1); // making the poptart cube // into a cuboid, // make a textured poptart of size size: Textureloader.poptart(gl, size); // texturized cube // HEAD: gl.glScaled((float) 1 / (scalefactor), (float) 1 / scalefactor, 1); // unscale // the // head gl.glScaled(1, 1, (float) 1.5); // scale the head // location of head with respect to the poptart: gl.glTranslated((0.7 * scalefactor), -1 / scalefactor * size, 0); Textureloader.head(gl, glut, size, roundness); // EARS: gl.glScaled(1, 1, (float) 1 / 1.5); // unscale ears. gl.glTranslated(0, 0.25 * size, 0.25 * size); // location of ear 1 // with respect to // head gl.glRotated(-90, 1, 0, 0);// point upwards. glut.glutSolidCone(0.25 * size, 0.5 * size, roundness, roundness); // ear // 1 gl.glRotated(90, 1, 0, 0); // rotate back gl.glTranslated(0, 0, -0.5 * size); // location of ear 2 with // respect to ear 1 gl.glRotated(-90, 1, 0, 0); // point upwards. glut.glutSolidCone(0.25 * size, 0.5 * size, roundness, roundness); // ear // 2 gl.glRotated(90, 1, 0, 0); // rotate back // PAWS: // translate back to middle of poptart: gl.glTranslated(0, 0, 0.5 * size); gl.glTranslated(0, -0.25 * size, -0.25 * size); gl.glTranslated(-(0.7 * scalefactor), 1 / scalefactor * size, 0); // making of the paws: // pawlocation with respect to middle of poptart: gl.glTranslated(0.4 * scalefactor, -0.5 * scalefactor, 0.2 * size); glut.glutSolidCube((float) (0.3 * size)); // paw 1 // paw location with respect to paw 1: gl.glTranslated(-0.8 * scalefactor, 0, 0); glut.glutSolidCube((float) (0.3 * size)); // paw 2 // Paw location with respect to paw 2: gl.glTranslated(0, 0, -0.5 * size); glut.glutSolidCube((float) (0.3 * size)); // paw 3 // Paw location with respect to paw 3: gl.glTranslated(0.8 * scalefactor, 0, 0); glut.glutSolidCube((float) (0.3 * size)); // paw 4 // TAIL: // Tail movement: double ytail = 0; // the translation in up direction of the next // tail segment with respect to the last. boolean up = false; if ((i >= 0) && (i < 35)) { ytail = i * (0.3 * size / 70); up = true; } if ((i >= 35) && (i < 70)) { ytail = (70 - i) * (0.3 * size / 70); } if ((i >= 70) && (!up)) { if ((j >= 0) && (j < 35)) { ytail = -j * (0.3 * size) / 70; } if ((j >= 35) && (j < 70)) { ytail = (j - 70) * (0.3 * size / 70); } } gl.glTranslated(-0.9 * size * scalefactor, 0.7 * size, 0.3 * size); // translation // with // respect // to // paw // 4. glut.glutSolidCube((float) (0.3 * size)); // tail part 1. gl.glTranslated(-0.3 * size, ytail, 0); // translation with respect // to tail part 1 glut.glutSolidCube((float) (0.3 * size));// tail part 2. gl.glTranslated(-0.3 * size, ytail, 0); // translation with respect // to tail part 2. glut.glutSolidCube((float) (0.3 * size)); // tail part 3. // TODO: if Nyan x and/or z location changes make paws and head // move. No Priority. // Nyans rainbow trail: gl.glPopMatrix();// reset alle coordinaten tot waar // gl.glPushMatrix() werd aangeroepen. // make rainbowtrail: // for (int i = 0; i < traillength; i++) { // of length traillength // gl.glPushMatrix(); // save all coords // gl.glTranslated(0, 3 / 4 + 0.5 * size, 0); // translate a bit up // // so that the // // rainbowtrail // // origins from the // // middle // gl.glTranslated((lastX[i]), lastY[i], (lastZ[i])); // translate // // to saved // // last // // coords // Textureloader.Rainbow(gl, 0.5 * size); // make the actual // // rainbowblock // gl.glPopMatrix(); // reset all coords // } // shift all coords in the last positions one position so that first // position in array becomes // free and last position is deleted // only once in 3 times for saving memory if ((i % 3 == 0) || ((j % 3 == 0) && (i > 69))) { for (int k = traillength - 1; k > 0; k = k - 1) { lastX[k] = lastX[k - 1]; lastY[k] = lastY[k - 1]; lastZ[k] = lastZ[k - 1]; } // put the new location in the arrays. lastX[0] = getLocationX(); lastY[0] = getLocationY(); lastZ[0] = getLocationZ(); } // gl.glPopMatrix(); if (this.getHP() < 0) { dead = true; } // make projectiles visible: for (int i = 0; i < rainbows.size(); i++) { rainbows.get(i).display(gl); } } } public double getHPoff() { double res = HPoff; HPoff = 0; return res; } public void setHP(int x) { HP = x; } }
ortix/candyland
src/NyanCat.java
6,429
// gl.glPushMatrix() werd aangeroepen.
line_comment
nl
import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import javax.media.opengl.GL; import com.sun.opengl.util.GLUT; /** * The class which governs the Nyan Cat * * @author Lennie de Roo * */ public class NyanCat extends GameObject implements VisibleObject { private double horAngle; // sets the direction in which Nyan looks // private Control Nyancontrol=null; // the code to tell Nyan what to do private double speed = 0.05; // the speed of Nyan private int i = 0; // hulp integer for floating up and down private int j = 0; // hulp integer for floating up and down private int traillength = 30; // amount of rainbow blocks following Nyan private double[] lastX = new double[traillength]; // for saving the last // locations of Nyan private double[] lastZ = new double[traillength]; private double[] lastY = new double[traillength]; float NyanColor[] = { (float) Math.random(), (float) Math.random(), (float) Math.random(), (float) Math.random() }; // color Nyan, // randomized for // funz. private int HP = 100; // HealthPoints :D private boolean goal = false; // has Nyan reached its goal yet? public double goalX = Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE; // where Nyan wants to go public double goalZ = Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE; boolean dead = false; // whether Nyan is dead or not. private Player player; private ArrayList<RainbowBlock> rainbows = new ArrayList<RainbowBlock>(); // private MazeRunner.maze MazeRunner.maze; private TimerTask timertask; private Timer timer = new Timer(); private double HPoff = 0; private int t = 0; // makes a NyanCat on the location x, y , z, looking in direction h public NyanCat(double x, double y, double z, double h, Player play) { super(x, y, z); System.out.println("nyan aangemaakt"); horAngle = h; player = play; // MazeRunner.maze = m; // init the last locations: for (int i = 0; i < traillength; i++) { lastX[i] = getLocationX(); lastZ[i] = getLocationZ(); lastY[i] = getLocationY(); } } public int getHP() { return HP; // healthpoints } public double getHorAngle() { return horAngle + 90; // plus 90, omdat Nyancat scheef is gebouwd. } /** * Sets the horizontal angle of the orientation. * * @param horAngle * the horAngle to set */ public void setHorAngle(double horangle) { this.horAngle = horangle; } /** * Returns the speed. * * @return the speed */ public double getSpeed() { return speed; } /** * Sets the speed. * * @param speed * the speed to set */ public void setSpeed(double speed) { this.speed = speed; } /** * Updates the physical location and orientation of the NyanCat. * * @param deltaTime * The time in milliseconds since the last update. */ public void update(int deltaTime) { boolean up = false; if ((i >= 0) && (i < 70)) { setLocationY(getLocationY() + 0.5 * getSpeed()); i = i + 1; up = true; } // fly down 70 times: if ((i >= 70) && (!up)) { setLocationY(getLocationY() - 0.5 * getSpeed()); j = j + 1; if ((j > 69)) { i = 0; j = 0; } } if (goal) { goal(Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE, Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE); } if (SeePlayer()) { // checks if player is seen goal(player.getLocationX(), player.getLocationZ()); // if player is // seen, set // goal to // players // location } if (!goal) { if (!SeePlayer()) { if (MazeRunner.maze.isWall(goalX,goalZ) || MazeRunner.maze.isWall(this.getLocationX() - 2 * speed * Math.sin(Math.toRadians(horAngle)), this.getLocationZ() - 2 * speed * Math.cos(Math.toRadians(horAngle)))) { goal(Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE, Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE); } if (t > 350) { goal(Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE, Math.random() * MazeRunner.maze.MAZE_SIZE * MazeRunner.maze.SQUARE_SIZE); t = 0; } } // move to goalX,goalZ moveTo(goalX, goalZ); t = t + 1; } // when goal is reached choose randomly a new goal: if ((Math.abs(getLocationX() - goalX) < speed) && (Math.abs(getLocationZ() - goalZ) < speed)) { goal = true; if ((Math.abs(getLocationX() - goalX) < speed) && (Math.abs(getLocationZ() - goalZ) < speed)) { goal = true; } } fireRainbow(10); for (int i = 0; i < rainbows.size(); i++) { rainbows.get(i).update(); if (rainbows.get(i).CollisionCheck(player)) { HPoff = HPoff + 5; rainbows.remove(i); } } } private void fireRainbow(int rof) { if (SeePlayer()) { // when player is seen, shoot rainbowblocks. if (timertask != null) return; timertask = new TimerTask() { @Override public void run() { if (SeePlayer()) { RainbowBlock Rainbow = new RainbowBlock( NyanCat.this.getLocationX(), NyanCat.this.getLocationY(), NyanCat.this.getLocationZ(), goalX, NyanCat.this.getLocationY(), goalZ, MazeRunner.maze); rainbows.add(Rainbow); } } }; timer.scheduleAtFixedRate(timertask, 0, 1000 + Math.round((Math.random() * 100))); } } public void goal(double X, double Y) { goalX = X; goalZ = Y; goal = false; } /** * Check if the Nyancat can see the player. It does so by checking whether a * line from the Nyan cat intersects with the Z-axis of the player. This * line has a field of view of 70 degrees. Anything outside this cannot be * seen by nyan * * @return true if seen, false if not */ public boolean SeePlayer() { // Checks whether the Nyan can see the player. // It does this by checking whether the angle the line from player to // Nyan makes with the Z-axis // and whether this angle is between Nyans looking angle +-70 degrees. double hoekPlayer = Math.toDegrees(Math.atan2(player.getLocationX() - this.getLocationX(), player.getLocationZ() - this.getLocationZ())); if (hoekPlayer < 0) { hoekPlayer = hoekPlayer + 360; // for better comparison } double HorAngle = this.getHorAngle(); if (this.getHorAngle() < 0) { HorAngle = HorAngle + 360; // for better comparison } // double deltaX = (player.getLocationX() - this.getLocationX()) // / Math.sqrt(Math.pow(player.getLocationX() - getLocationX(), 2) // + Math.pow(player.getLocationZ() - getLocationZ(), 2)); // double deltaZ = (player.getLocationZ() - getLocationZ()) // / Math.sqrt(Math.pow(player.getLocationX() - getLocationX(), 2) // + Math.pow(player.getLocationZ() - getLocationZ(), 2)); // if (HorAngle - 85 <= hoekPlayer) { if (HorAngle + 85 >= hoekPlayer) { // double x = player.getLocationX() - this.getLocationX(); // double z = player.getLocationZ() - this.getLocationZ(); // double length = Math.sqrt(x*x + z*z); // double hoev = Math.floor(length / 2.5); // double hoek = Math.tan(x / z); // for (int i = 0; i < hoev; i++) { // if (MazeRunner.maze.isWall(this.getLocationX() + Math.sqrt(12.5) * Math.asin(hoek) , // this.getLocationZ() + Math.sqrt(12.5)*Math.acos(hoek))) { // if (Math.abs(x) > Math.abs(z)) { // for (double i = 0; i < x; i = i + 10) { // if (MazeRunner.maze.isWall(this.getLocationX() + i, // this.getLocationZ() + (z / x) * i )) { // return false; // } // } // } // if (Math.abs(z) > Math.abs(x)) { // for (double i = 0; i < z; i = i + 2.5) { // if (MazeRunner.maze.isWall(this.getLocationX() + (x / z) * i, // this.getLocationZ() - 2.5 + i )) { // return false; // } // } // } // for (double i = 0; i < Math.abs(player.getLocationX() - this.getLocationX()); i = i + MazeRunner.maze.SQUARE_SIZE / 2) { for (double j = 0; j < Math.abs(player.getLocationZ() - this.getLocationZ()); j = j + MazeRunner.maze.SQUARE_SIZE / 2) { if (MazeRunner.maze.isWall(this.getLocationX() + i, this.getLocationZ() + j)) { return false; } } } return true; } } return false; } /** * Sets the location to where the nyancat should move to. * * @param X * the X location * @param Z * the Z location */ public void moveTo(double X, double Z) { // genormaliseerde richtingsvector: double deltaX = (X - getLocationX()) / Math.sqrt(Math.pow(X - getLocationX(), 2) + Math.pow(Z - getLocationZ(), 2)); double deltaZ = (Z - getLocationZ()) / Math.sqrt(Math.pow(X - getLocationX(), 2) + Math.pow(Z - getLocationZ(), 2)); if (MazeRunner.maze.isWall(this.getLocationX() + deltaX * speed, this.getLocationZ() + deltaZ * speed)) { if (!MazeRunner.maze.isWall(this.getLocationX() - deltaX * speed, this.getLocationZ() + deltaZ * speed)) { moveTo(this.getLocationX() - deltaX * speed, this.getLocationZ() + deltaZ * speed); } else if (!MazeRunner.maze.isWall(this.getLocationX() + deltaX * speed, this.getLocationZ() - deltaZ * speed)) { moveTo(this.getLocationX() + deltaX * speed, this.getLocationZ() - deltaZ * speed); } else if (!MazeRunner.maze.isWall(this.getLocationX() - deltaX * speed, this.getLocationZ() - deltaZ * speed)) { moveTo(this.getLocationX() - deltaX * speed, this.getLocationZ() - deltaZ * speed); } } if (!goal) { this.setLocationX(getLocationX() + deltaX * speed); this.setLocationZ(getLocationZ() + deltaZ * speed); double hoek = Math .atan(Math.abs(((this.getLocationX() - this.lastX[1]) / (this .getLocationZ() - this.lastZ[1])))); hoek = (hoek / Math.PI) * 180; // van rad naar degrees. // 4 kwadranten afzonderlijk bekijken vanwege oscillaties rond 0, en // range atan: if ((-this.lastX[1] + this.getLocationX() >= 0) && (-this.lastZ[1] + this.getLocationZ() >= 0)) { // hoek=hoek; } if ((-this.lastX[1] + this.getLocationX() < 0) && (-this.lastZ[1] + this.getLocationZ() >= 0)) { hoek = -hoek; } if ((-this.lastX[1] + this.getLocationX() >= 0) && (-this.lastZ[1] + this.getLocationZ() < 0)) { hoek = 180 - hoek; } if ((-this.lastX[1] + this.getLocationX() < 0) && (-this.lastZ[1] + this.getLocationZ() < 0)) { hoek = 180 + hoek; } hoek = hoek - 90; // offset vanwege rare assendefinities. this.setHorAngle(hoek); } } @Override public void display(GL gl) { // When Nyan is not dead, display him: if (!dead) { GLUT glut = new GLUT(); // Coords for NyanLocation: double X = this.getLocationX(); double Y = this.getLocationY() + 5 / 4; // Nyan is build around this // point, it is the center double Z = this.getLocationZ(); gl.glPushMatrix(); // slaat het coordinatenstelsel van nu op. // display the Nyan (its poptart) on its new location: gl.glTranslated(X, Y, Z); // X,Y,Z are the coordinates of the // middlepoint of the poptart of Nyan gl.glRotated(this.horAngle, 0, 1, 0); // rotate around Y-axis for // the right orientation, // System.out.println(horAngle); // make Nyan look to the right direction. // the appearance of Nyan: int roundness = 10; // how round are the spheres and cones? Less // round-> faster rendering. float size = 1; // measure for the size of Nyan float scalefactor = 2; // measure for scaling of the poptart gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, NyanColor, 0); // Nyan // material. // POPTART: gl.glScaled(scalefactor, scalefactor, 1); // making the poptart cube // into a cuboid, // make a textured poptart of size size: Textureloader.poptart(gl, size); // texturized cube // HEAD: gl.glScaled((float) 1 / (scalefactor), (float) 1 / scalefactor, 1); // unscale // the // head gl.glScaled(1, 1, (float) 1.5); // scale the head // location of head with respect to the poptart: gl.glTranslated((0.7 * scalefactor), -1 / scalefactor * size, 0); Textureloader.head(gl, glut, size, roundness); // EARS: gl.glScaled(1, 1, (float) 1 / 1.5); // unscale ears. gl.glTranslated(0, 0.25 * size, 0.25 * size); // location of ear 1 // with respect to // head gl.glRotated(-90, 1, 0, 0);// point upwards. glut.glutSolidCone(0.25 * size, 0.5 * size, roundness, roundness); // ear // 1 gl.glRotated(90, 1, 0, 0); // rotate back gl.glTranslated(0, 0, -0.5 * size); // location of ear 2 with // respect to ear 1 gl.glRotated(-90, 1, 0, 0); // point upwards. glut.glutSolidCone(0.25 * size, 0.5 * size, roundness, roundness); // ear // 2 gl.glRotated(90, 1, 0, 0); // rotate back // PAWS: // translate back to middle of poptart: gl.glTranslated(0, 0, 0.5 * size); gl.glTranslated(0, -0.25 * size, -0.25 * size); gl.glTranslated(-(0.7 * scalefactor), 1 / scalefactor * size, 0); // making of the paws: // pawlocation with respect to middle of poptart: gl.glTranslated(0.4 * scalefactor, -0.5 * scalefactor, 0.2 * size); glut.glutSolidCube((float) (0.3 * size)); // paw 1 // paw location with respect to paw 1: gl.glTranslated(-0.8 * scalefactor, 0, 0); glut.glutSolidCube((float) (0.3 * size)); // paw 2 // Paw location with respect to paw 2: gl.glTranslated(0, 0, -0.5 * size); glut.glutSolidCube((float) (0.3 * size)); // paw 3 // Paw location with respect to paw 3: gl.glTranslated(0.8 * scalefactor, 0, 0); glut.glutSolidCube((float) (0.3 * size)); // paw 4 // TAIL: // Tail movement: double ytail = 0; // the translation in up direction of the next // tail segment with respect to the last. boolean up = false; if ((i >= 0) && (i < 35)) { ytail = i * (0.3 * size / 70); up = true; } if ((i >= 35) && (i < 70)) { ytail = (70 - i) * (0.3 * size / 70); } if ((i >= 70) && (!up)) { if ((j >= 0) && (j < 35)) { ytail = -j * (0.3 * size) / 70; } if ((j >= 35) && (j < 70)) { ytail = (j - 70) * (0.3 * size / 70); } } gl.glTranslated(-0.9 * size * scalefactor, 0.7 * size, 0.3 * size); // translation // with // respect // to // paw // 4. glut.glutSolidCube((float) (0.3 * size)); // tail part 1. gl.glTranslated(-0.3 * size, ytail, 0); // translation with respect // to tail part 1 glut.glutSolidCube((float) (0.3 * size));// tail part 2. gl.glTranslated(-0.3 * size, ytail, 0); // translation with respect // to tail part 2. glut.glutSolidCube((float) (0.3 * size)); // tail part 3. // TODO: if Nyan x and/or z location changes make paws and head // move. No Priority. // Nyans rainbow trail: gl.glPopMatrix();// reset alle coordinaten tot waar // gl.glPushMatrix() werd<SUF> // make rainbowtrail: // for (int i = 0; i < traillength; i++) { // of length traillength // gl.glPushMatrix(); // save all coords // gl.glTranslated(0, 3 / 4 + 0.5 * size, 0); // translate a bit up // // so that the // // rainbowtrail // // origins from the // // middle // gl.glTranslated((lastX[i]), lastY[i], (lastZ[i])); // translate // // to saved // // last // // coords // Textureloader.Rainbow(gl, 0.5 * size); // make the actual // // rainbowblock // gl.glPopMatrix(); // reset all coords // } // shift all coords in the last positions one position so that first // position in array becomes // free and last position is deleted // only once in 3 times for saving memory if ((i % 3 == 0) || ((j % 3 == 0) && (i > 69))) { for (int k = traillength - 1; k > 0; k = k - 1) { lastX[k] = lastX[k - 1]; lastY[k] = lastY[k - 1]; lastZ[k] = lastZ[k - 1]; } // put the new location in the arrays. lastX[0] = getLocationX(); lastY[0] = getLocationY(); lastZ[0] = getLocationZ(); } // gl.glPopMatrix(); if (this.getHP() < 0) { dead = true; } // make projectiles visible: for (int i = 0; i < rainbows.size(); i++) { rainbows.get(i).display(gl); } } } public double getHPoff() { double res = HPoff; HPoff = 0; return res; } public void setHP(int x) { HP = x; } }
169474_15
/* * Copyright 2016-2022 The OSHI Project Contributors * SPDX-License-Identifier: MIT */ package oshi.jna.platform.mac; import com.sun.jna.Native; import com.sun.jna.Structure; import com.sun.jna.Structure.FieldOrder; import com.sun.jna.Union; import oshi.jna.platform.unix.CLibrary; import oshi.util.Util; /** * System class. This class should be considered non-API as it may be removed if/when its code is incorporated into the * JNA project. */ public interface SystemB extends com.sun.jna.platform.mac.SystemB, CLibrary { SystemB INSTANCE = Native.load("System", SystemB.class); int PROC_PIDLISTFDS = 1; int PROX_FDTYPE_SOCKET = 2; int PROC_PIDFDSOCKETINFO = 3; int TSI_T_NTIMERS = 4; int SOCKINFO_IN = 1; int SOCKINFO_TCP = 2; int UTX_USERSIZE = 256; int UTX_LINESIZE = 32; int UTX_IDSIZE = 4; int UTX_HOSTSIZE = 256; int AF_INET = 2; // The Internet Protocol version 4 (IPv4) address family. int AF_INET6 = 30; // The Internet Protocol version 6 (IPv6) address family. /** * Mac connection info */ @FieldOrder({ "ut_user", "ut_id", "ut_line", "ut_pid", "ut_type", "ut_tv", "ut_host", "ut_pad" }) class MacUtmpx extends Structure { public byte[] ut_user = new byte[UTX_USERSIZE]; // login name public byte[] ut_id = new byte[UTX_IDSIZE]; // id public byte[] ut_line = new byte[UTX_LINESIZE]; // tty name public int ut_pid; // process id creating the entry public short ut_type; // type of this entry public Timeval ut_tv; // time entry was created public byte[] ut_host = new byte[UTX_HOSTSIZE]; // host name public byte[] ut_pad = new byte[16]; // reserved for future use } /** * Mac file descriptor info */ @FieldOrder({ "proc_fd", "proc_fdtype" }) class ProcFdInfo extends Structure { public int proc_fd; public int proc_fdtype; } /** * Mac internet socket info */ @FieldOrder({ "insi_fport", "insi_lport", "insi_gencnt", "insi_flags", "insi_flow", "insi_vflag", "insi_ip_ttl", "rfu_1", "insi_faddr", "insi_laddr", "insi_v4", "insi_v6" }) class InSockInfo extends Structure { public int insi_fport; /* foreign port */ public int insi_lport; /* local port */ public long insi_gencnt; /* generation count of this instance */ public int insi_flags; /* generic IP/datagram flags */ public int insi_flow; public byte insi_vflag; /* ini_IPV4 or ini_IPV6 */ public byte insi_ip_ttl; /* time to live proto */ public int rfu_1; /* reserved */ /* protocol dependent part, v4 only in last element */ public int[] insi_faddr = new int[4]; /* foreign host table entry */ public int[] insi_laddr = new int[4]; /* local host table entry */ public byte insi_v4; /* type of service */ public byte[] insi_v6 = new byte[9]; } /** * Mac TCP socket info */ @FieldOrder({ "tcpsi_ini", "tcpsi_state", "tcpsi_timer", "tcpsi_mss", "tcpsi_flags", "rfu_1", "tcpsi_tp" }) class TcpSockInfo extends Structure { public InSockInfo tcpsi_ini; public int tcpsi_state; public int[] tcpsi_timer = new int[TSI_T_NTIMERS]; public int tcpsi_mss; public int tcpsi_flags; public int rfu_1; /* reserved */ public long tcpsi_tp; /* opaque handle of TCP protocol control block */ } /** * Mack IP Socket Info */ @FieldOrder({ "soi_stat", "soi_so", "soi_pcb", "soi_type", "soi_protocol", "soi_family", "soi_options", "soi_linger", "soi_state", "soi_qlen", "soi_incqlen", "soi_qlimit", "soi_timeo", "soi_error", "soi_oobmark", "soi_rcv", "soi_snd", "soi_kind", "rfu_1", "soi_proto" }) class SocketInfo extends Structure { public long[] soi_stat = new long[17]; // vinfo_stat public long soi_so; /* opaque handle of socket */ public long soi_pcb; /* opaque handle of protocol control block */ public int soi_type; public int soi_protocol; public int soi_family; public short soi_options; public short soi_linger; public short soi_state; public short soi_qlen; public short soi_incqlen; public short soi_qlimit; public short soi_timeo; public short soi_error; public int soi_oobmark; public int[] soi_rcv = new int[6]; // sockbuf_info public int[] soi_snd = new int[6]; // sockbuf_info public int soi_kind; public int rfu_1; /* reserved */ public Pri soi_proto; } /** * Mac file info */ @FieldOrder({ "fi_openflags", "fi_status", "fi_offset", "fi_type", "fi_guardflags" }) class ProcFileInfo extends Structure { public int fi_openflags; public int fi_status; public long fi_offset; public int fi_type; public int fi_guardflags; } /** * Mac socket info */ @FieldOrder({ "pfi", "psi" }) class SocketFdInfo extends Structure implements AutoCloseable { public ProcFileInfo pfi; public SocketInfo psi; @Override public void close() { Util.freeMemory(getPointer()); } } /** * Union for TCP or internet socket info */ class Pri extends Union { public InSockInfo pri_in; public TcpSockInfo pri_tcp; // max element is 524 bytes public byte[] max_size = new byte[524]; } /** * Reads a line from the current file position in the utmp file. It returns a pointer to a structure containing the * fields of the line. * <p> * Not thread safe * * @return a {@link MacUtmpx} on success, and NULL on failure (which includes the "record not found" case) */ MacUtmpx getutxent(); int proc_pidfdinfo(int pid, int fd, int flavor, Structure buffer, int buffersize); }
oshi/oshi
oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
1,969
/* protocol dependent part, v4 only in last element */
block_comment
nl
/* * Copyright 2016-2022 The OSHI Project Contributors * SPDX-License-Identifier: MIT */ package oshi.jna.platform.mac; import com.sun.jna.Native; import com.sun.jna.Structure; import com.sun.jna.Structure.FieldOrder; import com.sun.jna.Union; import oshi.jna.platform.unix.CLibrary; import oshi.util.Util; /** * System class. This class should be considered non-API as it may be removed if/when its code is incorporated into the * JNA project. */ public interface SystemB extends com.sun.jna.platform.mac.SystemB, CLibrary { SystemB INSTANCE = Native.load("System", SystemB.class); int PROC_PIDLISTFDS = 1; int PROX_FDTYPE_SOCKET = 2; int PROC_PIDFDSOCKETINFO = 3; int TSI_T_NTIMERS = 4; int SOCKINFO_IN = 1; int SOCKINFO_TCP = 2; int UTX_USERSIZE = 256; int UTX_LINESIZE = 32; int UTX_IDSIZE = 4; int UTX_HOSTSIZE = 256; int AF_INET = 2; // The Internet Protocol version 4 (IPv4) address family. int AF_INET6 = 30; // The Internet Protocol version 6 (IPv6) address family. /** * Mac connection info */ @FieldOrder({ "ut_user", "ut_id", "ut_line", "ut_pid", "ut_type", "ut_tv", "ut_host", "ut_pad" }) class MacUtmpx extends Structure { public byte[] ut_user = new byte[UTX_USERSIZE]; // login name public byte[] ut_id = new byte[UTX_IDSIZE]; // id public byte[] ut_line = new byte[UTX_LINESIZE]; // tty name public int ut_pid; // process id creating the entry public short ut_type; // type of this entry public Timeval ut_tv; // time entry was created public byte[] ut_host = new byte[UTX_HOSTSIZE]; // host name public byte[] ut_pad = new byte[16]; // reserved for future use } /** * Mac file descriptor info */ @FieldOrder({ "proc_fd", "proc_fdtype" }) class ProcFdInfo extends Structure { public int proc_fd; public int proc_fdtype; } /** * Mac internet socket info */ @FieldOrder({ "insi_fport", "insi_lport", "insi_gencnt", "insi_flags", "insi_flow", "insi_vflag", "insi_ip_ttl", "rfu_1", "insi_faddr", "insi_laddr", "insi_v4", "insi_v6" }) class InSockInfo extends Structure { public int insi_fport; /* foreign port */ public int insi_lport; /* local port */ public long insi_gencnt; /* generation count of this instance */ public int insi_flags; /* generic IP/datagram flags */ public int insi_flow; public byte insi_vflag; /* ini_IPV4 or ini_IPV6 */ public byte insi_ip_ttl; /* time to live proto */ public int rfu_1; /* reserved */ /* protocol dependent part,<SUF>*/ public int[] insi_faddr = new int[4]; /* foreign host table entry */ public int[] insi_laddr = new int[4]; /* local host table entry */ public byte insi_v4; /* type of service */ public byte[] insi_v6 = new byte[9]; } /** * Mac TCP socket info */ @FieldOrder({ "tcpsi_ini", "tcpsi_state", "tcpsi_timer", "tcpsi_mss", "tcpsi_flags", "rfu_1", "tcpsi_tp" }) class TcpSockInfo extends Structure { public InSockInfo tcpsi_ini; public int tcpsi_state; public int[] tcpsi_timer = new int[TSI_T_NTIMERS]; public int tcpsi_mss; public int tcpsi_flags; public int rfu_1; /* reserved */ public long tcpsi_tp; /* opaque handle of TCP protocol control block */ } /** * Mack IP Socket Info */ @FieldOrder({ "soi_stat", "soi_so", "soi_pcb", "soi_type", "soi_protocol", "soi_family", "soi_options", "soi_linger", "soi_state", "soi_qlen", "soi_incqlen", "soi_qlimit", "soi_timeo", "soi_error", "soi_oobmark", "soi_rcv", "soi_snd", "soi_kind", "rfu_1", "soi_proto" }) class SocketInfo extends Structure { public long[] soi_stat = new long[17]; // vinfo_stat public long soi_so; /* opaque handle of socket */ public long soi_pcb; /* opaque handle of protocol control block */ public int soi_type; public int soi_protocol; public int soi_family; public short soi_options; public short soi_linger; public short soi_state; public short soi_qlen; public short soi_incqlen; public short soi_qlimit; public short soi_timeo; public short soi_error; public int soi_oobmark; public int[] soi_rcv = new int[6]; // sockbuf_info public int[] soi_snd = new int[6]; // sockbuf_info public int soi_kind; public int rfu_1; /* reserved */ public Pri soi_proto; } /** * Mac file info */ @FieldOrder({ "fi_openflags", "fi_status", "fi_offset", "fi_type", "fi_guardflags" }) class ProcFileInfo extends Structure { public int fi_openflags; public int fi_status; public long fi_offset; public int fi_type; public int fi_guardflags; } /** * Mac socket info */ @FieldOrder({ "pfi", "psi" }) class SocketFdInfo extends Structure implements AutoCloseable { public ProcFileInfo pfi; public SocketInfo psi; @Override public void close() { Util.freeMemory(getPointer()); } } /** * Union for TCP or internet socket info */ class Pri extends Union { public InSockInfo pri_in; public TcpSockInfo pri_tcp; // max element is 524 bytes public byte[] max_size = new byte[524]; } /** * Reads a line from the current file position in the utmp file. It returns a pointer to a structure containing the * fields of the line. * <p> * Not thread safe * * @return a {@link MacUtmpx} on success, and NULL on failure (which includes the "record not found" case) */ MacUtmpx getutxent(); int proc_pidfdinfo(int pid, int fd, int flavor, Structure buffer, int buffersize); }
19350_5
package net.osmand.plus.configmap; import android.animation.ValueAnimator; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import net.osmand.plus.R; import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.utils.AndroidUtils; import net.osmand.plus.utils.ColorUtilities; import net.osmand.plus.widgets.ctxmenu.data.ContextMenuItem; import java.util.HashMap; import java.util.Map; public class CategoryAnimator { private static final Map<ContextMenuItem, ValueAnimator> runningAnimations = new HashMap<>(); private static final float MAX_ROTATION = 180; private final Context ctx; private final boolean isExpanding; private final ContextMenuItem category; private final View header; private final ImageView ivIndicator; private final TextView tvDescription; private final View itemsContainer; private final View divider; // common parameters private float descHeight; private float minHeaderHeight; private float maxHeaderHeight; private int maxListHeight; private int maxDuration; private CategoryAnimator(@NonNull ContextMenuItem category, @NonNull View view, boolean isExpanding) { this.category = category; this.ctx = view.getContext(); this.isExpanding = isExpanding; header = view.findViewById(R.id.button_container); ivIndicator = view.findViewById(R.id.explicit_indicator); tvDescription = view.findViewById(R.id.description); itemsContainer = view.findViewById(R.id.items_container); divider = view.findViewById(R.id.divider); calculateCommonParameters(); } private ValueAnimator startAnimation() { onBeforeAnimation(); // Determine passed distance in current direction float currentHeaderHeight = header.getHeight(); float wholeDistance = maxHeaderHeight - minHeaderHeight; float leftDistance = isExpanding ? (currentHeaderHeight - minHeaderHeight) : (maxHeaderHeight - currentHeaderHeight); float passedDistance = wholeDistance - leftDistance; // Determine restrictions int minValue = 0; int maxValue = 100; int startValue = (int) ((passedDistance / wholeDistance) * maxValue); // Determine correct animation duration int calculatedDuration = (int) ((float) maxDuration / maxValue * (maxValue - startValue)); int duration = Math.max(calculatedDuration, 0); // Create animation ValueAnimator animation = ValueAnimator.ofInt(startValue, maxValue); animation.setDuration(duration); animation.addUpdateListener(animator -> { int val = (Integer) animator.getAnimatedValue(); onMainAnimationUpdate(val, minValue, maxValue); if (val == maxValue) { onMainAnimationFinished(); if (isExpanding) { runningAnimations.remove(category); } else { onShowDescriptionAnimation(minValue, maxValue, duration); } } }); animation.start(); return animation; } private void calculateCommonParameters() { descHeight = getDimen(R.dimen.default_desc_line_height); int titleHeight = getDimen(R.dimen.default_title_line_height); int verticalMargin = getDimen(R.dimen.content_padding_small) * 2; minHeaderHeight = titleHeight + verticalMargin - AndroidUtils.dpToPx(ctx, 3); maxHeaderHeight = minHeaderHeight + descHeight; itemsContainer.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); maxListHeight = itemsContainer.getMeasuredHeight(); maxDuration = getInteger(isExpanding ? android.R.integer.config_mediumAnimTime : android.R.integer.config_shortAnimTime); } private void onBeforeAnimation() { // Make all views visible before animate them tvDescription.setVisibility(View.VISIBLE); itemsContainer.setVisibility(View.VISIBLE); divider.setVisibility(View.VISIBLE); // Description will be invisible until collapsing animation finished boolean hasDescription = category.getDescription() != null; tvDescription.setVisibility(hasDescription ? View.INVISIBLE : View.GONE); } private void onMainAnimationUpdate(int val, float minValue, float maxValue) { // Set indicator rotation float rotation = MAX_ROTATION / maxValue * val; ivIndicator.setRotation(isExpanding ? -rotation : rotation); // Set header height float headerIncrement = descHeight / maxValue * val; float headerHeight = isExpanding ? maxHeaderHeight - headerIncrement : minHeaderHeight + headerIncrement; ViewGroup.LayoutParams layoutParams = header.getLayoutParams(); layoutParams.height = (int) headerHeight; header.setLayoutParams(layoutParams); // Set list alpha float listAlpha = ColorUtilities.getProportionalAlpha(minValue, maxValue, val); float listInverseAlpha = 1.0f - listAlpha; itemsContainer.setAlpha(isExpanding ? listInverseAlpha : listAlpha); // Set list height float increment = (float) maxListHeight / maxValue * val; float height = isExpanding ? increment : maxListHeight - increment; ViewGroup.LayoutParams layoutParams1 = itemsContainer.getLayoutParams(); layoutParams1.height = (int) height; itemsContainer.setLayoutParams(layoutParams1); } private void onMainAnimationFinished() { // Set indicator icon and reset its rotation int indicatorRes = isExpanding ? R.drawable.ic_action_arrow_up : R.drawable.ic_action_arrow_down; ivIndicator.setRotation(0); ivIndicator.setImageResource(indicatorRes); boolean hasDescription = category.getDescription() != null; // Update views visibility AndroidUiHelper.updateVisibility(divider, isExpanding); AndroidUiHelper.updateVisibility(tvDescription, !isExpanding && hasDescription); AndroidUiHelper.updateVisibility(itemsContainer, isExpanding); // Set items container height as WRAP_CONTENT LayoutParams params = itemsContainer.getLayoutParams(); params.height = LayoutParams.WRAP_CONTENT; itemsContainer.setLayoutParams(params); } private void onShowDescriptionAnimation(int minValue, int maxValue, int duration) { ValueAnimator animator = ValueAnimator.ofInt(minValue, maxValue); animator.setDuration(duration); animator.addUpdateListener(animation -> { int val = (Integer) animator.getAnimatedValue(); float alpha = ColorUtilities.getProportionalAlpha(minValue, maxValue, val); tvDescription.setAlpha(1.0f - alpha); if (maxValue == val) { runningAnimations.remove(category); } }); animator.start(); } private int getDimen(int id) { return ctx.getResources().getDimensionPixelSize(id); } private int getInteger(int id) { return ctx.getResources().getInteger(id); } public static void startCollapsing(@NonNull ContextMenuItem category, @NonNull View view) { tryStartAnimation(category, view, false); } public static void startExpanding(@NonNull ContextMenuItem category, @NonNull View view) { tryStartAnimation(category, view, true); } private static void tryStartAnimation(@NonNull ContextMenuItem category, @NonNull View view, boolean isExpanding) { CategoryAnimator animator = new CategoryAnimator(category, view, isExpanding); // Stop previous animation for the category ValueAnimator runningAnimation = runningAnimations.remove(category); if (runningAnimation != null && runningAnimation.isRunning()) { runningAnimation.end(); } // Create and run a new animation runningAnimations.put(category, animator.startAnimation()); } }
osmandapp/OsmAnd
OsmAnd/src/net/osmand/plus/configmap/CategoryAnimator.java
2,133
// Set header height
line_comment
nl
package net.osmand.plus.configmap; import android.animation.ValueAnimator; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import net.osmand.plus.R; import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.utils.AndroidUtils; import net.osmand.plus.utils.ColorUtilities; import net.osmand.plus.widgets.ctxmenu.data.ContextMenuItem; import java.util.HashMap; import java.util.Map; public class CategoryAnimator { private static final Map<ContextMenuItem, ValueAnimator> runningAnimations = new HashMap<>(); private static final float MAX_ROTATION = 180; private final Context ctx; private final boolean isExpanding; private final ContextMenuItem category; private final View header; private final ImageView ivIndicator; private final TextView tvDescription; private final View itemsContainer; private final View divider; // common parameters private float descHeight; private float minHeaderHeight; private float maxHeaderHeight; private int maxListHeight; private int maxDuration; private CategoryAnimator(@NonNull ContextMenuItem category, @NonNull View view, boolean isExpanding) { this.category = category; this.ctx = view.getContext(); this.isExpanding = isExpanding; header = view.findViewById(R.id.button_container); ivIndicator = view.findViewById(R.id.explicit_indicator); tvDescription = view.findViewById(R.id.description); itemsContainer = view.findViewById(R.id.items_container); divider = view.findViewById(R.id.divider); calculateCommonParameters(); } private ValueAnimator startAnimation() { onBeforeAnimation(); // Determine passed distance in current direction float currentHeaderHeight = header.getHeight(); float wholeDistance = maxHeaderHeight - minHeaderHeight; float leftDistance = isExpanding ? (currentHeaderHeight - minHeaderHeight) : (maxHeaderHeight - currentHeaderHeight); float passedDistance = wholeDistance - leftDistance; // Determine restrictions int minValue = 0; int maxValue = 100; int startValue = (int) ((passedDistance / wholeDistance) * maxValue); // Determine correct animation duration int calculatedDuration = (int) ((float) maxDuration / maxValue * (maxValue - startValue)); int duration = Math.max(calculatedDuration, 0); // Create animation ValueAnimator animation = ValueAnimator.ofInt(startValue, maxValue); animation.setDuration(duration); animation.addUpdateListener(animator -> { int val = (Integer) animator.getAnimatedValue(); onMainAnimationUpdate(val, minValue, maxValue); if (val == maxValue) { onMainAnimationFinished(); if (isExpanding) { runningAnimations.remove(category); } else { onShowDescriptionAnimation(minValue, maxValue, duration); } } }); animation.start(); return animation; } private void calculateCommonParameters() { descHeight = getDimen(R.dimen.default_desc_line_height); int titleHeight = getDimen(R.dimen.default_title_line_height); int verticalMargin = getDimen(R.dimen.content_padding_small) * 2; minHeaderHeight = titleHeight + verticalMargin - AndroidUtils.dpToPx(ctx, 3); maxHeaderHeight = minHeaderHeight + descHeight; itemsContainer.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); maxListHeight = itemsContainer.getMeasuredHeight(); maxDuration = getInteger(isExpanding ? android.R.integer.config_mediumAnimTime : android.R.integer.config_shortAnimTime); } private void onBeforeAnimation() { // Make all views visible before animate them tvDescription.setVisibility(View.VISIBLE); itemsContainer.setVisibility(View.VISIBLE); divider.setVisibility(View.VISIBLE); // Description will be invisible until collapsing animation finished boolean hasDescription = category.getDescription() != null; tvDescription.setVisibility(hasDescription ? View.INVISIBLE : View.GONE); } private void onMainAnimationUpdate(int val, float minValue, float maxValue) { // Set indicator rotation float rotation = MAX_ROTATION / maxValue * val; ivIndicator.setRotation(isExpanding ? -rotation : rotation); // Set header<SUF> float headerIncrement = descHeight / maxValue * val; float headerHeight = isExpanding ? maxHeaderHeight - headerIncrement : minHeaderHeight + headerIncrement; ViewGroup.LayoutParams layoutParams = header.getLayoutParams(); layoutParams.height = (int) headerHeight; header.setLayoutParams(layoutParams); // Set list alpha float listAlpha = ColorUtilities.getProportionalAlpha(minValue, maxValue, val); float listInverseAlpha = 1.0f - listAlpha; itemsContainer.setAlpha(isExpanding ? listInverseAlpha : listAlpha); // Set list height float increment = (float) maxListHeight / maxValue * val; float height = isExpanding ? increment : maxListHeight - increment; ViewGroup.LayoutParams layoutParams1 = itemsContainer.getLayoutParams(); layoutParams1.height = (int) height; itemsContainer.setLayoutParams(layoutParams1); } private void onMainAnimationFinished() { // Set indicator icon and reset its rotation int indicatorRes = isExpanding ? R.drawable.ic_action_arrow_up : R.drawable.ic_action_arrow_down; ivIndicator.setRotation(0); ivIndicator.setImageResource(indicatorRes); boolean hasDescription = category.getDescription() != null; // Update views visibility AndroidUiHelper.updateVisibility(divider, isExpanding); AndroidUiHelper.updateVisibility(tvDescription, !isExpanding && hasDescription); AndroidUiHelper.updateVisibility(itemsContainer, isExpanding); // Set items container height as WRAP_CONTENT LayoutParams params = itemsContainer.getLayoutParams(); params.height = LayoutParams.WRAP_CONTENT; itemsContainer.setLayoutParams(params); } private void onShowDescriptionAnimation(int minValue, int maxValue, int duration) { ValueAnimator animator = ValueAnimator.ofInt(minValue, maxValue); animator.setDuration(duration); animator.addUpdateListener(animation -> { int val = (Integer) animator.getAnimatedValue(); float alpha = ColorUtilities.getProportionalAlpha(minValue, maxValue, val); tvDescription.setAlpha(1.0f - alpha); if (maxValue == val) { runningAnimations.remove(category); } }); animator.start(); } private int getDimen(int id) { return ctx.getResources().getDimensionPixelSize(id); } private int getInteger(int id) { return ctx.getResources().getInteger(id); } public static void startCollapsing(@NonNull ContextMenuItem category, @NonNull View view) { tryStartAnimation(category, view, false); } public static void startExpanding(@NonNull ContextMenuItem category, @NonNull View view) { tryStartAnimation(category, view, true); } private static void tryStartAnimation(@NonNull ContextMenuItem category, @NonNull View view, boolean isExpanding) { CategoryAnimator animator = new CategoryAnimator(category, view, isExpanding); // Stop previous animation for the category ValueAnimator runningAnimation = runningAnimations.remove(category); if (runningAnimation != null && runningAnimation.isRunning()) { runningAnimation.end(); } // Create and run a new animation runningAnimations.put(category, animator.startAnimation()); } }
119373_60
package org.osmdroid.views.overlay; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Path; import android.graphics.Rect; import android.util.DisplayMetrics; import android.view.WindowManager; import org.osmdroid.api.IGeoPoint; import org.osmdroid.library.R; import org.osmdroid.util.GeoPoint; import org.osmdroid.util.constants.GeoConstants; import org.osmdroid.views.MapView; import org.osmdroid.views.Projection; import java.lang.reflect.Field; import java.util.Locale; /** * ScaleBarOverlay.java * <p> * Puts a scale bar in the top-left corner of the screen, offset by a configurable * number of pixels. The bar is scaled to 1-inch length by querying for the physical * DPI of the screen. The size of the bar is printed between the tick marks. A * vertical (longitude) scale can be enabled. Scale is printed in metric (kilometers, * meters), imperial (miles, feet) and nautical (nautical miles, feet). * <p> * Author: Erik Burrows, Griffin Systems LLC * [email protected] * <p> * Change Log: * 2010-10-08: Inclusion to osmdroid trunk * 2015-12-17: Allow for top, bottom, left or right placement by W. Strickling * <p> * Usage: * <code> * MapView map = new MapView(...); * ScaleBarOverlay scaleBar = new ScaleBarOverlay(map); // Thiw is an important change of calling! * <p> * map.getOverlays().add(scaleBar); * </code> * <p> * To Do List: * 1. Allow for top, bottom, left or right placement. // done in this changement * 2. Scale bar to precise displayed scale text after rounding. */ public class ScaleBarOverlay extends Overlay implements GeoConstants { // =========================================================== // Fields // =========================================================== private static final Rect sTextBoundsRect = new Rect(); public enum UnitsOfMeasure { metric, imperial, nautical } // Defaults int xOffset = 10; int yOffset = 10; double minZoom = 0; UnitsOfMeasure unitsOfMeasure = UnitsOfMeasure.metric; boolean latitudeBar = true; boolean longitudeBar = false; protected boolean alignBottom = false; protected boolean alignRight = false; // Internal private Context context; private MapView mMapView; protected final Path barPath = new Path(); protected final Rect latitudeBarRect = new Rect(); protected final Rect longitudeBarRect = new Rect(); private double lastZoomLevel = -1; private double lastLatitude = 0.0; public float xdpi; public float ydpi; public int screenWidth; public int screenHeight; private Paint barPaint; private Paint bgPaint; private Paint textPaint; private boolean centred = false; private boolean adjustLength = false; private float maxLength; /** * @since 6.1.0 */ private int mMapWidth; /** * @since 6.1.0 */ private int mMapHeight; // =========================================================== // Constructors // =========================================================== public ScaleBarOverlay(final MapView mapView) { this(mapView, mapView.getContext(), 0, 0); } /** * @since 6.1.0 */ public ScaleBarOverlay(final Context pContext, final int pMapWidth, final int pMapHeight) { this(null, pContext, pMapWidth, pMapHeight); } /** * @since 6.1.0 */ private ScaleBarOverlay(final MapView pMapView, final Context pContext, final int pMapWidth, final int pMapHeight) { super(); mMapView = pMapView; context = pContext; mMapWidth = pMapWidth; mMapHeight = pMapHeight; final DisplayMetrics dm = context.getResources().getDisplayMetrics(); this.barPaint = new Paint(); this.barPaint.setColor(Color.BLACK); this.barPaint.setAntiAlias(true); this.barPaint.setStyle(Style.STROKE); this.barPaint.setAlpha(255); this.barPaint.setStrokeWidth(2 * dm.density); this.bgPaint = null; this.textPaint = new Paint(); this.textPaint.setColor(Color.BLACK); this.textPaint.setAntiAlias(true); this.textPaint.setStyle(Style.FILL); this.textPaint.setAlpha(255); this.textPaint.setTextSize(10 * dm.density); this.xdpi = dm.xdpi; this.ydpi = dm.ydpi; this.screenWidth = dm.widthPixels; this.screenHeight = dm.heightPixels; // DPI corrections for specific models String manufacturer = null; try { final Field field = android.os.Build.class.getField("MANUFACTURER"); manufacturer = (String) field.get(null); } catch (final Exception ignore) { } if ("motorola".equals(manufacturer) && "DROIDX".equals(android.os.Build.MODEL)) { // If the screen is rotated, flip the x and y dpi values WindowManager windowManager = (WindowManager) this.context .getSystemService(Context.WINDOW_SERVICE); if (windowManager != null && windowManager.getDefaultDisplay().getOrientation() > 0) { this.xdpi = (float) (this.screenWidth / 3.75); this.ydpi = (float) (this.screenHeight / 2.1); } else { this.xdpi = (float) (this.screenWidth / 2.1); this.ydpi = (float) (this.screenHeight / 3.75); } } else if ("motorola".equals(manufacturer) && "Droid".equals(android.os.Build.MODEL)) { // http://www.mail-archive.com/[email protected]/msg109497.html this.xdpi = 264; this.ydpi = 264; } // set default max length to 1 inch maxLength = 2.54f; } // =========================================================== // Getter & Setter // =========================================================== /** * Sets the minimum zoom level for the scale bar to be drawn. * * @param zoom minimum zoom level */ public void setMinZoom(final double zoom) { this.minZoom = zoom; } /** * Sets the scale bar screen offset for the bar. Note: if the bar is set to be drawn centered, * this will be the middle of the bar, otherwise the top left corner. * * @param x x screen offset * @param y z screen offset */ public void setScaleBarOffset(final int x, final int y) { xOffset = x; yOffset = y; } /** * Sets the bar's line width. (the default is 2) * * @param width the new line width */ public void setLineWidth(final float width) { this.barPaint.setStrokeWidth(width); } /** * Sets the text size. (the default is 12) * * @param size the new text size */ public void setTextSize(final float size) { this.textPaint.setTextSize(size); } /** * Sets the units of measure to be shown in the scale bar */ public void setUnitsOfMeasure(UnitsOfMeasure unitsOfMeasure) { this.unitsOfMeasure = unitsOfMeasure; lastZoomLevel = -1; // Force redraw of scalebar } /** * Gets the units of measure to be shown in the scale bar */ public UnitsOfMeasure getUnitsOfMeasure() { return unitsOfMeasure; } /** * Latitudinal / horizontal scale bar flag * * @param latitude */ public void drawLatitudeScale(final boolean latitude) { this.latitudeBar = latitude; lastZoomLevel = -1; // Force redraw of scalebar } /** * Longitudinal / vertical scale bar flag * * @param longitude */ public void drawLongitudeScale(final boolean longitude) { this.longitudeBar = longitude; lastZoomLevel = -1; // Force redraw of scalebar } /** * Flag to draw the bar centered around the set offset coordinates or to the right/bottom of the * coordinates (default) * * @param centred set true to centre the bar around the given screen coordinates */ public void setCentred(final boolean centred) { this.centred = centred; alignBottom = !centred; alignRight = !centred; lastZoomLevel = -1; // Force redraw of scalebar } public void setAlignBottom(final boolean alignBottom) { this.centred = false; this.alignBottom = alignBottom; lastZoomLevel = -1; // Force redraw of scalebar } public void setAlignRight(final boolean alignRight) { this.centred = false; this.alignRight = alignRight; lastZoomLevel = -1; // Force redraw of scalebar } /** * Return's the paint used to draw the bar * * @return the paint used to draw the bar */ public Paint getBarPaint() { return barPaint; } /** * Sets the paint for drawing the bar * * @param pBarPaint bar drawing paint */ public void setBarPaint(final Paint pBarPaint) { if (pBarPaint == null) { throw new IllegalArgumentException("pBarPaint argument cannot be null"); } barPaint = pBarPaint; lastZoomLevel = -1; // Force redraw of scalebar } /** * Returns the paint used to draw the text * * @return the paint used to draw the text */ public Paint getTextPaint() { return textPaint; } /** * Sets the paint for drawing the text * * @param pTextPaint text drawing paint */ public void setTextPaint(final Paint pTextPaint) { if (pTextPaint == null) { throw new IllegalArgumentException("pTextPaint argument cannot be null"); } textPaint = pTextPaint; lastZoomLevel = -1; // Force redraw of scalebar } /** * Sets the background paint. Set to null to disable drawing of background (default) * * @param pBgPaint the paint for colouring the bar background */ public void setBackgroundPaint(final Paint pBgPaint) { bgPaint = pBgPaint; lastZoomLevel = -1; // Force redraw of scalebar } /** * If enabled, the bar will automatically adjust the length to reflect a round number (starting * with 1, 2 or 5). If disabled, the bar will always be drawn in full length representing a * fractional distance. */ public void setEnableAdjustLength(boolean adjustLength) { this.adjustLength = adjustLength; lastZoomLevel = -1; // Force redraw of scalebar } /** * Sets the maximum bar length. If adjustLength is disabled this will match exactly the length * of the bar. If adjustLength is enabled, the bar will be shortened to reflect a round number * in length. * * @param pMaxLengthInCm maximum length of the bar in the screen in cm. Default is 2.54 (=1 inch) */ public void setMaxLength(final float pMaxLengthInCm) { this.maxLength = pMaxLengthInCm; lastZoomLevel = -1; // Force redraw of scalebar } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== @Override public void draw(Canvas c, Projection projection) { final double zoomLevel = projection.getZoomLevel(); if (zoomLevel < minZoom) { return; } final Rect rect = projection.getIntrinsicScreenRect(); int _screenWidth = rect.width(); int _screenHeight = rect.height(); boolean screenSizeChanged = _screenHeight != screenHeight || _screenWidth != screenWidth; screenHeight = _screenHeight; screenWidth = _screenWidth; final IGeoPoint center = projection.fromPixels(screenWidth / 2, screenHeight / 2, null); if (zoomLevel != lastZoomLevel || center.getLatitude() != lastLatitude || screenSizeChanged) { lastZoomLevel = zoomLevel; lastLatitude = center.getLatitude(); rebuildBarPath(projection); } int offsetX = xOffset; int offsetY = yOffset; if (alignBottom) offsetY *= -1; if (alignRight) offsetX *= -1; if (centred && latitudeBar) offsetX += -latitudeBarRect.width() / 2; if (centred && longitudeBar) offsetY += -longitudeBarRect.height() / 2; projection.save(c, false, true); c.translate(offsetX, offsetY); if (latitudeBar && bgPaint != null) c.drawRect(latitudeBarRect, bgPaint); if (longitudeBar && bgPaint != null) { // Don't draw on top of latitude background... int offsetTop = latitudeBar ? latitudeBarRect.height() : 0; c.drawRect(longitudeBarRect.left, longitudeBarRect.top + offsetTop, longitudeBarRect.right, longitudeBarRect.bottom, bgPaint); } c.drawPath(barPath, barPaint); if (latitudeBar) { drawLatitudeText(c, projection); } if (longitudeBar) { drawLongitudeText(c, projection); } projection.restore(c, true); } // =========================================================== // Methods // =========================================================== public void disableScaleBar() { setEnabled(false); } public void enableScaleBar() { setEnabled(true); } private void drawLatitudeText(final Canvas canvas, final Projection projection) { // calculate dots per centimeter int xdpcm = (int) ((float) xdpi / 2.54); // get length in pixel int xLen = (int) (maxLength * xdpcm); // Two points, xLen apart, at scale bar screen location IGeoPoint p1 = projection.fromPixels((screenWidth / 2) - (xLen / 2), yOffset, null); IGeoPoint p2 = projection.fromPixels((screenWidth / 2) + (xLen / 2), yOffset, null); // get distance in meters between points final double xMeters = ((GeoPoint) p1).distanceToAsDouble(p2); // get adjusted distance, shortened to the next lower number starting with 1, 2 or 5 final double xMetersAdjusted = this.adjustLength ? adjustScaleBarLength(xMeters) : xMeters; // get adjusted length in pixels final int xBarLengthPixels = (int) (xLen * xMetersAdjusted / xMeters); // create text final String xMsg = scaleBarLengthText(xMetersAdjusted); textPaint.getTextBounds(xMsg, 0, xMsg.length(), sTextBoundsRect); final int xTextSpacing = (int) (sTextBoundsRect.height() / 5.0); float x = xBarLengthPixels / 2 - sTextBoundsRect.width() / 2; if (alignRight) x += screenWidth - xBarLengthPixels; float y; if (alignBottom) { y = screenHeight - xTextSpacing * 2; } else y = sTextBoundsRect.height() + xTextSpacing; canvas.drawText(xMsg, x, y, textPaint); } private void drawLongitudeText(final Canvas canvas, final Projection projection) { // calculate dots per centimeter int ydpcm = (int) ((float) ydpi / 2.54); // get length in pixel int yLen = (int) (maxLength * ydpcm); // Two points, yLen apart, at scale bar screen location IGeoPoint p1 = projection .fromPixels(screenWidth / 2, (screenHeight / 2) - (yLen / 2), null); IGeoPoint p2 = projection .fromPixels(screenWidth / 2, (screenHeight / 2) + (yLen / 2), null); // get distance in meters between points final double yMeters = ((GeoPoint) p1).distanceToAsDouble(p2); // get adjusted distance, shortened to the next lower number starting with 1, 2 or 5 final double yMetersAdjusted = this.adjustLength ? adjustScaleBarLength(yMeters) : yMeters; // get adjusted length in pixels final int yBarLengthPixels = (int) (yLen * yMetersAdjusted / yMeters); // create text final String yMsg = scaleBarLengthText(yMetersAdjusted); textPaint.getTextBounds(yMsg, 0, yMsg.length(), sTextBoundsRect); final int yTextSpacing = (int) (sTextBoundsRect.height() / 5.0); float x; if (alignRight) { x = screenWidth - yTextSpacing * 2; } else x = sTextBoundsRect.height() + yTextSpacing; float y = yBarLengthPixels / 2 + sTextBoundsRect.width() / 2; if (alignBottom) y += screenHeight - yBarLengthPixels; canvas.save(); canvas.rotate(-90, x, y); canvas.drawText(yMsg, x, y, textPaint); canvas.restore(); } protected void rebuildBarPath(final Projection projection) { //** modified to protected // We want the scale bar to be as long as the closest round-number miles/kilometers // to 1-inch at the latitude at the current center of the screen. // calculate dots per centimeter int xdpcm = (int) ((float) xdpi / 2.54); int ydpcm = (int) ((float) ydpi / 2.54); // get length in pixel int xLen = (int) (maxLength * xdpcm); int yLen = (int) (maxLength * ydpcm); // Two points, xLen apart, at scale bar screen location IGeoPoint p1 = projection.fromPixels((screenWidth / 2) - (xLen / 2), yOffset, null); IGeoPoint p2 = projection.fromPixels((screenWidth / 2) + (xLen / 2), yOffset, null); // get distance in meters between points final double xMeters = ((GeoPoint) p1).distanceToAsDouble(p2); // get adjusted distance, shortened to the next lower number starting with 1, 2 or 5 final double xMetersAdjusted = this.adjustLength ? adjustScaleBarLength(xMeters) : xMeters; // get adjusted length in pixels final int xBarLengthPixels = (int) (xLen * xMetersAdjusted / xMeters); // Two points, yLen apart, at scale bar screen location p1 = projection.fromPixels(screenWidth / 2, (screenHeight / 2) - (yLen / 2), null); p2 = projection.fromPixels(screenWidth / 2, (screenHeight / 2) + (yLen / 2), null); // get distance in meters between points final double yMeters = ((GeoPoint) p1).distanceToAsDouble(p2); // get adjusted distance, shortened to the next lower number starting with 1, 2 or 5 final double yMetersAdjusted = this.adjustLength ? adjustScaleBarLength(yMeters) : yMeters; // get adjusted length in pixels final int yBarLengthPixels = (int) (yLen * yMetersAdjusted / yMeters); // create text final String xMsg = scaleBarLengthText(xMetersAdjusted); final Rect xTextRect = new Rect(); textPaint.getTextBounds(xMsg, 0, xMsg.length(), xTextRect); int xTextSpacing = (int) (xTextRect.height() / 5.0); // create text final String yMsg = scaleBarLengthText(yMetersAdjusted); final Rect yTextRect = new Rect(); textPaint.getTextBounds(yMsg, 0, yMsg.length(), yTextRect); int yTextSpacing = (int) (yTextRect.height() / 5.0); int xTextHeight = xTextRect.height(); int yTextHeight = yTextRect.height(); barPath.rewind(); //** alignBottom ad-ons int barOriginX = 0; int barOriginY = 0; int barToX = xBarLengthPixels; int barToY = yBarLengthPixels; if (alignBottom) { xTextSpacing *= -1; xTextHeight *= -1; barOriginY = getMapHeight(); barToY = barOriginY - yBarLengthPixels; } if (alignRight) { yTextSpacing *= -1; yTextHeight *= -1; barOriginX = getMapWidth(); barToX = barOriginX - xBarLengthPixels; } if (latitudeBar) { // draw latitude bar barPath.moveTo(barToX, barOriginY + xTextHeight + xTextSpacing * 2); barPath.lineTo(barToX, barOriginY); barPath.lineTo(barOriginX, barOriginY); if (!longitudeBar) { barPath.lineTo(barOriginX, barOriginY + xTextHeight + xTextSpacing * 2); } latitudeBarRect.set(barOriginX, barOriginY, barToX, barOriginY + xTextHeight + xTextSpacing * 2); } if (longitudeBar) { // draw longitude bar if (!latitudeBar) { barPath.moveTo(barOriginX + yTextHeight + yTextSpacing * 2, barOriginY); barPath.lineTo(barOriginX, barOriginY); } barPath.lineTo(barOriginX, barToY); barPath.lineTo(barOriginX + yTextHeight + yTextSpacing * 2, barToY); longitudeBarRect.set(barOriginX, barOriginY, barOriginX + yTextHeight + yTextSpacing * 2, barToY); } } /** * Returns a reduced length that starts with 1, 2 or 5 and trailing zeros. If set to nautical or * imperial the input will be transformed before and after the reduction so that the result * holds in that respective unit. * * @param length length to round * @return reduced, rounded (in m, nm or mi depending on setting) result */ private double adjustScaleBarLength(double length) { long pow = 0; boolean feet = false; if (unitsOfMeasure == UnitsOfMeasure.imperial) { if (length >= GeoConstants.METERS_PER_STATUTE_MILE / 5) length = length / GeoConstants.METERS_PER_STATUTE_MILE; else { length = length * GeoConstants.FEET_PER_METER; feet = true; } } else if (unitsOfMeasure == UnitsOfMeasure.nautical) { if (length >= GeoConstants.METERS_PER_NAUTICAL_MILE / 5) length = length / GeoConstants.METERS_PER_NAUTICAL_MILE; else { length = length * GeoConstants.FEET_PER_METER; feet = true; } } while (length >= 10) { pow++; length /= 10; } while (length < 1 && length > 0) { pow--; length *= 10; } if (length < 2) { length = 1; } else if (length < 5) { length = 2; } else { length = 5; } if (feet) length = length / GeoConstants.FEET_PER_METER; else if (unitsOfMeasure == UnitsOfMeasure.imperial) length = length * GeoConstants.METERS_PER_STATUTE_MILE; else if (unitsOfMeasure == UnitsOfMeasure.nautical) length = length * GeoConstants.METERS_PER_NAUTICAL_MILE; length *= Math.pow(10, pow); return length; } protected String scaleBarLengthText(final double meters) { switch (unitsOfMeasure) { default: case metric: if (meters >= 1000 * 5) { return getConvertedScaleString(meters, UnitOfMeasure.kilometer, "%.0f"); } else if (meters >= 1000 / 5) { return getConvertedScaleString(meters, UnitOfMeasure.kilometer, "%.1f"); } else if (meters >= 20) { return getConvertedScaleString(meters, UnitOfMeasure.meter, "%.0f"); } else { return getConvertedScaleString(meters, UnitOfMeasure.meter, "%.2f"); } case imperial: if (meters >= METERS_PER_STATUTE_MILE * 5) { return getConvertedScaleString(meters, UnitOfMeasure.statuteMile, "%.0f"); } else if (meters >= METERS_PER_STATUTE_MILE / 5) { return getConvertedScaleString(meters, UnitOfMeasure.statuteMile, "%.1f"); } else { return getConvertedScaleString(meters, UnitOfMeasure.foot, "%.0f"); } case nautical: if (meters >= METERS_PER_NAUTICAL_MILE * 5) { return getConvertedScaleString(meters, UnitOfMeasure.nauticalMile, "%.0f"); } else if (meters >= METERS_PER_NAUTICAL_MILE / 5) { return getConvertedScaleString(meters, UnitOfMeasure.nauticalMile, "%.1f"); } else { return getConvertedScaleString(meters, UnitOfMeasure.foot, "%.0f"); } } } @Override public void onDetach(MapView mapView) { this.context = null; this.mMapView = null; barPaint = null; bgPaint = null; textPaint = null; } /** * @since 6.0.0 */ private String getConvertedScaleString(final double pMeters, final GeoConstants.UnitOfMeasure pConversion, final String pFormat) { return getScaleString( context, String.format(Locale.getDefault(), pFormat, pMeters / pConversion.getConversionFactorToMeters()), pConversion); } /** * @since 6.1.1 */ public static String getScaleString(final Context pContext, final String pValue, final GeoConstants.UnitOfMeasure pUnitOfMeasure) { return pContext.getString( R.string.format_distance_value_unit, pValue, pContext.getString(pUnitOfMeasure.getStringResId())); } /** * @since 6.1.0 */ private int getMapWidth() { return mMapView != null ? mMapView.getWidth() : mMapWidth; } /** * @since 6.1.0 */ private int getMapHeight() { return mMapView != null ? mMapView.getHeight() : mMapHeight; } }
osmdroid/osmdroid
osmdroid-android/src/main/java/org/osmdroid/views/overlay/ScaleBarOverlay.java
7,659
// get distance in meters between points
line_comment
nl
package org.osmdroid.views.overlay; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Path; import android.graphics.Rect; import android.util.DisplayMetrics; import android.view.WindowManager; import org.osmdroid.api.IGeoPoint; import org.osmdroid.library.R; import org.osmdroid.util.GeoPoint; import org.osmdroid.util.constants.GeoConstants; import org.osmdroid.views.MapView; import org.osmdroid.views.Projection; import java.lang.reflect.Field; import java.util.Locale; /** * ScaleBarOverlay.java * <p> * Puts a scale bar in the top-left corner of the screen, offset by a configurable * number of pixels. The bar is scaled to 1-inch length by querying for the physical * DPI of the screen. The size of the bar is printed between the tick marks. A * vertical (longitude) scale can be enabled. Scale is printed in metric (kilometers, * meters), imperial (miles, feet) and nautical (nautical miles, feet). * <p> * Author: Erik Burrows, Griffin Systems LLC * [email protected] * <p> * Change Log: * 2010-10-08: Inclusion to osmdroid trunk * 2015-12-17: Allow for top, bottom, left or right placement by W. Strickling * <p> * Usage: * <code> * MapView map = new MapView(...); * ScaleBarOverlay scaleBar = new ScaleBarOverlay(map); // Thiw is an important change of calling! * <p> * map.getOverlays().add(scaleBar); * </code> * <p> * To Do List: * 1. Allow for top, bottom, left or right placement. // done in this changement * 2. Scale bar to precise displayed scale text after rounding. */ public class ScaleBarOverlay extends Overlay implements GeoConstants { // =========================================================== // Fields // =========================================================== private static final Rect sTextBoundsRect = new Rect(); public enum UnitsOfMeasure { metric, imperial, nautical } // Defaults int xOffset = 10; int yOffset = 10; double minZoom = 0; UnitsOfMeasure unitsOfMeasure = UnitsOfMeasure.metric; boolean latitudeBar = true; boolean longitudeBar = false; protected boolean alignBottom = false; protected boolean alignRight = false; // Internal private Context context; private MapView mMapView; protected final Path barPath = new Path(); protected final Rect latitudeBarRect = new Rect(); protected final Rect longitudeBarRect = new Rect(); private double lastZoomLevel = -1; private double lastLatitude = 0.0; public float xdpi; public float ydpi; public int screenWidth; public int screenHeight; private Paint barPaint; private Paint bgPaint; private Paint textPaint; private boolean centred = false; private boolean adjustLength = false; private float maxLength; /** * @since 6.1.0 */ private int mMapWidth; /** * @since 6.1.0 */ private int mMapHeight; // =========================================================== // Constructors // =========================================================== public ScaleBarOverlay(final MapView mapView) { this(mapView, mapView.getContext(), 0, 0); } /** * @since 6.1.0 */ public ScaleBarOverlay(final Context pContext, final int pMapWidth, final int pMapHeight) { this(null, pContext, pMapWidth, pMapHeight); } /** * @since 6.1.0 */ private ScaleBarOverlay(final MapView pMapView, final Context pContext, final int pMapWidth, final int pMapHeight) { super(); mMapView = pMapView; context = pContext; mMapWidth = pMapWidth; mMapHeight = pMapHeight; final DisplayMetrics dm = context.getResources().getDisplayMetrics(); this.barPaint = new Paint(); this.barPaint.setColor(Color.BLACK); this.barPaint.setAntiAlias(true); this.barPaint.setStyle(Style.STROKE); this.barPaint.setAlpha(255); this.barPaint.setStrokeWidth(2 * dm.density); this.bgPaint = null; this.textPaint = new Paint(); this.textPaint.setColor(Color.BLACK); this.textPaint.setAntiAlias(true); this.textPaint.setStyle(Style.FILL); this.textPaint.setAlpha(255); this.textPaint.setTextSize(10 * dm.density); this.xdpi = dm.xdpi; this.ydpi = dm.ydpi; this.screenWidth = dm.widthPixels; this.screenHeight = dm.heightPixels; // DPI corrections for specific models String manufacturer = null; try { final Field field = android.os.Build.class.getField("MANUFACTURER"); manufacturer = (String) field.get(null); } catch (final Exception ignore) { } if ("motorola".equals(manufacturer) && "DROIDX".equals(android.os.Build.MODEL)) { // If the screen is rotated, flip the x and y dpi values WindowManager windowManager = (WindowManager) this.context .getSystemService(Context.WINDOW_SERVICE); if (windowManager != null && windowManager.getDefaultDisplay().getOrientation() > 0) { this.xdpi = (float) (this.screenWidth / 3.75); this.ydpi = (float) (this.screenHeight / 2.1); } else { this.xdpi = (float) (this.screenWidth / 2.1); this.ydpi = (float) (this.screenHeight / 3.75); } } else if ("motorola".equals(manufacturer) && "Droid".equals(android.os.Build.MODEL)) { // http://www.mail-archive.com/[email protected]/msg109497.html this.xdpi = 264; this.ydpi = 264; } // set default max length to 1 inch maxLength = 2.54f; } // =========================================================== // Getter & Setter // =========================================================== /** * Sets the minimum zoom level for the scale bar to be drawn. * * @param zoom minimum zoom level */ public void setMinZoom(final double zoom) { this.minZoom = zoom; } /** * Sets the scale bar screen offset for the bar. Note: if the bar is set to be drawn centered, * this will be the middle of the bar, otherwise the top left corner. * * @param x x screen offset * @param y z screen offset */ public void setScaleBarOffset(final int x, final int y) { xOffset = x; yOffset = y; } /** * Sets the bar's line width. (the default is 2) * * @param width the new line width */ public void setLineWidth(final float width) { this.barPaint.setStrokeWidth(width); } /** * Sets the text size. (the default is 12) * * @param size the new text size */ public void setTextSize(final float size) { this.textPaint.setTextSize(size); } /** * Sets the units of measure to be shown in the scale bar */ public void setUnitsOfMeasure(UnitsOfMeasure unitsOfMeasure) { this.unitsOfMeasure = unitsOfMeasure; lastZoomLevel = -1; // Force redraw of scalebar } /** * Gets the units of measure to be shown in the scale bar */ public UnitsOfMeasure getUnitsOfMeasure() { return unitsOfMeasure; } /** * Latitudinal / horizontal scale bar flag * * @param latitude */ public void drawLatitudeScale(final boolean latitude) { this.latitudeBar = latitude; lastZoomLevel = -1; // Force redraw of scalebar } /** * Longitudinal / vertical scale bar flag * * @param longitude */ public void drawLongitudeScale(final boolean longitude) { this.longitudeBar = longitude; lastZoomLevel = -1; // Force redraw of scalebar } /** * Flag to draw the bar centered around the set offset coordinates or to the right/bottom of the * coordinates (default) * * @param centred set true to centre the bar around the given screen coordinates */ public void setCentred(final boolean centred) { this.centred = centred; alignBottom = !centred; alignRight = !centred; lastZoomLevel = -1; // Force redraw of scalebar } public void setAlignBottom(final boolean alignBottom) { this.centred = false; this.alignBottom = alignBottom; lastZoomLevel = -1; // Force redraw of scalebar } public void setAlignRight(final boolean alignRight) { this.centred = false; this.alignRight = alignRight; lastZoomLevel = -1; // Force redraw of scalebar } /** * Return's the paint used to draw the bar * * @return the paint used to draw the bar */ public Paint getBarPaint() { return barPaint; } /** * Sets the paint for drawing the bar * * @param pBarPaint bar drawing paint */ public void setBarPaint(final Paint pBarPaint) { if (pBarPaint == null) { throw new IllegalArgumentException("pBarPaint argument cannot be null"); } barPaint = pBarPaint; lastZoomLevel = -1; // Force redraw of scalebar } /** * Returns the paint used to draw the text * * @return the paint used to draw the text */ public Paint getTextPaint() { return textPaint; } /** * Sets the paint for drawing the text * * @param pTextPaint text drawing paint */ public void setTextPaint(final Paint pTextPaint) { if (pTextPaint == null) { throw new IllegalArgumentException("pTextPaint argument cannot be null"); } textPaint = pTextPaint; lastZoomLevel = -1; // Force redraw of scalebar } /** * Sets the background paint. Set to null to disable drawing of background (default) * * @param pBgPaint the paint for colouring the bar background */ public void setBackgroundPaint(final Paint pBgPaint) { bgPaint = pBgPaint; lastZoomLevel = -1; // Force redraw of scalebar } /** * If enabled, the bar will automatically adjust the length to reflect a round number (starting * with 1, 2 or 5). If disabled, the bar will always be drawn in full length representing a * fractional distance. */ public void setEnableAdjustLength(boolean adjustLength) { this.adjustLength = adjustLength; lastZoomLevel = -1; // Force redraw of scalebar } /** * Sets the maximum bar length. If adjustLength is disabled this will match exactly the length * of the bar. If adjustLength is enabled, the bar will be shortened to reflect a round number * in length. * * @param pMaxLengthInCm maximum length of the bar in the screen in cm. Default is 2.54 (=1 inch) */ public void setMaxLength(final float pMaxLengthInCm) { this.maxLength = pMaxLengthInCm; lastZoomLevel = -1; // Force redraw of scalebar } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== @Override public void draw(Canvas c, Projection projection) { final double zoomLevel = projection.getZoomLevel(); if (zoomLevel < minZoom) { return; } final Rect rect = projection.getIntrinsicScreenRect(); int _screenWidth = rect.width(); int _screenHeight = rect.height(); boolean screenSizeChanged = _screenHeight != screenHeight || _screenWidth != screenWidth; screenHeight = _screenHeight; screenWidth = _screenWidth; final IGeoPoint center = projection.fromPixels(screenWidth / 2, screenHeight / 2, null); if (zoomLevel != lastZoomLevel || center.getLatitude() != lastLatitude || screenSizeChanged) { lastZoomLevel = zoomLevel; lastLatitude = center.getLatitude(); rebuildBarPath(projection); } int offsetX = xOffset; int offsetY = yOffset; if (alignBottom) offsetY *= -1; if (alignRight) offsetX *= -1; if (centred && latitudeBar) offsetX += -latitudeBarRect.width() / 2; if (centred && longitudeBar) offsetY += -longitudeBarRect.height() / 2; projection.save(c, false, true); c.translate(offsetX, offsetY); if (latitudeBar && bgPaint != null) c.drawRect(latitudeBarRect, bgPaint); if (longitudeBar && bgPaint != null) { // Don't draw on top of latitude background... int offsetTop = latitudeBar ? latitudeBarRect.height() : 0; c.drawRect(longitudeBarRect.left, longitudeBarRect.top + offsetTop, longitudeBarRect.right, longitudeBarRect.bottom, bgPaint); } c.drawPath(barPath, barPaint); if (latitudeBar) { drawLatitudeText(c, projection); } if (longitudeBar) { drawLongitudeText(c, projection); } projection.restore(c, true); } // =========================================================== // Methods // =========================================================== public void disableScaleBar() { setEnabled(false); } public void enableScaleBar() { setEnabled(true); } private void drawLatitudeText(final Canvas canvas, final Projection projection) { // calculate dots per centimeter int xdpcm = (int) ((float) xdpi / 2.54); // get length in pixel int xLen = (int) (maxLength * xdpcm); // Two points, xLen apart, at scale bar screen location IGeoPoint p1 = projection.fromPixels((screenWidth / 2) - (xLen / 2), yOffset, null); IGeoPoint p2 = projection.fromPixels((screenWidth / 2) + (xLen / 2), yOffset, null); // get distance in meters between points final double xMeters = ((GeoPoint) p1).distanceToAsDouble(p2); // get adjusted distance, shortened to the next lower number starting with 1, 2 or 5 final double xMetersAdjusted = this.adjustLength ? adjustScaleBarLength(xMeters) : xMeters; // get adjusted length in pixels final int xBarLengthPixels = (int) (xLen * xMetersAdjusted / xMeters); // create text final String xMsg = scaleBarLengthText(xMetersAdjusted); textPaint.getTextBounds(xMsg, 0, xMsg.length(), sTextBoundsRect); final int xTextSpacing = (int) (sTextBoundsRect.height() / 5.0); float x = xBarLengthPixels / 2 - sTextBoundsRect.width() / 2; if (alignRight) x += screenWidth - xBarLengthPixels; float y; if (alignBottom) { y = screenHeight - xTextSpacing * 2; } else y = sTextBoundsRect.height() + xTextSpacing; canvas.drawText(xMsg, x, y, textPaint); } private void drawLongitudeText(final Canvas canvas, final Projection projection) { // calculate dots per centimeter int ydpcm = (int) ((float) ydpi / 2.54); // get length in pixel int yLen = (int) (maxLength * ydpcm); // Two points, yLen apart, at scale bar screen location IGeoPoint p1 = projection .fromPixels(screenWidth / 2, (screenHeight / 2) - (yLen / 2), null); IGeoPoint p2 = projection .fromPixels(screenWidth / 2, (screenHeight / 2) + (yLen / 2), null); // get distance in meters between points final double yMeters = ((GeoPoint) p1).distanceToAsDouble(p2); // get adjusted distance, shortened to the next lower number starting with 1, 2 or 5 final double yMetersAdjusted = this.adjustLength ? adjustScaleBarLength(yMeters) : yMeters; // get adjusted length in pixels final int yBarLengthPixels = (int) (yLen * yMetersAdjusted / yMeters); // create text final String yMsg = scaleBarLengthText(yMetersAdjusted); textPaint.getTextBounds(yMsg, 0, yMsg.length(), sTextBoundsRect); final int yTextSpacing = (int) (sTextBoundsRect.height() / 5.0); float x; if (alignRight) { x = screenWidth - yTextSpacing * 2; } else x = sTextBoundsRect.height() + yTextSpacing; float y = yBarLengthPixels / 2 + sTextBoundsRect.width() / 2; if (alignBottom) y += screenHeight - yBarLengthPixels; canvas.save(); canvas.rotate(-90, x, y); canvas.drawText(yMsg, x, y, textPaint); canvas.restore(); } protected void rebuildBarPath(final Projection projection) { //** modified to protected // We want the scale bar to be as long as the closest round-number miles/kilometers // to 1-inch at the latitude at the current center of the screen. // calculate dots per centimeter int xdpcm = (int) ((float) xdpi / 2.54); int ydpcm = (int) ((float) ydpi / 2.54); // get length in pixel int xLen = (int) (maxLength * xdpcm); int yLen = (int) (maxLength * ydpcm); // Two points, xLen apart, at scale bar screen location IGeoPoint p1 = projection.fromPixels((screenWidth / 2) - (xLen / 2), yOffset, null); IGeoPoint p2 = projection.fromPixels((screenWidth / 2) + (xLen / 2), yOffset, null); // get distance in meters between points final double xMeters = ((GeoPoint) p1).distanceToAsDouble(p2); // get adjusted distance, shortened to the next lower number starting with 1, 2 or 5 final double xMetersAdjusted = this.adjustLength ? adjustScaleBarLength(xMeters) : xMeters; // get adjusted length in pixels final int xBarLengthPixels = (int) (xLen * xMetersAdjusted / xMeters); // Two points, yLen apart, at scale bar screen location p1 = projection.fromPixels(screenWidth / 2, (screenHeight / 2) - (yLen / 2), null); p2 = projection.fromPixels(screenWidth / 2, (screenHeight / 2) + (yLen / 2), null); // get distance<SUF> final double yMeters = ((GeoPoint) p1).distanceToAsDouble(p2); // get adjusted distance, shortened to the next lower number starting with 1, 2 or 5 final double yMetersAdjusted = this.adjustLength ? adjustScaleBarLength(yMeters) : yMeters; // get adjusted length in pixels final int yBarLengthPixels = (int) (yLen * yMetersAdjusted / yMeters); // create text final String xMsg = scaleBarLengthText(xMetersAdjusted); final Rect xTextRect = new Rect(); textPaint.getTextBounds(xMsg, 0, xMsg.length(), xTextRect); int xTextSpacing = (int) (xTextRect.height() / 5.0); // create text final String yMsg = scaleBarLengthText(yMetersAdjusted); final Rect yTextRect = new Rect(); textPaint.getTextBounds(yMsg, 0, yMsg.length(), yTextRect); int yTextSpacing = (int) (yTextRect.height() / 5.0); int xTextHeight = xTextRect.height(); int yTextHeight = yTextRect.height(); barPath.rewind(); //** alignBottom ad-ons int barOriginX = 0; int barOriginY = 0; int barToX = xBarLengthPixels; int barToY = yBarLengthPixels; if (alignBottom) { xTextSpacing *= -1; xTextHeight *= -1; barOriginY = getMapHeight(); barToY = barOriginY - yBarLengthPixels; } if (alignRight) { yTextSpacing *= -1; yTextHeight *= -1; barOriginX = getMapWidth(); barToX = barOriginX - xBarLengthPixels; } if (latitudeBar) { // draw latitude bar barPath.moveTo(barToX, barOriginY + xTextHeight + xTextSpacing * 2); barPath.lineTo(barToX, barOriginY); barPath.lineTo(barOriginX, barOriginY); if (!longitudeBar) { barPath.lineTo(barOriginX, barOriginY + xTextHeight + xTextSpacing * 2); } latitudeBarRect.set(barOriginX, barOriginY, barToX, barOriginY + xTextHeight + xTextSpacing * 2); } if (longitudeBar) { // draw longitude bar if (!latitudeBar) { barPath.moveTo(barOriginX + yTextHeight + yTextSpacing * 2, barOriginY); barPath.lineTo(barOriginX, barOriginY); } barPath.lineTo(barOriginX, barToY); barPath.lineTo(barOriginX + yTextHeight + yTextSpacing * 2, barToY); longitudeBarRect.set(barOriginX, barOriginY, barOriginX + yTextHeight + yTextSpacing * 2, barToY); } } /** * Returns a reduced length that starts with 1, 2 or 5 and trailing zeros. If set to nautical or * imperial the input will be transformed before and after the reduction so that the result * holds in that respective unit. * * @param length length to round * @return reduced, rounded (in m, nm or mi depending on setting) result */ private double adjustScaleBarLength(double length) { long pow = 0; boolean feet = false; if (unitsOfMeasure == UnitsOfMeasure.imperial) { if (length >= GeoConstants.METERS_PER_STATUTE_MILE / 5) length = length / GeoConstants.METERS_PER_STATUTE_MILE; else { length = length * GeoConstants.FEET_PER_METER; feet = true; } } else if (unitsOfMeasure == UnitsOfMeasure.nautical) { if (length >= GeoConstants.METERS_PER_NAUTICAL_MILE / 5) length = length / GeoConstants.METERS_PER_NAUTICAL_MILE; else { length = length * GeoConstants.FEET_PER_METER; feet = true; } } while (length >= 10) { pow++; length /= 10; } while (length < 1 && length > 0) { pow--; length *= 10; } if (length < 2) { length = 1; } else if (length < 5) { length = 2; } else { length = 5; } if (feet) length = length / GeoConstants.FEET_PER_METER; else if (unitsOfMeasure == UnitsOfMeasure.imperial) length = length * GeoConstants.METERS_PER_STATUTE_MILE; else if (unitsOfMeasure == UnitsOfMeasure.nautical) length = length * GeoConstants.METERS_PER_NAUTICAL_MILE; length *= Math.pow(10, pow); return length; } protected String scaleBarLengthText(final double meters) { switch (unitsOfMeasure) { default: case metric: if (meters >= 1000 * 5) { return getConvertedScaleString(meters, UnitOfMeasure.kilometer, "%.0f"); } else if (meters >= 1000 / 5) { return getConvertedScaleString(meters, UnitOfMeasure.kilometer, "%.1f"); } else if (meters >= 20) { return getConvertedScaleString(meters, UnitOfMeasure.meter, "%.0f"); } else { return getConvertedScaleString(meters, UnitOfMeasure.meter, "%.2f"); } case imperial: if (meters >= METERS_PER_STATUTE_MILE * 5) { return getConvertedScaleString(meters, UnitOfMeasure.statuteMile, "%.0f"); } else if (meters >= METERS_PER_STATUTE_MILE / 5) { return getConvertedScaleString(meters, UnitOfMeasure.statuteMile, "%.1f"); } else { return getConvertedScaleString(meters, UnitOfMeasure.foot, "%.0f"); } case nautical: if (meters >= METERS_PER_NAUTICAL_MILE * 5) { return getConvertedScaleString(meters, UnitOfMeasure.nauticalMile, "%.0f"); } else if (meters >= METERS_PER_NAUTICAL_MILE / 5) { return getConvertedScaleString(meters, UnitOfMeasure.nauticalMile, "%.1f"); } else { return getConvertedScaleString(meters, UnitOfMeasure.foot, "%.0f"); } } } @Override public void onDetach(MapView mapView) { this.context = null; this.mMapView = null; barPaint = null; bgPaint = null; textPaint = null; } /** * @since 6.0.0 */ private String getConvertedScaleString(final double pMeters, final GeoConstants.UnitOfMeasure pConversion, final String pFormat) { return getScaleString( context, String.format(Locale.getDefault(), pFormat, pMeters / pConversion.getConversionFactorToMeters()), pConversion); } /** * @since 6.1.1 */ public static String getScaleString(final Context pContext, final String pValue, final GeoConstants.UnitOfMeasure pUnitOfMeasure) { return pContext.getString( R.string.format_distance_value_unit, pValue, pContext.getString(pUnitOfMeasure.getStringResId())); } /** * @since 6.1.0 */ private int getMapWidth() { return mMapView != null ? mMapView.getWidth() : mMapWidth; } /** * @since 6.1.0 */ private int getMapHeight() { return mMapView != null ? mMapView.getHeight() : mMapHeight; } }
68724_129
/*=========================================================================== BASS_FX 2.4 - Copyright (c) 2002-2019 (: JOBnik! :) [Arthur Aminov, ISRAEL] [http://www.jobnik.org] bugs/suggestions/questions: forum : http://www.un4seen.com/forum/?board=1 http://www.jobnik.org/forums e-mail : [email protected] -------------------------------------------------- NOTE: This header will work only with BASS_FX version 2.4.12 Check www.un4seen.com or www.jobnik.org for any later versions. * Requires BASS 2.4 (available at http://www.un4seen.com) ===========================================================================*/ package com.un4seen.bass; @SuppressWarnings({"all"}) public class BASS_FX { // BASS_CHANNELINFO types public static final int BASS_CTYPE_STREAM_TEMPO = 0x1f200; public static final int BASS_CTYPE_STREAM_REVERSE = 0x1f201; // Tempo / Reverse / BPM / Beat flag public static final int BASS_FX_FREESOURCE = 0x10000; // Free the source handle as well? // BASS_FX Version public static native int BASS_FX_GetVersion(); /*=========================================================================== DSP (Digital Signal Processing) ===========================================================================*/ /* Multi-channel order of each channel is as follows: 3 channels left-front, right-front, center. 4 channels left-front, right-front, left-rear/side, right-rear/side. 5 channels left-front, right-front, center, left-rear/side, right-rear/side. 6 channels (5.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side. 8 channels (7.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side, left-rear center, right-rear center. */ // DSP channels flags public static final int BASS_BFX_CHANALL = -1; // all channels at once (as by default) public static final int BASS_BFX_CHANNONE = 0; // disable an effect for all channels public static final int BASS_BFX_CHAN1 = 1; // left-front channel public static final int BASS_BFX_CHAN2 = 2; // right-front channel public static final int BASS_BFX_CHAN3 = 4; // see above info public static final int BASS_BFX_CHAN4 = 8; // see above info public static final int BASS_BFX_CHAN5 = 16; // see above info public static final int BASS_BFX_CHAN6 = 32; // see above info public static final int BASS_BFX_CHAN7 = 64; // see above info public static final int BASS_BFX_CHAN8 = 128; // see above info // if you have more than 8 channels (7.1), use this function public static int BASS_BFX_CHANNEL_N(int n) { return (1<<((n)-1)); } // DSP effects public static final int BASS_FX_BFX_ROTATE = 0x10000; // A channels volume ping-pong / multi channel public static final int BASS_FX_BFX_ECHO = 0x10001; // Echo / 2 channels max (deprecated) public static final int BASS_FX_BFX_FLANGER = 0x10002; // Flanger / multi channel (deprecated) public static final int BASS_FX_BFX_VOLUME = 0x10003; // Volume / multi channel public static final int BASS_FX_BFX_PEAKEQ = 0x10004; // Peaking Equalizer / multi channel public static final int BASS_FX_BFX_REVERB = 0x10005; // Reverb / 2 channels max (deprecated) public static final int BASS_FX_BFX_LPF = 0x10006; // Low Pass Filter 24dB / multi channel (deprecated) public static final int BASS_FX_BFX_MIX = 0x10007; // Swap, remap and mix channels / multi channel public static final int BASS_FX_BFX_DAMP = 0x10008; // Dynamic Amplification / multi channel public static final int BASS_FX_BFX_AUTOWAH = 0x10009; // Auto Wah / multi channel public static final int BASS_FX_BFX_ECHO2 = 0x1000a; // Echo 2 / multi channel (deprecated) public static final int BASS_FX_BFX_PHASER = 0x1000b; // Phaser / multi channel public static final int BASS_FX_BFX_ECHO3 = 0x1000c; // Echo 3 / multi channel (deprecated) public static final int BASS_FX_BFX_CHORUS = 0x1000d; // Chorus/Flanger / multi channel public static final int BASS_FX_BFX_APF = 0x1000e; // All Pass Filter / multi channel (deprecated) public static final int BASS_FX_BFX_COMPRESSOR = 0x1000f; // Compressor / multi channel (deprecated) public static final int BASS_FX_BFX_DISTORTION = 0x10010; // Distortion / multi channel public static final int BASS_FX_BFX_COMPRESSOR2 = 0x10011; // Compressor 2 / multi channel public static final int BASS_FX_BFX_VOLUME_ENV = 0x10012; // Volume envelope / multi channel public static final int BASS_FX_BFX_BQF = 0x10013; // BiQuad filters / multi channel public static final int BASS_FX_BFX_ECHO4 = 0x10014; // Echo 4 / multi channel public static final int BASS_FX_BFX_PITCHSHIFT = 0x10015; // Pitch shift using FFT / multi channel (not available on mobile) public static final int BASS_FX_BFX_FREEVERB = 0x10016; // Reverb using "Freeverb" algo / multi channel /* Deprecated effects in 2.4.10 version: ------------------------------------ BASS_FX_BFX_ECHO -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_ECHO2 -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_ECHO3 -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_REVERB -> use BASS_FX_BFX_FREEVERB BASS_FX_BFX_FLANGER -> use BASS_FX_BFX_CHORUS BASS_FX_BFX_COMPRESSOR -> use BASS_FX_BFX_COMPRESSOR2 BASS_FX_BFX_APF -> use BASS_FX_BFX_BQF with BASS_BFX_BQF_ALLPASS filter BASS_FX_BFX_LPF -> use 2x BASS_FX_BFX_BQF with BASS_BFX_BQF_LOWPASS filter and appropriate fQ values */ // Rotate public static class BASS_BFX_ROTATE { public float fRate; // rotation rate/speed in Hz (A negative rate can be used for reverse direction) public int lChannel; // BASS_BFX_CHANxxx flag/s (supported only even number of channels) } // Echo (deprecated) public static class BASS_BFX_ECHO { public float fLevel; // [0....1....n] linear public int lDelay; // [1200..30000] } // Flanger (deprecated) public static class BASS_BFX_FLANGER { public float fWetDry; // [0....1....n] linear public float fSpeed; // [0......0.09] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Volume public static class BASS_BFX_VOLUME { public int lChannel; // BASS_BFX_CHANxxx flag/s or 0 for global volume control public float fVolume; // [0....1....n] linear } // Peaking Equalizer public static class BASS_BFX_PEAKEQ { public int lBand; // [0...............n] more bands means more memory & cpu usage public float fBandwidth; // [0.1...........<10] in octaves - fQ is not in use (Bandwidth has a priority over fQ) public float fQ; // [0...............1] the EE kinda definition (linear) (if Bandwidth is not in use) public float fCenter; // [1Hz..<info.freq/2] in Hz public float fGain; // [-15dB...0...+15dB] in dB (can be above/below these limits) public int lChannel; // BASS_BFX_CHANxxx flag/s } // Reverb (deprecated) public static class BASS_BFX_REVERB { public float fLevel; // [0....1....n] linear public int lDelay; // [1200..10000] } // Low Pass Filter (deprecated) public static class BASS_BFX_LPF { public float fResonance; // [0.01...........10] public float fCutOffFreq; // [1Hz...info.freq/2] cutoff frequency public int lChannel; // BASS_BFX_CHANxxx flag/s } // Swap, remap and mix public static class BASS_BFX_MIX { public int[] lChannel; // an array of channels to mix using BASS_BFX_CHANxxx flag/s (lChannel[0] is left channel...) } // Dynamic Amplification public static class BASS_BFX_DAMP { public float fTarget; // target volume level [0<......1] linear public float fQuiet; // quiet volume level [0.......1] linear public float fRate; // amp adjustment rate [0.......1] linear public float fGain; // amplification level [0...1...n] linear public float fDelay; // delay in seconds before increasing level [0.......n] linear public int lChannel; // BASS_BFX_CHANxxx flag/s } // Auto Wah public static class BASS_BFX_AUTOWAH { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fRate; // rate of sweep in cycles per second [0<....<10] public float fRange; // sweep range in octaves [0<....<10] public float fFreq; // base frequency of sweep Hz [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 2 (deprecated) public static class BASS_BFX_ECHO2 { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fDelay; // delay sec [0<......n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Phaser public static class BASS_BFX_PHASER { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fRate; // rate of sweep in cycles per second [0<....<10] public float fRange; // sweep range in octaves [0<....<10] public float fFreq; // base frequency of sweep [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 3 (deprecated) public static class BASS_BFX_ECHO3 { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fDelay; // delay sec [0<......n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Chorus/Flanger public static class BASS_BFX_CHORUS { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fMinSweep; // minimal delay ms [0<...6000] public float fMaxSweep; // maximum delay ms [0<...6000] public float fRate; // rate ms/s [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // All Pass Filter (deprecated) public static class BASS_BFX_APF { public float fGain; // reverberation time [-1=<..<=1] public float fDelay; // delay sec [0<....<=n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Compressor (deprecated) public static class BASS_BFX_COMPRESSOR { public float fThreshold; // compressor threshold [0<=...<=1] public float fAttacktime; // attack time ms [0<.<=1000] public float fReleasetime; // release time ms [0<.<=5000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Distortion public static class BASS_BFX_DISTORTION { public float fDrive; // distortion drive [0<=...<=5] public float fDryMix; // dry (unaffected) signal mix [-5<=..<=5] public float fWetMix; // wet (affected) signal mix [-5<=..<=5] public float fFeedback; // output signal to feed back into input [-1<=..<=1] public float fVolume; // distortion volume [0=<...<=2] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Compressor 2 public static class BASS_BFX_COMPRESSOR2 { public float fGain; // output gain of signal after compression [-60....60] in dB public float fThreshold; // point at which compression begins [-60.....0] in dB public float fRatio; // compression ratio [1.......n] public float fAttack; // attack time in ms [0.01.1000] public float fRelease; // release time in ms [0.01.5000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Volume envelope public static class BASS_BFX_VOLUME_ENV { public int lChannel; // BASS_BFX_CHANxxx flag/s public int lNodeCount; // number of nodes public BASS_BFX_ENV_NODE[] pNodes; // the nodes public boolean bFollow; // follow source position } public static class BASS_BFX_ENV_NODE { public double pos; // node position in seconds (1st envelope node must be at position 0) public float val; // node value } // BiQuad Filters public static final int BASS_BFX_BQF_LOWPASS = 0; public static final int BASS_BFX_BQF_HIGHPASS = 1; public static final int BASS_BFX_BQF_BANDPASS = 2; // constant 0 dB peak gain public static final int BASS_BFX_BQF_BANDPASS_Q = 3; // constant skirt gain, peak gain = Q public static final int BASS_BFX_BQF_NOTCH = 4; public static final int BASS_BFX_BQF_ALLPASS = 5; public static final int BASS_BFX_BQF_PEAKINGEQ = 6; public static final int BASS_BFX_BQF_LOWSHELF = 7; public static final int BASS_BFX_BQF_HIGHSHELF = 8; public static class BASS_BFX_BQF { public int lFilter; // BASS_BFX_BQF_xxx filter types public float fCenter; // [1Hz..<info.freq/2] Cutoff (central) frequency in Hz public float fGain; // [-15dB...0...+15dB] Used only for PEAKINGEQ and Shelving filters in dB (can be above/below these limits) public float fBandwidth; // [0.1...........<10] Bandwidth in octaves (fQ is not in use (fBandwidth has a priority over fQ)) // (between -3 dB frequencies for BANDPASS and NOTCH or between midpoint // (fGgain/2) gain frequencies for PEAKINGEQ) public float fQ; // [0.1.....1.......n] The EE kinda definition (linear) (if fBandwidth is not in use) public float fS; // [0.1.....1.......n] A "shelf slope" parameter (linear) (used only with Shelving filters) // when fS = 1, the shelf slope is as steep as you can get it and remain monotonically // increasing or decreasing gain with frequency. public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 4 public static class BASS_BFX_ECHO4 { public float fDryMix; // dry (unaffected) signal mix [-2.......2] public float fWetMix; // wet (affected) signal mix [-2.......2] public float fFeedback; // output signal to feed back into input [-1.......1] public float fDelay; // delay sec [0<.......n] public boolean bStereo; // echo adjoining channels to each other [TRUE/FALSE] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Pitch shift (not available on mobile) public static class BASS_BFX_PITCHSHIFT { public float fPitchShift; // A factor value which is between 0.5 (one octave down) and 2 (one octave up) (1 won't change the pitch) [1 default] // (fSemitones is not in use, fPitchShift has a priority over fSemitones) public float fSemitones; // Semitones (0 won't change the pitch) [0 default] public int lFFTsize; // Defines the FFT frame size used for the processing. Typical values are 1024, 2048 and 4096 [2048 default] // It may be any value <= 8192 but it MUST be a power of 2 public int lOsamp; // Is the STFT oversampling factor which also determines the overlap between adjacent STFT frames [8 default] // It should at least be 4 for moderate scaling ratios. A value of 32 is recommended for best quality (better quality = higher CPU usage) public int lChannel; // BASS_BFX_CHANxxx flag/s } // Freeverb public static final int BASS_BFX_FREEVERB_MODE_FREEZE = 1; public static class BASS_BFX_FREEVERB { public float fDryMix; // dry (unaffected) signal mix [0........1], def. 0 public float fWetMix; // wet (affected) signal mix [0........3], def. 1.0f public float fRoomSize; // room size [0........1], def. 0.5f public float fDamp; // damping [0........1], def. 0.5f public float fWidth; // stereo width [0........1], def. 1 public int lMode; // 0 or BASS_BFX_FREEVERB_MODE_FREEZE, def. 0 (no freeze) public int lChannel; // BASS_BFX_CHANxxx flag/s } /*=========================================================================== set dsp fx - BASS_ChannelSetFX remove dsp fx - BASS_ChannelRemoveFX set parameters - BASS_FXSetParameters retrieve parameters - BASS_FXGetParameters reset the state - BASS_FXReset ===========================================================================*/ /*=========================================================================== Tempo, Pitch scaling and Sample rate changers ===========================================================================*/ // NOTE: Enable Tempo supported flags in BASS_FX_TempoCreate and the others to source handle. // tempo attributes (BASS_ChannelSet/GetAttribute) public static final int BASS_ATTRIB_TEMPO = 0x10000; public static final int BASS_ATTRIB_TEMPO_PITCH = 0x10001; public static final int BASS_ATTRIB_TEMPO_FREQ = 0x10002; // tempo attributes options public static final int BASS_ATTRIB_TEMPO_OPTION_USE_AA_FILTER = 0x10010; // TRUE (default) / FALSE (default for multi-channel on mobile devices for lower CPU usage) public static final int BASS_ATTRIB_TEMPO_OPTION_AA_FILTER_LENGTH = 0x10011; // 32 default (8 .. 128 taps) public static final int BASS_ATTRIB_TEMPO_OPTION_USE_QUICKALGO = 0x10012; // TRUE (default on mobile devices for lower CPU usage) / FALSE (default) public static final int BASS_ATTRIB_TEMPO_OPTION_SEQUENCE_MS = 0x10013; // 82 default, 0 = automatic public static final int BASS_ATTRIB_TEMPO_OPTION_SEEKWINDOW_MS = 0x10014; // 28 default, 0 = automatic public static final int BASS_ATTRIB_TEMPO_OPTION_OVERLAP_MS = 0x10015; // 8 default public static final int BASS_ATTRIB_TEMPO_OPTION_PREVENT_CLICK = 0x10016; // TRUE / FALSE (default) // tempo algorithm flags public static final int BASS_FX_TEMPO_ALGO_LINEAR = 0x200; public static final int BASS_FX_TEMPO_ALGO_CUBIC = 0x400; // default public static final int BASS_FX_TEMPO_ALGO_SHANNON = 0x800; public static native int BASS_FX_TempoCreate(int chan, int flags); public static native int BASS_FX_TempoGetSource(int chan); public static native float BASS_FX_TempoGetRateRatio(int chan); /*=========================================================================== Reverse playback ===========================================================================*/ // NOTES: 1. MODs won't load without BASS_MUSIC_PRESCAN flag. // 2. Enable Reverse supported flags in BASS_FX_ReverseCreate and the others to source handle. // reverse attribute (BASS_ChannelSet/GetAttribute) public static final int BASS_ATTRIB_REVERSE_DIR = 0x11000; // playback directions public static final int BASS_FX_RVS_REVERSE = -1; public static final int BASS_FX_RVS_FORWARD = 1; public static native int BASS_FX_ReverseCreate(int chan, float dec_block, int flags); public static native int BASS_FX_ReverseGetSource(int chan); /*=========================================================================== BPM (Beats Per Minute) ===========================================================================*/ // bpm flags public static final int BASS_FX_BPM_BKGRND = 1; // if in use, then you can do other processing while detection's in progress. Available only in Windows platforms (BPM/Beat) public static final int BASS_FX_BPM_MULT2 = 2; // if in use, then will auto multiply bpm by 2 (if BPM < minBPM*2) // translation options (deprecated) public static final int BASS_FX_BPM_TRAN_X2 = 0; // multiply the original BPM value by 2 (may be called only once & will change the original BPM as well!) public static final int BASS_FX_BPM_TRAN_2FREQ = 1; // BPM value to Frequency public static final int BASS_FX_BPM_TRAN_FREQ2 = 2; // Frequency to BPM value public static final int BASS_FX_BPM_TRAN_2PERCENT = 3; // BPM value to Percents public static final int BASS_FX_BPM_TRAN_PERCENT2 = 4; // Percents to BPM value public interface BPMPROC { void BPMPROC(int chan, float bpm, Object user); } public interface BPMPROGRESSPROC { void BPMPROGRESSPROC(int chan, float percent, Object user); } // back-compatibility public interface BPMPROCESSPROC { void BPMPROCESSPROC(int chan, float percent, Object user); } public static native float BASS_FX_BPM_DecodeGet(int chan, double startSec, double endSec, int minMaxBPM, int flags, Object proc, Object user); public static native boolean BASS_FX_BPM_CallbackSet(int handle, BPMPROC proc, double period, int minMaxBPM, int flags, Object user); public static native boolean BASS_FX_BPM_CallbackReset(int handle); public static native float BASS_FX_BPM_Translate(int handle, float val2tran, int trans); // deprecated public static native boolean BASS_FX_BPM_Free(int handle); /*=========================================================================== Beat position trigger ===========================================================================*/ public interface BPMBEATPROC { void BPMBEATPROC(int chan, double beatpos, Object user); } public static native boolean BASS_FX_BPM_BeatCallbackSet(int handle, BPMBEATPROC proc, Object user); public static native boolean BASS_FX_BPM_BeatCallbackReset(int handle); public static native boolean BASS_FX_BPM_BeatDecodeGet(int chan, double startSec, double endSec, int flags, BPMBEATPROC proc, Object user); public static native boolean BASS_FX_BPM_BeatSetParameters(int handle, float bandwidth, float centerfreq, float beat_rtime); public static native boolean BASS_FX_BPM_BeatGetParameters(int handle, Float bandwidth, Float centerfreq, Float beat_rtime); public static native boolean BASS_FX_BPM_BeatFree(int handle); /*=========================================================================== Macros ===========================================================================*/ // translate linear level to logarithmic dB public static double BASS_BFX_Linear2dB(double level) { return (20*Math.log10(level)); } // translate logarithmic dB level to linear public static double BASS_BFX_dB2Linear(double dB) { return (Math.pow(10,(dB)/20)); } static { System.loadLibrary("bass_fx"); } }
osudroid/osu-droid
LibBASS/src/main/java/com/un4seen/bass/BASS_FX.java
7,873
// room size [0........1], def. 0.5f
line_comment
nl
/*=========================================================================== BASS_FX 2.4 - Copyright (c) 2002-2019 (: JOBnik! :) [Arthur Aminov, ISRAEL] [http://www.jobnik.org] bugs/suggestions/questions: forum : http://www.un4seen.com/forum/?board=1 http://www.jobnik.org/forums e-mail : [email protected] -------------------------------------------------- NOTE: This header will work only with BASS_FX version 2.4.12 Check www.un4seen.com or www.jobnik.org for any later versions. * Requires BASS 2.4 (available at http://www.un4seen.com) ===========================================================================*/ package com.un4seen.bass; @SuppressWarnings({"all"}) public class BASS_FX { // BASS_CHANNELINFO types public static final int BASS_CTYPE_STREAM_TEMPO = 0x1f200; public static final int BASS_CTYPE_STREAM_REVERSE = 0x1f201; // Tempo / Reverse / BPM / Beat flag public static final int BASS_FX_FREESOURCE = 0x10000; // Free the source handle as well? // BASS_FX Version public static native int BASS_FX_GetVersion(); /*=========================================================================== DSP (Digital Signal Processing) ===========================================================================*/ /* Multi-channel order of each channel is as follows: 3 channels left-front, right-front, center. 4 channels left-front, right-front, left-rear/side, right-rear/side. 5 channels left-front, right-front, center, left-rear/side, right-rear/side. 6 channels (5.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side. 8 channels (7.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side, left-rear center, right-rear center. */ // DSP channels flags public static final int BASS_BFX_CHANALL = -1; // all channels at once (as by default) public static final int BASS_BFX_CHANNONE = 0; // disable an effect for all channels public static final int BASS_BFX_CHAN1 = 1; // left-front channel public static final int BASS_BFX_CHAN2 = 2; // right-front channel public static final int BASS_BFX_CHAN3 = 4; // see above info public static final int BASS_BFX_CHAN4 = 8; // see above info public static final int BASS_BFX_CHAN5 = 16; // see above info public static final int BASS_BFX_CHAN6 = 32; // see above info public static final int BASS_BFX_CHAN7 = 64; // see above info public static final int BASS_BFX_CHAN8 = 128; // see above info // if you have more than 8 channels (7.1), use this function public static int BASS_BFX_CHANNEL_N(int n) { return (1<<((n)-1)); } // DSP effects public static final int BASS_FX_BFX_ROTATE = 0x10000; // A channels volume ping-pong / multi channel public static final int BASS_FX_BFX_ECHO = 0x10001; // Echo / 2 channels max (deprecated) public static final int BASS_FX_BFX_FLANGER = 0x10002; // Flanger / multi channel (deprecated) public static final int BASS_FX_BFX_VOLUME = 0x10003; // Volume / multi channel public static final int BASS_FX_BFX_PEAKEQ = 0x10004; // Peaking Equalizer / multi channel public static final int BASS_FX_BFX_REVERB = 0x10005; // Reverb / 2 channels max (deprecated) public static final int BASS_FX_BFX_LPF = 0x10006; // Low Pass Filter 24dB / multi channel (deprecated) public static final int BASS_FX_BFX_MIX = 0x10007; // Swap, remap and mix channels / multi channel public static final int BASS_FX_BFX_DAMP = 0x10008; // Dynamic Amplification / multi channel public static final int BASS_FX_BFX_AUTOWAH = 0x10009; // Auto Wah / multi channel public static final int BASS_FX_BFX_ECHO2 = 0x1000a; // Echo 2 / multi channel (deprecated) public static final int BASS_FX_BFX_PHASER = 0x1000b; // Phaser / multi channel public static final int BASS_FX_BFX_ECHO3 = 0x1000c; // Echo 3 / multi channel (deprecated) public static final int BASS_FX_BFX_CHORUS = 0x1000d; // Chorus/Flanger / multi channel public static final int BASS_FX_BFX_APF = 0x1000e; // All Pass Filter / multi channel (deprecated) public static final int BASS_FX_BFX_COMPRESSOR = 0x1000f; // Compressor / multi channel (deprecated) public static final int BASS_FX_BFX_DISTORTION = 0x10010; // Distortion / multi channel public static final int BASS_FX_BFX_COMPRESSOR2 = 0x10011; // Compressor 2 / multi channel public static final int BASS_FX_BFX_VOLUME_ENV = 0x10012; // Volume envelope / multi channel public static final int BASS_FX_BFX_BQF = 0x10013; // BiQuad filters / multi channel public static final int BASS_FX_BFX_ECHO4 = 0x10014; // Echo 4 / multi channel public static final int BASS_FX_BFX_PITCHSHIFT = 0x10015; // Pitch shift using FFT / multi channel (not available on mobile) public static final int BASS_FX_BFX_FREEVERB = 0x10016; // Reverb using "Freeverb" algo / multi channel /* Deprecated effects in 2.4.10 version: ------------------------------------ BASS_FX_BFX_ECHO -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_ECHO2 -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_ECHO3 -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_REVERB -> use BASS_FX_BFX_FREEVERB BASS_FX_BFX_FLANGER -> use BASS_FX_BFX_CHORUS BASS_FX_BFX_COMPRESSOR -> use BASS_FX_BFX_COMPRESSOR2 BASS_FX_BFX_APF -> use BASS_FX_BFX_BQF with BASS_BFX_BQF_ALLPASS filter BASS_FX_BFX_LPF -> use 2x BASS_FX_BFX_BQF with BASS_BFX_BQF_LOWPASS filter and appropriate fQ values */ // Rotate public static class BASS_BFX_ROTATE { public float fRate; // rotation rate/speed in Hz (A negative rate can be used for reverse direction) public int lChannel; // BASS_BFX_CHANxxx flag/s (supported only even number of channels) } // Echo (deprecated) public static class BASS_BFX_ECHO { public float fLevel; // [0....1....n] linear public int lDelay; // [1200..30000] } // Flanger (deprecated) public static class BASS_BFX_FLANGER { public float fWetDry; // [0....1....n] linear public float fSpeed; // [0......0.09] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Volume public static class BASS_BFX_VOLUME { public int lChannel; // BASS_BFX_CHANxxx flag/s or 0 for global volume control public float fVolume; // [0....1....n] linear } // Peaking Equalizer public static class BASS_BFX_PEAKEQ { public int lBand; // [0...............n] more bands means more memory & cpu usage public float fBandwidth; // [0.1...........<10] in octaves - fQ is not in use (Bandwidth has a priority over fQ) public float fQ; // [0...............1] the EE kinda definition (linear) (if Bandwidth is not in use) public float fCenter; // [1Hz..<info.freq/2] in Hz public float fGain; // [-15dB...0...+15dB] in dB (can be above/below these limits) public int lChannel; // BASS_BFX_CHANxxx flag/s } // Reverb (deprecated) public static class BASS_BFX_REVERB { public float fLevel; // [0....1....n] linear public int lDelay; // [1200..10000] } // Low Pass Filter (deprecated) public static class BASS_BFX_LPF { public float fResonance; // [0.01...........10] public float fCutOffFreq; // [1Hz...info.freq/2] cutoff frequency public int lChannel; // BASS_BFX_CHANxxx flag/s } // Swap, remap and mix public static class BASS_BFX_MIX { public int[] lChannel; // an array of channels to mix using BASS_BFX_CHANxxx flag/s (lChannel[0] is left channel...) } // Dynamic Amplification public static class BASS_BFX_DAMP { public float fTarget; // target volume level [0<......1] linear public float fQuiet; // quiet volume level [0.......1] linear public float fRate; // amp adjustment rate [0.......1] linear public float fGain; // amplification level [0...1...n] linear public float fDelay; // delay in seconds before increasing level [0.......n] linear public int lChannel; // BASS_BFX_CHANxxx flag/s } // Auto Wah public static class BASS_BFX_AUTOWAH { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fRate; // rate of sweep in cycles per second [0<....<10] public float fRange; // sweep range in octaves [0<....<10] public float fFreq; // base frequency of sweep Hz [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 2 (deprecated) public static class BASS_BFX_ECHO2 { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fDelay; // delay sec [0<......n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Phaser public static class BASS_BFX_PHASER { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fRate; // rate of sweep in cycles per second [0<....<10] public float fRange; // sweep range in octaves [0<....<10] public float fFreq; // base frequency of sweep [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 3 (deprecated) public static class BASS_BFX_ECHO3 { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fDelay; // delay sec [0<......n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Chorus/Flanger public static class BASS_BFX_CHORUS { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fMinSweep; // minimal delay ms [0<...6000] public float fMaxSweep; // maximum delay ms [0<...6000] public float fRate; // rate ms/s [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // All Pass Filter (deprecated) public static class BASS_BFX_APF { public float fGain; // reverberation time [-1=<..<=1] public float fDelay; // delay sec [0<....<=n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Compressor (deprecated) public static class BASS_BFX_COMPRESSOR { public float fThreshold; // compressor threshold [0<=...<=1] public float fAttacktime; // attack time ms [0<.<=1000] public float fReleasetime; // release time ms [0<.<=5000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Distortion public static class BASS_BFX_DISTORTION { public float fDrive; // distortion drive [0<=...<=5] public float fDryMix; // dry (unaffected) signal mix [-5<=..<=5] public float fWetMix; // wet (affected) signal mix [-5<=..<=5] public float fFeedback; // output signal to feed back into input [-1<=..<=1] public float fVolume; // distortion volume [0=<...<=2] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Compressor 2 public static class BASS_BFX_COMPRESSOR2 { public float fGain; // output gain of signal after compression [-60....60] in dB public float fThreshold; // point at which compression begins [-60.....0] in dB public float fRatio; // compression ratio [1.......n] public float fAttack; // attack time in ms [0.01.1000] public float fRelease; // release time in ms [0.01.5000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Volume envelope public static class BASS_BFX_VOLUME_ENV { public int lChannel; // BASS_BFX_CHANxxx flag/s public int lNodeCount; // number of nodes public BASS_BFX_ENV_NODE[] pNodes; // the nodes public boolean bFollow; // follow source position } public static class BASS_BFX_ENV_NODE { public double pos; // node position in seconds (1st envelope node must be at position 0) public float val; // node value } // BiQuad Filters public static final int BASS_BFX_BQF_LOWPASS = 0; public static final int BASS_BFX_BQF_HIGHPASS = 1; public static final int BASS_BFX_BQF_BANDPASS = 2; // constant 0 dB peak gain public static final int BASS_BFX_BQF_BANDPASS_Q = 3; // constant skirt gain, peak gain = Q public static final int BASS_BFX_BQF_NOTCH = 4; public static final int BASS_BFX_BQF_ALLPASS = 5; public static final int BASS_BFX_BQF_PEAKINGEQ = 6; public static final int BASS_BFX_BQF_LOWSHELF = 7; public static final int BASS_BFX_BQF_HIGHSHELF = 8; public static class BASS_BFX_BQF { public int lFilter; // BASS_BFX_BQF_xxx filter types public float fCenter; // [1Hz..<info.freq/2] Cutoff (central) frequency in Hz public float fGain; // [-15dB...0...+15dB] Used only for PEAKINGEQ and Shelving filters in dB (can be above/below these limits) public float fBandwidth; // [0.1...........<10] Bandwidth in octaves (fQ is not in use (fBandwidth has a priority over fQ)) // (between -3 dB frequencies for BANDPASS and NOTCH or between midpoint // (fGgain/2) gain frequencies for PEAKINGEQ) public float fQ; // [0.1.....1.......n] The EE kinda definition (linear) (if fBandwidth is not in use) public float fS; // [0.1.....1.......n] A "shelf slope" parameter (linear) (used only with Shelving filters) // when fS = 1, the shelf slope is as steep as you can get it and remain monotonically // increasing or decreasing gain with frequency. public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 4 public static class BASS_BFX_ECHO4 { public float fDryMix; // dry (unaffected) signal mix [-2.......2] public float fWetMix; // wet (affected) signal mix [-2.......2] public float fFeedback; // output signal to feed back into input [-1.......1] public float fDelay; // delay sec [0<.......n] public boolean bStereo; // echo adjoining channels to each other [TRUE/FALSE] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Pitch shift (not available on mobile) public static class BASS_BFX_PITCHSHIFT { public float fPitchShift; // A factor value which is between 0.5 (one octave down) and 2 (one octave up) (1 won't change the pitch) [1 default] // (fSemitones is not in use, fPitchShift has a priority over fSemitones) public float fSemitones; // Semitones (0 won't change the pitch) [0 default] public int lFFTsize; // Defines the FFT frame size used for the processing. Typical values are 1024, 2048 and 4096 [2048 default] // It may be any value <= 8192 but it MUST be a power of 2 public int lOsamp; // Is the STFT oversampling factor which also determines the overlap between adjacent STFT frames [8 default] // It should at least be 4 for moderate scaling ratios. A value of 32 is recommended for best quality (better quality = higher CPU usage) public int lChannel; // BASS_BFX_CHANxxx flag/s } // Freeverb public static final int BASS_BFX_FREEVERB_MODE_FREEZE = 1; public static class BASS_BFX_FREEVERB { public float fDryMix; // dry (unaffected) signal mix [0........1], def. 0 public float fWetMix; // wet (affected) signal mix [0........3], def. 1.0f public float fRoomSize; // room size<SUF> public float fDamp; // damping [0........1], def. 0.5f public float fWidth; // stereo width [0........1], def. 1 public int lMode; // 0 or BASS_BFX_FREEVERB_MODE_FREEZE, def. 0 (no freeze) public int lChannel; // BASS_BFX_CHANxxx flag/s } /*=========================================================================== set dsp fx - BASS_ChannelSetFX remove dsp fx - BASS_ChannelRemoveFX set parameters - BASS_FXSetParameters retrieve parameters - BASS_FXGetParameters reset the state - BASS_FXReset ===========================================================================*/ /*=========================================================================== Tempo, Pitch scaling and Sample rate changers ===========================================================================*/ // NOTE: Enable Tempo supported flags in BASS_FX_TempoCreate and the others to source handle. // tempo attributes (BASS_ChannelSet/GetAttribute) public static final int BASS_ATTRIB_TEMPO = 0x10000; public static final int BASS_ATTRIB_TEMPO_PITCH = 0x10001; public static final int BASS_ATTRIB_TEMPO_FREQ = 0x10002; // tempo attributes options public static final int BASS_ATTRIB_TEMPO_OPTION_USE_AA_FILTER = 0x10010; // TRUE (default) / FALSE (default for multi-channel on mobile devices for lower CPU usage) public static final int BASS_ATTRIB_TEMPO_OPTION_AA_FILTER_LENGTH = 0x10011; // 32 default (8 .. 128 taps) public static final int BASS_ATTRIB_TEMPO_OPTION_USE_QUICKALGO = 0x10012; // TRUE (default on mobile devices for lower CPU usage) / FALSE (default) public static final int BASS_ATTRIB_TEMPO_OPTION_SEQUENCE_MS = 0x10013; // 82 default, 0 = automatic public static final int BASS_ATTRIB_TEMPO_OPTION_SEEKWINDOW_MS = 0x10014; // 28 default, 0 = automatic public static final int BASS_ATTRIB_TEMPO_OPTION_OVERLAP_MS = 0x10015; // 8 default public static final int BASS_ATTRIB_TEMPO_OPTION_PREVENT_CLICK = 0x10016; // TRUE / FALSE (default) // tempo algorithm flags public static final int BASS_FX_TEMPO_ALGO_LINEAR = 0x200; public static final int BASS_FX_TEMPO_ALGO_CUBIC = 0x400; // default public static final int BASS_FX_TEMPO_ALGO_SHANNON = 0x800; public static native int BASS_FX_TempoCreate(int chan, int flags); public static native int BASS_FX_TempoGetSource(int chan); public static native float BASS_FX_TempoGetRateRatio(int chan); /*=========================================================================== Reverse playback ===========================================================================*/ // NOTES: 1. MODs won't load without BASS_MUSIC_PRESCAN flag. // 2. Enable Reverse supported flags in BASS_FX_ReverseCreate and the others to source handle. // reverse attribute (BASS_ChannelSet/GetAttribute) public static final int BASS_ATTRIB_REVERSE_DIR = 0x11000; // playback directions public static final int BASS_FX_RVS_REVERSE = -1; public static final int BASS_FX_RVS_FORWARD = 1; public static native int BASS_FX_ReverseCreate(int chan, float dec_block, int flags); public static native int BASS_FX_ReverseGetSource(int chan); /*=========================================================================== BPM (Beats Per Minute) ===========================================================================*/ // bpm flags public static final int BASS_FX_BPM_BKGRND = 1; // if in use, then you can do other processing while detection's in progress. Available only in Windows platforms (BPM/Beat) public static final int BASS_FX_BPM_MULT2 = 2; // if in use, then will auto multiply bpm by 2 (if BPM < minBPM*2) // translation options (deprecated) public static final int BASS_FX_BPM_TRAN_X2 = 0; // multiply the original BPM value by 2 (may be called only once & will change the original BPM as well!) public static final int BASS_FX_BPM_TRAN_2FREQ = 1; // BPM value to Frequency public static final int BASS_FX_BPM_TRAN_FREQ2 = 2; // Frequency to BPM value public static final int BASS_FX_BPM_TRAN_2PERCENT = 3; // BPM value to Percents public static final int BASS_FX_BPM_TRAN_PERCENT2 = 4; // Percents to BPM value public interface BPMPROC { void BPMPROC(int chan, float bpm, Object user); } public interface BPMPROGRESSPROC { void BPMPROGRESSPROC(int chan, float percent, Object user); } // back-compatibility public interface BPMPROCESSPROC { void BPMPROCESSPROC(int chan, float percent, Object user); } public static native float BASS_FX_BPM_DecodeGet(int chan, double startSec, double endSec, int minMaxBPM, int flags, Object proc, Object user); public static native boolean BASS_FX_BPM_CallbackSet(int handle, BPMPROC proc, double period, int minMaxBPM, int flags, Object user); public static native boolean BASS_FX_BPM_CallbackReset(int handle); public static native float BASS_FX_BPM_Translate(int handle, float val2tran, int trans); // deprecated public static native boolean BASS_FX_BPM_Free(int handle); /*=========================================================================== Beat position trigger ===========================================================================*/ public interface BPMBEATPROC { void BPMBEATPROC(int chan, double beatpos, Object user); } public static native boolean BASS_FX_BPM_BeatCallbackSet(int handle, BPMBEATPROC proc, Object user); public static native boolean BASS_FX_BPM_BeatCallbackReset(int handle); public static native boolean BASS_FX_BPM_BeatDecodeGet(int chan, double startSec, double endSec, int flags, BPMBEATPROC proc, Object user); public static native boolean BASS_FX_BPM_BeatSetParameters(int handle, float bandwidth, float centerfreq, float beat_rtime); public static native boolean BASS_FX_BPM_BeatGetParameters(int handle, Float bandwidth, Float centerfreq, Float beat_rtime); public static native boolean BASS_FX_BPM_BeatFree(int handle); /*=========================================================================== Macros ===========================================================================*/ // translate linear level to logarithmic dB public static double BASS_BFX_Linear2dB(double level) { return (20*Math.log10(level)); } // translate logarithmic dB level to linear public static double BASS_BFX_dB2Linear(double dB) { return (Math.pow(10,(dB)/20)); } static { System.loadLibrary("bass_fx"); } }
200057_13
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.de; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedToken; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.JLanguageTool; import org.languagetool.language.German; import org.languagetool.rules.Category; import org.languagetool.rules.Example; import org.languagetool.rules.RuleMatch; import org.languagetool.tagging.de.GermanTagger; import org.languagetool.tagging.de.GermanToken; import org.languagetool.tagging.de.GermanToken.POSType; import org.languagetool.tools.StringTools; import java.io.IOException; import java.util.*; /** * Check that adjectives and verbs are not written with an uppercase * first letter (except at the start of a sentence) and cases * like this: <tt>Das laufen f&auml;llt mir leicht.</tt> (<tt>laufen</tt> needs * to be uppercased). * * @author Daniel Naber */ public class CaseRule extends GermanRule { private final GermanTagger tagger; // wenn hinter diesen Wörtern ein Verb steht, ist es wohl ein substantiviertes Verb, // muss also groß geschrieben werden: private static final Set<String> nounIndicators = new HashSet<>(); static { nounIndicators.add("das"); nounIndicators.add("sein"); //indicator.add("seines"); // TODO: ? //nounIndicators.add("ihr"); // would cause false alarm e.g. "Auf ihr stehen die Ruinen..." nounIndicators.add("mein"); nounIndicators.add("dein"); nounIndicators.add("euer"); //indicator.add("ihres"); //indicator.add("ihren"); } private static final Set<String> sentenceStartExceptions = new HashSet<>(); static { sentenceStartExceptions.add("("); sentenceStartExceptions.add(":"); sentenceStartExceptions.add("\""); sentenceStartExceptions.add("'"); sentenceStartExceptions.add("„"); sentenceStartExceptions.add("“"); sentenceStartExceptions.add("«"); sentenceStartExceptions.add("»"); sentenceStartExceptions.add("."); } private static final Set<String> exceptions = new HashSet<>(); static { /* * These are words that Morphy only knows as non-nouns. The proper * solution is to add all those to our Morphy data, but as a simple * workaround to avoid false alarms, these words can be added here. */ exceptions.add("Tel"); // Tel. = Telefon exceptions.add("Unschuldiger"); exceptions.add("Vorgesetzter"); exceptions.add("Abs"); // Abs. = Abkürzung für Absatz, Absender, ... exceptions.add("Klappe"); exceptions.add("Vorfahre"); exceptions.add("Mittler"); exceptions.add("Hr"); // Hr. = Abkürzung für Herr exceptions.add("Schwarz"); exceptions.add("Genese"); exceptions.add("Rosa"); exceptions.add("Auftrieb"); exceptions.add("Zuschnitt"); exceptions.add("Geschossen"); exceptions.add("Vortrieb"); exceptions.add("Abtrieb"); exceptions.add("Gesandter"); exceptions.add("Durchfahrt"); exceptions.add("Durchgriff"); exceptions.add("Überfahrt"); exceptions.add("Zeche"); exceptions.add("Sparte"); exceptions.add("Sparten"); exceptions.add("Heiliger"); exceptions.add("Reisender"); exceptions.add("Hochdeutsch"); exceptions.add("Pest"); exceptions.add("Schwinge"); exceptions.add("Verlies"); exceptions.add("Nachfolge"); exceptions.add("Stift"); exceptions.add("Belange"); exceptions.add("Geistlicher"); exceptions.add("Jenseits"); exceptions.add("Abends"); exceptions.add("Abgeordneter"); exceptions.add("Angestellter"); exceptions.add("Abriss"); exceptions.add("Ahne"); exceptions.add("Ähnlichem"); exceptions.add("Ähnliches"); // je nach Kontext groß (TODO), z.B. "Er hat Ähnliches erlebt" exceptions.add("Allerlei"); exceptions.add("Anklang"); exceptions.add("Anstrich"); exceptions.add("Armes"); exceptions.add("Aus"); // "vor dem Aus stehen" exceptions.add("Ausdrücke"); exceptions.add("Auswüchsen"); exceptions.add("Bände"); exceptions.add("Bänden"); exceptions.add("Beauftragter"); exceptions.add("Belange"); exceptions.add("besonderes"); // je nach Kontext groß (TODO): "etwas Besonderes" exceptions.add("Biss"); exceptions.add("De"); // "De Morgan" etc exceptions.add("Dr"); exceptions.add("Durcheinander"); exceptions.add("Eindrücke"); exceptions.add("Erwachsener"); exceptions.add("Flöße"); exceptions.add("Folgendes"); // je nach Kontext groß (TODO)... exceptions.add("Fort"); exceptions.add("Fraß"); exceptions.add("Für"); // "das Für und Wider" exceptions.add("Genüge"); exceptions.add("Gläubiger"); exceptions.add("Goldener"); // Goldener Schnitt exceptions.add("Große"); // Alexander der Große, der Große Bär exceptions.add("Großen"); exceptions.add("Guten"); // das Kap der Guten Hoffnung exceptions.add("Hechte"); exceptions.add("Herzöge"); exceptions.add("Herzögen"); exceptions.add("Hinfahrt"); exceptions.add("Hundert"); // je nach Kontext groß (TODO) exceptions.add("Ihnen"); exceptions.add("Ihr"); exceptions.add("Ihre"); exceptions.add("Ihrem"); exceptions.add("Ihren"); exceptions.add("Ihrer"); exceptions.add("Ihres"); exceptions.add("Infrarot"); exceptions.add("Jenseits"); exceptions.add("Jugendlicher"); exceptions.add("Jünger"); exceptions.add("Klaue"); exceptions.add("Kleine"); // der Kleine Bär exceptions.add("Konditional"); exceptions.add("Krähe"); exceptions.add("Kurzem"); exceptions.add("Landwirtschaft"); exceptions.add("Langem"); exceptions.add("Längerem"); exceptions.add("Las"); // Las Vegas, nicht "lesen" exceptions.add("Le"); // "Le Monde" etc exceptions.add("Letzt"); exceptions.add("Letzt"); // "zu guter Letzt" exceptions.add("Letztere"); exceptions.add("Letzterer"); exceptions.add("Letzteres"); exceptions.add("Link"); exceptions.add("Links"); exceptions.add("Löhne"); exceptions.add("Luden"); exceptions.add("Mitfahrt"); exceptions.add("Mr"); exceptions.add("Mrd"); exceptions.add("Mrs"); exceptions.add("Nachfrage"); exceptions.add("Nachts"); // "des Nachts", "eines Nachts" exceptions.add("Nähte"); exceptions.add("Nähten"); exceptions.add("Neuem"); exceptions.add("Neues"); // nichts Neues exceptions.add("Nr"); exceptions.add("Nutze"); // zu Nutze exceptions.add("Obdachloser"); exceptions.add("Oder"); // der Fluss exceptions.add("Patsche"); exceptions.add("Pfiffe"); exceptions.add("Pfiffen"); exceptions.add("Prof"); exceptions.add("Puste"); exceptions.add("Sachverständiger"); exceptions.add("Sankt"); exceptions.add("Scheine"); exceptions.add("Scheiße"); exceptions.add("Schuft"); exceptions.add("Schufte"); exceptions.add("Schuld"); exceptions.add("Schwärme"); exceptions.add("Schwarzes"); // Schwarzes Brett exceptions.add("Sie"); exceptions.add("Spitz"); exceptions.add("St"); // Paris St. Germain exceptions.add("Stereotyp"); exceptions.add("Störe"); exceptions.add("Tausend"); // je nach Kontext groß (TODO) exceptions.add("Toter"); exceptions.add("tun"); // "Sie müssen das tun" exceptions.add("Übrigen"); // je nach Kontext groß (TODO), z.B. "im Übrigen" exceptions.add("Unvorhergesehenes"); // je nach Kontext groß (TODO), z.B. "etwas Unvorhergesehenes" exceptions.add("Verantwortlicher"); exceptions.add("Verwandter"); exceptions.add("Vielfaches"); exceptions.add("Vorsitzender"); exceptions.add("Fraktionsvorsitzender"); exceptions.add("Weitem"); exceptions.add("Weiteres"); exceptions.add("Wicht"); exceptions.add("Wichtiges"); exceptions.add("Wider"); // "das Für und Wider" exceptions.add("Wild"); exceptions.add("Zeche"); exceptions.add("Zusage"); exceptions.add("Zwinge"); exceptions.add("Erster"); // "er wurde Erster im Langlauf" exceptions.add("Zweiter"); exceptions.add("Dritter"); exceptions.add("Vierter"); exceptions.add("Fünfter"); exceptions.add("Sechster"); exceptions.add("Siebter"); exceptions.add("Achter"); exceptions.add("Neunter"); exceptions.add("Erste"); // "sie wurde Erste im Langlauf" exceptions.add("Zweite"); exceptions.add("Dritte"); exceptions.add("Vierte"); exceptions.add("Fünfte"); exceptions.add("Sechste"); exceptions.add("Siebte"); exceptions.add("Achte"); exceptions.add("Neunte"); // TODO: alle Sprachen + flektierte Formen exceptions.add("Afrikanisch"); exceptions.add("Altarabisch"); exceptions.add("Altchinesisch"); exceptions.add("Altgriechisch"); exceptions.add("Althochdeutsch"); exceptions.add("Altpersisch"); exceptions.add("Amerikanisch"); exceptions.add("Arabisch"); exceptions.add("Chinesisch"); exceptions.add("Dänisch"); exceptions.add("Deutsch"); exceptions.add("Englisch"); exceptions.add("Finnisch"); exceptions.add("Französisch"); exceptions.add("Frühneuhochdeutsch"); exceptions.add("Germanisch"); exceptions.add("Griechisch"); exceptions.add("Hocharabisch"); exceptions.add("Hochchinesisch"); exceptions.add("Hochdeutsch"); exceptions.add("Holländisch"); exceptions.add("Italienisch"); exceptions.add("Japanisch"); exceptions.add("Jiddisch"); exceptions.add("Jugoslawisch"); exceptions.add("Koreanisch"); exceptions.add("Kroatisch"); exceptions.add("Lateinisch"); exceptions.add("Luxemburgisch"); exceptions.add("Mittelhochdeutsch"); exceptions.add("Neuhochdeutsch"); exceptions.add("Niederländisch"); exceptions.add("Norwegisch"); exceptions.add("Persisch"); exceptions.add("Polnisch"); exceptions.add("Portugiesisch"); exceptions.add("Russisch"); exceptions.add("Schwedisch"); exceptions.add("Schweizerisch"); exceptions.add("Serbisch"); exceptions.add("Serbokroatisch"); exceptions.add("Slawisch"); exceptions.add("Spanisch"); exceptions.add("Tschechisch"); exceptions.add("Türkisch"); exceptions.add("Ukrainisch"); exceptions.add("Ungarisch"); exceptions.add("Weißrussisch"); // Änderungen an der Rechtschreibreform 2006 erlauben hier Großschreibung: exceptions.add("Dein"); exceptions.add("Deine"); exceptions.add("Deinem"); exceptions.add("Deinen"); exceptions.add("Deiner"); exceptions.add("Deines"); exceptions.add("Dich"); exceptions.add("Dir"); exceptions.add("Du"); exceptions.add("Euch"); exceptions.add("Euer"); exceptions.add("Eure"); exceptions.add("Eurem"); exceptions.add("Euren"); exceptions.add("Eures"); } private static final Set<String> myExceptionPhrases = new HashSet<>(); static { // use proper upper/lowercase spelling here: myExceptionPhrases.add("nichts Wichtigeres"); myExceptionPhrases.add("nichts Schöneres"); myExceptionPhrases.add("ohne Wenn und Aber"); myExceptionPhrases.add("Große Koalition"); myExceptionPhrases.add("Großen Koalition"); myExceptionPhrases.add("im Großen und Ganzen"); myExceptionPhrases.add("Im Großen und Ganzen"); myExceptionPhrases.add("im Guten wie im Schlechten"); myExceptionPhrases.add("Im Guten wie im Schlechten"); myExceptionPhrases.add("Russisches Reich"); myExceptionPhrases.add("Tel Aviv"); myExceptionPhrases.add("Erster Weltkrieg"); myExceptionPhrases.add("Ersten Weltkriegs"); myExceptionPhrases.add("Ersten Weltkrieges"); myExceptionPhrases.add("Erstem Weltkrieg"); myExceptionPhrases.add("Zweiter Weltkrieg"); myExceptionPhrases.add("Zweiten Weltkriegs"); myExceptionPhrases.add("Zweiten Weltkrieges"); myExceptionPhrases.add("Zweitem Weltkrieg"); myExceptionPhrases.add("Vielfaches"); myExceptionPhrases.add("Auswärtiges Amt"); myExceptionPhrases.add("Auswärtigen Amt"); myExceptionPhrases.add("Auswärtigen Amts"); myExceptionPhrases.add("Auswärtigen Amtes"); myExceptionPhrases.add("Bürgerliches Gesetzbuch"); myExceptionPhrases.add("Bürgerlichen Gesetzbuch"); myExceptionPhrases.add("Bürgerlichen Gesetzbuchs"); myExceptionPhrases.add("Bürgerlichen Gesetzbuches"); myExceptionPhrases.add("Haute Couture"); myExceptionPhrases.add("aus dem Nichts"); myExceptionPhrases.add("Kleiner Bär"); // das Sternbild myExceptionPhrases.add("Zehn Gebote"); myExceptionPhrases.add("Römische Reich Deutscher Nation"); myExceptionPhrases.add("ein absolutes Muss"); myExceptionPhrases.add("ein Muss"); } private static final Set<String> substVerbenExceptions = new HashSet<>(); static { substVerbenExceptions.add("scheinen"); substVerbenExceptions.add("klar"); substVerbenExceptions.add("heißen"); substVerbenExceptions.add("einen"); substVerbenExceptions.add("gehören"); substVerbenExceptions.add("bedeutet"); // "und das bedeutet..." substVerbenExceptions.add("ermöglicht"); // "und das ermöglicht..." substVerbenExceptions.add("funktioniert"); // "Das funktioniert..." substVerbenExceptions.add("sollen"); substVerbenExceptions.add("werden"); substVerbenExceptions.add("dürfen"); substVerbenExceptions.add("müssen"); substVerbenExceptions.add("so"); substVerbenExceptions.add("ist"); substVerbenExceptions.add("können"); substVerbenExceptions.add("mein"); // "etwas, das mein Interesse geweckt hat" substVerbenExceptions.add("sein"); substVerbenExceptions.add("muss"); substVerbenExceptions.add("muß"); substVerbenExceptions.add("wollen"); substVerbenExceptions.add("habe"); substVerbenExceptions.add("ein"); // nicht "einen" (Verb) substVerbenExceptions.add("tun"); // "...dann wird er das tun." substVerbenExceptions.add("bestätigt"); substVerbenExceptions.add("bestätigte"); substVerbenExceptions.add("bestätigten"); substVerbenExceptions.add("bekommen"); } public CaseRule(final ResourceBundle messages, final German german) { if (messages != null) { super.setCategory(new Category(messages.getString("category_case"))); } this.tagger = (GermanTagger) german.getTagger(); addExamplePair(Example.wrong("<marker>Das laufen</marker> fällt mir schwer."), Example.fixed("<marker>Das Laufen</marker> fällt mir schwer.")); } @Override public String getId() { return "DE_CASE"; } @Override public String getDescription() { return "Großschreibung von Nomen und substantivierten Verben"; } @Override public RuleMatch[] match(final AnalyzedSentence sentence) throws IOException { final List<RuleMatch> ruleMatches = new ArrayList<>(); final AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); boolean prevTokenIsDas = false; for (int i = 0; i < tokens.length; i++) { //Note: defaulting to the first analysis is only save if we only query for sentence start final String posToken = tokens[i].getAnalyzedToken(0).getPOSTag(); if (posToken != null && posToken.equals(JLanguageTool.SENTENCE_START_TAGNAME)) { continue; } if (i == 1) { // don't care about first word, UppercaseSentenceStartRule does this already if (nounIndicators.contains(tokens[i].getToken().toLowerCase())) { prevTokenIsDas = true; } continue; } if (i > 0 && (tokens[i-1].getToken().equals("Herr") || tokens[i-1].getToken().equals("Herrn") || tokens[i-1].getToken().equals("Frau")) ) { // "Frau Stieg" could be a name, ignore continue; } final AnalyzedTokenReadings analyzedToken = tokens[i]; final String token = analyzedToken.getToken(); List<AnalyzedToken> readings = analyzedToken.getReadings(); AnalyzedTokenReadings analyzedGermanToken2; boolean isBaseform = false; if (analyzedToken.getReadingsLength() >= 1 && analyzedToken.hasLemma(token)) { isBaseform = true; } if ((readings == null || analyzedToken.getAnalyzedToken(0).getPOSTag() == null || GermanHelper.hasReadingOfType(analyzedToken, GermanToken.POSType.VERB)) && isBaseform) { // no match, e.g. for "Groß": try if there's a match for the lowercased word: analyzedGermanToken2 = tagger.lookup(token.toLowerCase()); if (analyzedGermanToken2 != null) { readings = analyzedGermanToken2.getReadings(); } boolean nextTokenIsPersonalPronoun = false; if (i < tokens.length - 1) { // avoid false alarm for "Das haben wir getan." etc: nextTokenIsPersonalPronoun = tokens[i + 1].hasPartialPosTag("PRO:PER") || tokens[i + 1].getToken().equals("Sie"); } potentiallyAddLowercaseMatch(ruleMatches, tokens[i], prevTokenIsDas, token, nextTokenIsPersonalPronoun); } prevTokenIsDas = nounIndicators.contains(tokens[i].getToken().toLowerCase()); if (readings == null) { continue; } final boolean hasNounReading = GermanHelper.hasReadingOfType(analyzedToken, GermanToken.POSType.NOMEN); if (hasNounReading) { // it's the spell checker's task to check that nouns are uppercase continue; } // TODO: this lookup should only happen once: analyzedGermanToken2 = tagger.lookup(token.toLowerCase()); if (analyzedToken.getAnalyzedToken(0).getPOSTag() == null && analyzedGermanToken2 == null) { continue; } if (analyzedToken.getAnalyzedToken(0).getPOSTag() == null && analyzedGermanToken2 != null && analyzedGermanToken2.getAnalyzedToken(0).getPOSTag() == null) { // unknown word, probably a name etc continue; } potentiallyAddUppercaseMatch(ruleMatches, tokens, i, analyzedToken, token); } return toRuleMatchArray(ruleMatches); } private void potentiallyAddLowercaseMatch(List<RuleMatch> ruleMatches, AnalyzedTokenReadings tokenReadings, boolean prevTokenIsDas, String token, boolean nextTokenIsPersonalPronoun) { if (prevTokenIsDas && !nextTokenIsPersonalPronoun) { // e.g. essen -> Essen if (Character.isLowerCase(token.charAt(0)) && !substVerbenExceptions.contains(token)) { final String msg = "Substantivierte Verben werden großgeschrieben."; final RuleMatch ruleMatch = new RuleMatch(this, tokenReadings.getStartPos(), tokenReadings.getStartPos() + token.length(), msg); final String word = tokenReadings.getToken(); final String fixedWord = StringTools.uppercaseFirstChar(word); ruleMatch.setSuggestedReplacement(fixedWord); ruleMatches.add(ruleMatch); } } } private void potentiallyAddUppercaseMatch(List<RuleMatch> ruleMatches, AnalyzedTokenReadings[] tokens, int i, AnalyzedTokenReadings analyzedToken, String token) { if (Character.isUpperCase(token.charAt(0)) && token.length() > 1 && // length limit = ignore abbreviations !sentenceStartExceptions.contains(tokens[i - 1].getToken()) && !StringTools.isAllUppercase(token) && !exceptions.contains(token) && !GermanHelper.hasReadingOfType(analyzedToken, POSType.PROPER_NOUN) && !analyzedToken.isSentenceEnd() && !( (tokens[i-1].getToken().equals("]") || tokens[i-1].getToken().equals(")")) && // sentence starts with […] ( (i == 4 && tokens[i-2].getToken().equals("…")) || (i == 6 && tokens[i-2].getToken().equals(".")) ) ) && !isExceptionPhrase(i, tokens)) { final String msg = "Außer am Satzanfang werden nur Nomen und Eigennamen großgeschrieben"; final RuleMatch ruleMatch = new RuleMatch(this, tokens[i].getStartPos(), tokens[i].getStartPos() + token.length(), msg); final String word = tokens[i].getToken(); final String fixedWord = Character.toLowerCase(word.charAt(0)) + word.substring(1); ruleMatch.setSuggestedReplacement(fixedWord); ruleMatches.add(ruleMatch); } } private boolean isExceptionPhrase(int i, AnalyzedTokenReadings[] tokens) { for (String exc : myExceptionPhrases) { final String[] parts = exc.split(" "); for (int j = 0; j < parts.length; j++) { if (parts[j].equals(tokens[i].getToken())) { final int startIndex = i-j; if (compareLists(tokens, startIndex, startIndex+parts.length-1, parts)) { return true; } } } } return false; } private boolean compareLists(AnalyzedTokenReadings[] tokens, int startIndex, int endIndex, String[] parts) { if (startIndex < 0) { return false; } int i = 0; for (int j = startIndex; j <= endIndex; j++) { if (i >= parts.length) { return false; } if (!tokens[j].getToken().equals(parts[i])) { return false; } i++; } return true; } @Override public void reset() { // nothing } }
osyvokon/languagetool
languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/CaseRule.java
7,318
// "De Morgan" etc
line_comment
nl
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.de; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedToken; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.JLanguageTool; import org.languagetool.language.German; import org.languagetool.rules.Category; import org.languagetool.rules.Example; import org.languagetool.rules.RuleMatch; import org.languagetool.tagging.de.GermanTagger; import org.languagetool.tagging.de.GermanToken; import org.languagetool.tagging.de.GermanToken.POSType; import org.languagetool.tools.StringTools; import java.io.IOException; import java.util.*; /** * Check that adjectives and verbs are not written with an uppercase * first letter (except at the start of a sentence) and cases * like this: <tt>Das laufen f&auml;llt mir leicht.</tt> (<tt>laufen</tt> needs * to be uppercased). * * @author Daniel Naber */ public class CaseRule extends GermanRule { private final GermanTagger tagger; // wenn hinter diesen Wörtern ein Verb steht, ist es wohl ein substantiviertes Verb, // muss also groß geschrieben werden: private static final Set<String> nounIndicators = new HashSet<>(); static { nounIndicators.add("das"); nounIndicators.add("sein"); //indicator.add("seines"); // TODO: ? //nounIndicators.add("ihr"); // would cause false alarm e.g. "Auf ihr stehen die Ruinen..." nounIndicators.add("mein"); nounIndicators.add("dein"); nounIndicators.add("euer"); //indicator.add("ihres"); //indicator.add("ihren"); } private static final Set<String> sentenceStartExceptions = new HashSet<>(); static { sentenceStartExceptions.add("("); sentenceStartExceptions.add(":"); sentenceStartExceptions.add("\""); sentenceStartExceptions.add("'"); sentenceStartExceptions.add("„"); sentenceStartExceptions.add("“"); sentenceStartExceptions.add("«"); sentenceStartExceptions.add("»"); sentenceStartExceptions.add("."); } private static final Set<String> exceptions = new HashSet<>(); static { /* * These are words that Morphy only knows as non-nouns. The proper * solution is to add all those to our Morphy data, but as a simple * workaround to avoid false alarms, these words can be added here. */ exceptions.add("Tel"); // Tel. = Telefon exceptions.add("Unschuldiger"); exceptions.add("Vorgesetzter"); exceptions.add("Abs"); // Abs. = Abkürzung für Absatz, Absender, ... exceptions.add("Klappe"); exceptions.add("Vorfahre"); exceptions.add("Mittler"); exceptions.add("Hr"); // Hr. = Abkürzung für Herr exceptions.add("Schwarz"); exceptions.add("Genese"); exceptions.add("Rosa"); exceptions.add("Auftrieb"); exceptions.add("Zuschnitt"); exceptions.add("Geschossen"); exceptions.add("Vortrieb"); exceptions.add("Abtrieb"); exceptions.add("Gesandter"); exceptions.add("Durchfahrt"); exceptions.add("Durchgriff"); exceptions.add("Überfahrt"); exceptions.add("Zeche"); exceptions.add("Sparte"); exceptions.add("Sparten"); exceptions.add("Heiliger"); exceptions.add("Reisender"); exceptions.add("Hochdeutsch"); exceptions.add("Pest"); exceptions.add("Schwinge"); exceptions.add("Verlies"); exceptions.add("Nachfolge"); exceptions.add("Stift"); exceptions.add("Belange"); exceptions.add("Geistlicher"); exceptions.add("Jenseits"); exceptions.add("Abends"); exceptions.add("Abgeordneter"); exceptions.add("Angestellter"); exceptions.add("Abriss"); exceptions.add("Ahne"); exceptions.add("Ähnlichem"); exceptions.add("Ähnliches"); // je nach Kontext groß (TODO), z.B. "Er hat Ähnliches erlebt" exceptions.add("Allerlei"); exceptions.add("Anklang"); exceptions.add("Anstrich"); exceptions.add("Armes"); exceptions.add("Aus"); // "vor dem Aus stehen" exceptions.add("Ausdrücke"); exceptions.add("Auswüchsen"); exceptions.add("Bände"); exceptions.add("Bänden"); exceptions.add("Beauftragter"); exceptions.add("Belange"); exceptions.add("besonderes"); // je nach Kontext groß (TODO): "etwas Besonderes" exceptions.add("Biss"); exceptions.add("De"); // "De Morgan"<SUF> exceptions.add("Dr"); exceptions.add("Durcheinander"); exceptions.add("Eindrücke"); exceptions.add("Erwachsener"); exceptions.add("Flöße"); exceptions.add("Folgendes"); // je nach Kontext groß (TODO)... exceptions.add("Fort"); exceptions.add("Fraß"); exceptions.add("Für"); // "das Für und Wider" exceptions.add("Genüge"); exceptions.add("Gläubiger"); exceptions.add("Goldener"); // Goldener Schnitt exceptions.add("Große"); // Alexander der Große, der Große Bär exceptions.add("Großen"); exceptions.add("Guten"); // das Kap der Guten Hoffnung exceptions.add("Hechte"); exceptions.add("Herzöge"); exceptions.add("Herzögen"); exceptions.add("Hinfahrt"); exceptions.add("Hundert"); // je nach Kontext groß (TODO) exceptions.add("Ihnen"); exceptions.add("Ihr"); exceptions.add("Ihre"); exceptions.add("Ihrem"); exceptions.add("Ihren"); exceptions.add("Ihrer"); exceptions.add("Ihres"); exceptions.add("Infrarot"); exceptions.add("Jenseits"); exceptions.add("Jugendlicher"); exceptions.add("Jünger"); exceptions.add("Klaue"); exceptions.add("Kleine"); // der Kleine Bär exceptions.add("Konditional"); exceptions.add("Krähe"); exceptions.add("Kurzem"); exceptions.add("Landwirtschaft"); exceptions.add("Langem"); exceptions.add("Längerem"); exceptions.add("Las"); // Las Vegas, nicht "lesen" exceptions.add("Le"); // "Le Monde" etc exceptions.add("Letzt"); exceptions.add("Letzt"); // "zu guter Letzt" exceptions.add("Letztere"); exceptions.add("Letzterer"); exceptions.add("Letzteres"); exceptions.add("Link"); exceptions.add("Links"); exceptions.add("Löhne"); exceptions.add("Luden"); exceptions.add("Mitfahrt"); exceptions.add("Mr"); exceptions.add("Mrd"); exceptions.add("Mrs"); exceptions.add("Nachfrage"); exceptions.add("Nachts"); // "des Nachts", "eines Nachts" exceptions.add("Nähte"); exceptions.add("Nähten"); exceptions.add("Neuem"); exceptions.add("Neues"); // nichts Neues exceptions.add("Nr"); exceptions.add("Nutze"); // zu Nutze exceptions.add("Obdachloser"); exceptions.add("Oder"); // der Fluss exceptions.add("Patsche"); exceptions.add("Pfiffe"); exceptions.add("Pfiffen"); exceptions.add("Prof"); exceptions.add("Puste"); exceptions.add("Sachverständiger"); exceptions.add("Sankt"); exceptions.add("Scheine"); exceptions.add("Scheiße"); exceptions.add("Schuft"); exceptions.add("Schufte"); exceptions.add("Schuld"); exceptions.add("Schwärme"); exceptions.add("Schwarzes"); // Schwarzes Brett exceptions.add("Sie"); exceptions.add("Spitz"); exceptions.add("St"); // Paris St. Germain exceptions.add("Stereotyp"); exceptions.add("Störe"); exceptions.add("Tausend"); // je nach Kontext groß (TODO) exceptions.add("Toter"); exceptions.add("tun"); // "Sie müssen das tun" exceptions.add("Übrigen"); // je nach Kontext groß (TODO), z.B. "im Übrigen" exceptions.add("Unvorhergesehenes"); // je nach Kontext groß (TODO), z.B. "etwas Unvorhergesehenes" exceptions.add("Verantwortlicher"); exceptions.add("Verwandter"); exceptions.add("Vielfaches"); exceptions.add("Vorsitzender"); exceptions.add("Fraktionsvorsitzender"); exceptions.add("Weitem"); exceptions.add("Weiteres"); exceptions.add("Wicht"); exceptions.add("Wichtiges"); exceptions.add("Wider"); // "das Für und Wider" exceptions.add("Wild"); exceptions.add("Zeche"); exceptions.add("Zusage"); exceptions.add("Zwinge"); exceptions.add("Erster"); // "er wurde Erster im Langlauf" exceptions.add("Zweiter"); exceptions.add("Dritter"); exceptions.add("Vierter"); exceptions.add("Fünfter"); exceptions.add("Sechster"); exceptions.add("Siebter"); exceptions.add("Achter"); exceptions.add("Neunter"); exceptions.add("Erste"); // "sie wurde Erste im Langlauf" exceptions.add("Zweite"); exceptions.add("Dritte"); exceptions.add("Vierte"); exceptions.add("Fünfte"); exceptions.add("Sechste"); exceptions.add("Siebte"); exceptions.add("Achte"); exceptions.add("Neunte"); // TODO: alle Sprachen + flektierte Formen exceptions.add("Afrikanisch"); exceptions.add("Altarabisch"); exceptions.add("Altchinesisch"); exceptions.add("Altgriechisch"); exceptions.add("Althochdeutsch"); exceptions.add("Altpersisch"); exceptions.add("Amerikanisch"); exceptions.add("Arabisch"); exceptions.add("Chinesisch"); exceptions.add("Dänisch"); exceptions.add("Deutsch"); exceptions.add("Englisch"); exceptions.add("Finnisch"); exceptions.add("Französisch"); exceptions.add("Frühneuhochdeutsch"); exceptions.add("Germanisch"); exceptions.add("Griechisch"); exceptions.add("Hocharabisch"); exceptions.add("Hochchinesisch"); exceptions.add("Hochdeutsch"); exceptions.add("Holländisch"); exceptions.add("Italienisch"); exceptions.add("Japanisch"); exceptions.add("Jiddisch"); exceptions.add("Jugoslawisch"); exceptions.add("Koreanisch"); exceptions.add("Kroatisch"); exceptions.add("Lateinisch"); exceptions.add("Luxemburgisch"); exceptions.add("Mittelhochdeutsch"); exceptions.add("Neuhochdeutsch"); exceptions.add("Niederländisch"); exceptions.add("Norwegisch"); exceptions.add("Persisch"); exceptions.add("Polnisch"); exceptions.add("Portugiesisch"); exceptions.add("Russisch"); exceptions.add("Schwedisch"); exceptions.add("Schweizerisch"); exceptions.add("Serbisch"); exceptions.add("Serbokroatisch"); exceptions.add("Slawisch"); exceptions.add("Spanisch"); exceptions.add("Tschechisch"); exceptions.add("Türkisch"); exceptions.add("Ukrainisch"); exceptions.add("Ungarisch"); exceptions.add("Weißrussisch"); // Änderungen an der Rechtschreibreform 2006 erlauben hier Großschreibung: exceptions.add("Dein"); exceptions.add("Deine"); exceptions.add("Deinem"); exceptions.add("Deinen"); exceptions.add("Deiner"); exceptions.add("Deines"); exceptions.add("Dich"); exceptions.add("Dir"); exceptions.add("Du"); exceptions.add("Euch"); exceptions.add("Euer"); exceptions.add("Eure"); exceptions.add("Eurem"); exceptions.add("Euren"); exceptions.add("Eures"); } private static final Set<String> myExceptionPhrases = new HashSet<>(); static { // use proper upper/lowercase spelling here: myExceptionPhrases.add("nichts Wichtigeres"); myExceptionPhrases.add("nichts Schöneres"); myExceptionPhrases.add("ohne Wenn und Aber"); myExceptionPhrases.add("Große Koalition"); myExceptionPhrases.add("Großen Koalition"); myExceptionPhrases.add("im Großen und Ganzen"); myExceptionPhrases.add("Im Großen und Ganzen"); myExceptionPhrases.add("im Guten wie im Schlechten"); myExceptionPhrases.add("Im Guten wie im Schlechten"); myExceptionPhrases.add("Russisches Reich"); myExceptionPhrases.add("Tel Aviv"); myExceptionPhrases.add("Erster Weltkrieg"); myExceptionPhrases.add("Ersten Weltkriegs"); myExceptionPhrases.add("Ersten Weltkrieges"); myExceptionPhrases.add("Erstem Weltkrieg"); myExceptionPhrases.add("Zweiter Weltkrieg"); myExceptionPhrases.add("Zweiten Weltkriegs"); myExceptionPhrases.add("Zweiten Weltkrieges"); myExceptionPhrases.add("Zweitem Weltkrieg"); myExceptionPhrases.add("Vielfaches"); myExceptionPhrases.add("Auswärtiges Amt"); myExceptionPhrases.add("Auswärtigen Amt"); myExceptionPhrases.add("Auswärtigen Amts"); myExceptionPhrases.add("Auswärtigen Amtes"); myExceptionPhrases.add("Bürgerliches Gesetzbuch"); myExceptionPhrases.add("Bürgerlichen Gesetzbuch"); myExceptionPhrases.add("Bürgerlichen Gesetzbuchs"); myExceptionPhrases.add("Bürgerlichen Gesetzbuches"); myExceptionPhrases.add("Haute Couture"); myExceptionPhrases.add("aus dem Nichts"); myExceptionPhrases.add("Kleiner Bär"); // das Sternbild myExceptionPhrases.add("Zehn Gebote"); myExceptionPhrases.add("Römische Reich Deutscher Nation"); myExceptionPhrases.add("ein absolutes Muss"); myExceptionPhrases.add("ein Muss"); } private static final Set<String> substVerbenExceptions = new HashSet<>(); static { substVerbenExceptions.add("scheinen"); substVerbenExceptions.add("klar"); substVerbenExceptions.add("heißen"); substVerbenExceptions.add("einen"); substVerbenExceptions.add("gehören"); substVerbenExceptions.add("bedeutet"); // "und das bedeutet..." substVerbenExceptions.add("ermöglicht"); // "und das ermöglicht..." substVerbenExceptions.add("funktioniert"); // "Das funktioniert..." substVerbenExceptions.add("sollen"); substVerbenExceptions.add("werden"); substVerbenExceptions.add("dürfen"); substVerbenExceptions.add("müssen"); substVerbenExceptions.add("so"); substVerbenExceptions.add("ist"); substVerbenExceptions.add("können"); substVerbenExceptions.add("mein"); // "etwas, das mein Interesse geweckt hat" substVerbenExceptions.add("sein"); substVerbenExceptions.add("muss"); substVerbenExceptions.add("muß"); substVerbenExceptions.add("wollen"); substVerbenExceptions.add("habe"); substVerbenExceptions.add("ein"); // nicht "einen" (Verb) substVerbenExceptions.add("tun"); // "...dann wird er das tun." substVerbenExceptions.add("bestätigt"); substVerbenExceptions.add("bestätigte"); substVerbenExceptions.add("bestätigten"); substVerbenExceptions.add("bekommen"); } public CaseRule(final ResourceBundle messages, final German german) { if (messages != null) { super.setCategory(new Category(messages.getString("category_case"))); } this.tagger = (GermanTagger) german.getTagger(); addExamplePair(Example.wrong("<marker>Das laufen</marker> fällt mir schwer."), Example.fixed("<marker>Das Laufen</marker> fällt mir schwer.")); } @Override public String getId() { return "DE_CASE"; } @Override public String getDescription() { return "Großschreibung von Nomen und substantivierten Verben"; } @Override public RuleMatch[] match(final AnalyzedSentence sentence) throws IOException { final List<RuleMatch> ruleMatches = new ArrayList<>(); final AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace(); boolean prevTokenIsDas = false; for (int i = 0; i < tokens.length; i++) { //Note: defaulting to the first analysis is only save if we only query for sentence start final String posToken = tokens[i].getAnalyzedToken(0).getPOSTag(); if (posToken != null && posToken.equals(JLanguageTool.SENTENCE_START_TAGNAME)) { continue; } if (i == 1) { // don't care about first word, UppercaseSentenceStartRule does this already if (nounIndicators.contains(tokens[i].getToken().toLowerCase())) { prevTokenIsDas = true; } continue; } if (i > 0 && (tokens[i-1].getToken().equals("Herr") || tokens[i-1].getToken().equals("Herrn") || tokens[i-1].getToken().equals("Frau")) ) { // "Frau Stieg" could be a name, ignore continue; } final AnalyzedTokenReadings analyzedToken = tokens[i]; final String token = analyzedToken.getToken(); List<AnalyzedToken> readings = analyzedToken.getReadings(); AnalyzedTokenReadings analyzedGermanToken2; boolean isBaseform = false; if (analyzedToken.getReadingsLength() >= 1 && analyzedToken.hasLemma(token)) { isBaseform = true; } if ((readings == null || analyzedToken.getAnalyzedToken(0).getPOSTag() == null || GermanHelper.hasReadingOfType(analyzedToken, GermanToken.POSType.VERB)) && isBaseform) { // no match, e.g. for "Groß": try if there's a match for the lowercased word: analyzedGermanToken2 = tagger.lookup(token.toLowerCase()); if (analyzedGermanToken2 != null) { readings = analyzedGermanToken2.getReadings(); } boolean nextTokenIsPersonalPronoun = false; if (i < tokens.length - 1) { // avoid false alarm for "Das haben wir getan." etc: nextTokenIsPersonalPronoun = tokens[i + 1].hasPartialPosTag("PRO:PER") || tokens[i + 1].getToken().equals("Sie"); } potentiallyAddLowercaseMatch(ruleMatches, tokens[i], prevTokenIsDas, token, nextTokenIsPersonalPronoun); } prevTokenIsDas = nounIndicators.contains(tokens[i].getToken().toLowerCase()); if (readings == null) { continue; } final boolean hasNounReading = GermanHelper.hasReadingOfType(analyzedToken, GermanToken.POSType.NOMEN); if (hasNounReading) { // it's the spell checker's task to check that nouns are uppercase continue; } // TODO: this lookup should only happen once: analyzedGermanToken2 = tagger.lookup(token.toLowerCase()); if (analyzedToken.getAnalyzedToken(0).getPOSTag() == null && analyzedGermanToken2 == null) { continue; } if (analyzedToken.getAnalyzedToken(0).getPOSTag() == null && analyzedGermanToken2 != null && analyzedGermanToken2.getAnalyzedToken(0).getPOSTag() == null) { // unknown word, probably a name etc continue; } potentiallyAddUppercaseMatch(ruleMatches, tokens, i, analyzedToken, token); } return toRuleMatchArray(ruleMatches); } private void potentiallyAddLowercaseMatch(List<RuleMatch> ruleMatches, AnalyzedTokenReadings tokenReadings, boolean prevTokenIsDas, String token, boolean nextTokenIsPersonalPronoun) { if (prevTokenIsDas && !nextTokenIsPersonalPronoun) { // e.g. essen -> Essen if (Character.isLowerCase(token.charAt(0)) && !substVerbenExceptions.contains(token)) { final String msg = "Substantivierte Verben werden großgeschrieben."; final RuleMatch ruleMatch = new RuleMatch(this, tokenReadings.getStartPos(), tokenReadings.getStartPos() + token.length(), msg); final String word = tokenReadings.getToken(); final String fixedWord = StringTools.uppercaseFirstChar(word); ruleMatch.setSuggestedReplacement(fixedWord); ruleMatches.add(ruleMatch); } } } private void potentiallyAddUppercaseMatch(List<RuleMatch> ruleMatches, AnalyzedTokenReadings[] tokens, int i, AnalyzedTokenReadings analyzedToken, String token) { if (Character.isUpperCase(token.charAt(0)) && token.length() > 1 && // length limit = ignore abbreviations !sentenceStartExceptions.contains(tokens[i - 1].getToken()) && !StringTools.isAllUppercase(token) && !exceptions.contains(token) && !GermanHelper.hasReadingOfType(analyzedToken, POSType.PROPER_NOUN) && !analyzedToken.isSentenceEnd() && !( (tokens[i-1].getToken().equals("]") || tokens[i-1].getToken().equals(")")) && // sentence starts with […] ( (i == 4 && tokens[i-2].getToken().equals("…")) || (i == 6 && tokens[i-2].getToken().equals(".")) ) ) && !isExceptionPhrase(i, tokens)) { final String msg = "Außer am Satzanfang werden nur Nomen und Eigennamen großgeschrieben"; final RuleMatch ruleMatch = new RuleMatch(this, tokens[i].getStartPos(), tokens[i].getStartPos() + token.length(), msg); final String word = tokens[i].getToken(); final String fixedWord = Character.toLowerCase(word.charAt(0)) + word.substring(1); ruleMatch.setSuggestedReplacement(fixedWord); ruleMatches.add(ruleMatch); } } private boolean isExceptionPhrase(int i, AnalyzedTokenReadings[] tokens) { for (String exc : myExceptionPhrases) { final String[] parts = exc.split(" "); for (int j = 0; j < parts.length; j++) { if (parts[j].equals(tokens[i].getToken())) { final int startIndex = i-j; if (compareLists(tokens, startIndex, startIndex+parts.length-1, parts)) { return true; } } } } return false; } private boolean compareLists(AnalyzedTokenReadings[] tokens, int startIndex, int endIndex, String[] parts) { if (startIndex < 0) { return false; } int i = 0; for (int j = startIndex; j <= endIndex; j++) { if (i >= parts.length) { return false; } if (!tokens[j].getToken().equals(parts[i])) { return false; } i++; } return true; } @Override public void reset() { // nothing } }
6079_22
/* * Copyright 2013 Krzysztof Otrebski ([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 pl.otros.vfs.browser.util; import com.google.common.base.Joiner; import com.google.common.base.Throwables; import com.jcraft.jsch.JSchException; import jcifs.smb.SmbAuthException; import net.sf.vfsjfilechooser.utils.VFSURIParser; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.vfs2.*; import org.apache.commons.vfs2.UserAuthenticationData.Type; import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder; import org.apache.commons.vfs2.impl.StandardFileSystemManager; import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder; import org.apache.commons.vfs2.provider.http.HttpFileObject; import org.apache.commons.vfs2.provider.sftp.SftpFileObject; import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.otros.vfs.browser.Icons; import pl.otros.vfs.browser.LinkFileObject; import pl.otros.vfs.browser.TaskContext; import pl.otros.vfs.browser.auth.*; import javax.swing.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A helper class to deal with commons-vfs file abstractions * * @author Yves Zoundi <yveszoundi at users dot sf dot net> * @author Jojada Tirtowidjojo <jojada at users.sourceforge.net> * @author Stephan Schuster <stephanschuster at users.sourceforge.net> * @version 0.0.5 */ public final class VFSUtils { private static final int SYMBOLIC_LINK_MAX_SIZE = 128; private static final String OS_NAME = System.getProperty("os.name").toLowerCase(); private static final String PROTO_PREFIX = "://"; private static final String FILE_PREFIX = OS_NAME.startsWith("windows") ? "file:///" : "file://"; private static final int FILE_PREFIX_LEN = FILE_PREFIX.length(); private static final File HOME_DIRECTORY = new File(System.getProperty("user.home")); // public static final File CONFIG_DIRECTORY = new File(HOME_DIRECTORY, ".vfsjfilechooser"); public static final File CONFIG_DIRECTORY = new File(HOME_DIRECTORY, ".otrosvfsbrowser"); public static final File USER_AUTH_FILE = new File(CONFIG_DIRECTORY, "auth.xml"); public static final File USER_AUTH_FILE_BAK = new File(CONFIG_DIRECTORY, "auth.xml.bak"); private static final Logger LOGGER = LoggerFactory.getLogger(VFSUtils.class); private static final Map<String, Icon> schemeIconMap = new HashMap<String, Icon>(); private static final Set<String> archivesSuffixes = new HashSet<String>(); private static final ReadWriteLock aLock = new ReentrantReadWriteLock(true); private static final AuthStore sessionAuthStore = new MemoryAuthStore(); //TODO change to persistent auth store private static final AuthStore persistentAuthStore = new MemoryAuthStore(); private static final URIUtils URI_UTILS = new URIUtils(); // File size localized strings // private static members private static FileSystemManager fileSystemManager; private static AuthStoreUtils authStoreUtils; private static boolean authStoreLoaded = false; static { schemeIconMap.put("file", Icons.getInstance().getDrive()); schemeIconMap.put("sftp", Icons.getInstance().getNetworkCloud()); schemeIconMap.put("ftp", Icons.getInstance().getNetworkCloud()); schemeIconMap.put("smb", Icons.getInstance().getSambaShare()); schemeIconMap.put("http", Icons.getInstance().getNetworkCloud()); schemeIconMap.put("https", Icons.getInstance().getNetworkCloud()); schemeIconMap.put("zip", Icons.getInstance().getFolderZipper()); schemeIconMap.put("tar", Icons.getInstance().getFolderZipper()); schemeIconMap.put("jar", Icons.getInstance().getFolderZipper()); schemeIconMap.put("tgz", Icons.getInstance().getFolderZipper()); schemeIconMap.put("tbz", Icons.getInstance().getFolderZipper()); archivesSuffixes.add("zip"); archivesSuffixes.add("tar"); archivesSuffixes.add("jar"); archivesSuffixes.add("tgz"); archivesSuffixes.add("gz"); archivesSuffixes.add("tar"); archivesSuffixes.add("tbz"); archivesSuffixes.add("tgz"); //TODO fix this authStoreUtils = new AuthStoreUtils(new StaticPasswordProvider("Password".toCharArray())); } // prevent unnecessary calls private VFSUtils() { throw new AssertionError("Trying to create a VFSUtils object"); } /** * Returns the global filesystem manager * * @return the global filesystem manager */ public static FileSystemManager getFileSystemManager() { aLock.readLock().lock(); try { if (fileSystemManager == null) { try { StandardFileSystemManager fm = new StandardFileSystemManager(); fm.setCacheStrategy(CacheStrategy.MANUAL); fm.init(); LOGGER.info("Supported schemes: {} ", Joiner.on(", ").join(fm.getSchemes())); fileSystemManager = fm; } catch (Exception exc) { throw new RuntimeException(exc); } } return fileSystemManager; } finally { aLock.readLock().unlock(); } } // ----------------------------------------------------------------------- /** * Remove user credentials information * * @param fileName The file name * @return The "safe" display name without username and password information */ public static String getFriendlyName(String fileName) { return getFriendlyName(fileName, true); } public static String getFriendlyName(String fileName, boolean excludeLocalFilePrefix) { if (fileName == null) { return ""; } StringBuilder filePath = new StringBuilder(); int pos = fileName.lastIndexOf('@'); if (pos == -1) { filePath.append(fileName); } else { int pos2 = fileName.indexOf(PROTO_PREFIX); if (pos2 == -1) { filePath.append(fileName); } else { String protocol = fileName.substring(0, pos2); filePath.append(protocol).append(PROTO_PREFIX).append(fileName.substring(pos + 1)); } } String returnedString = filePath.toString(); if (excludeLocalFilePrefix && returnedString.startsWith(FILE_PREFIX)) { return filePath.substring(FILE_PREFIX_LEN); } return returnedString; } /** * Returns the root filesystem of a given file * * @param fileObject A file * @return the root filesystem of a given file */ public static FileObject createFileSystemRoot(FileObject fileObject) { try { return fileObject.getFileSystem().getRoot(); } catch (FileSystemException ex) { return null; } } /** * Returns all the files of a folder * * @param folder A folder * @return the files of a folder */ public static FileObject[] getFiles(FileObject folder) throws FileSystemException { return getChildren(folder); } /** * Returns the root file system of a file representation * * @param fileObject A file abstraction * @return the root file system of a file representation */ public static FileObject getRootFileSystem(FileObject fileObject) { try { if ((fileObject == null) || !fileObject.exists()) { return null; } return fileObject.getFileSystem().getRoot(); } catch (FileSystemException ex) { return null; } } /** * Tells whether a file is hidden * * @param fileObject a file representation * @return whether a file is hidden */ public static boolean isHiddenFile(FileObject fileObject) { try { return fileObject.getName().getBaseName().charAt(0) == '.'; } catch (Exception ex) { return false; } } /** * Tells whether a file is the root file system * * @param fileObject A file representation * @return whether a file is the root file system */ public static boolean isRoot(FileObject fileObject) { try { return fileObject.getParent() == null; } catch (FileSystemException ex) { return false; } } /** * Returns a file representation * * @param filePath The file path * @return a file representation * @throws FileSystemException */ public static FileObject resolveFileObject(String filePath) throws FileSystemException { LOGGER.info("Resolving file: {}", URI_UTILS.getFriendlyURI(filePath)); FileSystemOptions options = new FileSystemOptions(); if (filePath.startsWith("sftp://")) { SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance(); builder.setStrictHostKeyChecking(options, "no"); builder.setUserDirIsRoot(options, false); builder.setCompression(options, "zlib,none"); builder.setDisableDetectExecChannel(options, true); // see https://issues.apache.org/jira/browse/VFS-818 } else if (filePath.startsWith("smb://")) { } else if (filePath.startsWith("ftp://")) { FtpFileSystemConfigBuilder.getInstance().setPassiveMode(options, true); } //Getting user, password, keyfile or pageant auth information and set it. UserAuthenticatorFactory factory = new UserAuthenticatorFactory(); OtrosUserAuthenticator authenticator = factory.getUiUserAuthenticator(persistentAuthStore, sessionAuthStore, filePath, options); if (pathContainsCredentials(filePath)) { authenticator = null; } DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(options, authenticator); return resolveFileObject(filePath, options, null, persistentAuthStore, sessionAuthStore); } private static boolean pathContainsCredentials(String filePath) { VFSURIParser parser = new VFSURIParser(filePath); return StringUtils.isNotBlank(parser.getUsername()) && StringUtils.isNotBlank(parser.getPassword()); } public static FileObject resolveFileObject(URI uri) throws FileSystemException, MalformedURLException { return resolveFileObject(uri.toURL().toExternalForm()); } /** * Returns a file representation * * @param filePath The file path * @param options The filesystem options * @return a file representation * @throws FileSystemException */ private static FileObject resolveFileObject(String filePath, FileSystemOptions options, OtrosUserAuthenticator authenticator, AuthStore persistentAuthStore, AuthStore sessionAuthStore) throws FileSystemException { FileObject resolveFile; VFSURIParser parser = new VFSURIParser(filePath); //Get file type to force authentication try { resolveFile = getFileSystemManager().resolveFile(filePath, options); resolveFile.getType(); } catch (FileSystemException e) { LOGGER.error("Error resolving file " + URI_UTILS.getFriendlyURI(filePath), e); Throwable rootCause = Throwables.getRootCause(e); boolean authorizationFailed = checkForWrongCredentials(rootCause); if (authorizationFailed) { LOGGER.error("Wrong user name or password for " + filePath); //clear last data //authenticator can be null if user/password was entered in URL if (authenticator != null) { Optional.ofNullable(authenticator.getLastUserAuthenticationData()).ifPresent( lastUserAuthenticationData -> { lastUserAuthenticationData.remove(UserAuthenticationDataWrapper.PASSWORD); String user = new String(lastUserAuthenticationData.getData(UserAuthenticationData.USERNAME)); UserAuthenticationInfo auInfo = new UserAuthenticationInfo(parser.getProtocol().getName(), parser.getHostname(), user); sessionAuthStore.remove(auInfo); sessionAuthStore.add(auInfo, lastUserAuthenticationData); LOGGER.info("Removing password for {} on {}", new String(lastUserAuthenticationData.getData(UserAuthenticationData.USERNAME)), filePath); } ); } } throw e; } if (resolveFile != null && authenticator != null && authenticator.getLastUserAuthenticationData() != null) { UserAuthenticationDataWrapper lastUserAuthenticationData = authenticator.getLastUserAuthenticationData(); Map<Type, char[]> addedTypes = lastUserAuthenticationData.getAddedTypes(); String user = new String(addedTypes.get(UserAuthenticationData.USERNAME)); UserAuthenticationInfo auInfo = new UserAuthenticationInfo(parser.getProtocol().getName(), parser.getHostname(), user); sessionAuthStore.add(auInfo, lastUserAuthenticationData.copy()); if (authenticator.isPasswordSave()) { LOGGER.info("Saving password for {}://{}@{}", parser.getProtocol().getName(), user, parser.getHostname()); persistentAuthStore.add(auInfo, lastUserAuthenticationData); saveAuthStore(); } } return resolveFile; } public static boolean checkForWrongCredentials(Throwable exception) { if (exception.getCause() != null) { return checkForWrongCredentials(exception.getCause()); } else { String message = exception.getMessage(); return exception instanceof SmbAuthException && message.contains("The specified network password is not correct") || exception instanceof JSchException && message.contains("Auth fail"); } } /** * Returns a file representation * * @param folder A folder * @param filename A filename * @return a file contained in a given folder */ public static FileObject resolveFileObject(FileObject folder, String filename) { try { return folder.resolveFile(filename); } catch (FileSystemException ex) { return null; } } /** * Tells whether a file exists * * @param fileObject A file representation * @return whether a file exists */ public static boolean exists(FileObject fileObject) { if (fileObject == null) { return false; } try { return fileObject.exists(); } catch (FileSystemException ex) { return false; } } /** * y * * @param fileObject A file object representation * @return whether a file object is a directory */ public static boolean isDirectory(FileObject fileObject) { try { return fileObject.getType().equals(FileType.FOLDER); } catch (FileSystemException ex) { LOGGER.info("Exception when checking if fileobject is folder", ex); return false; } } /** * Returns whether a file object is a local file * * @param fileObject * @return true of {@link FileObject} is a local file */ public static boolean isLocalFile(FileObject fileObject) { try { return fileObject.getURL().getProtocol().equalsIgnoreCase("file") && FileType.FILE.equals(fileObject.getType()); } catch (FileSystemException e) { LOGGER.info("Exception when checking if fileobject is local file", e); return false; } } /** * Tells whether a folder is the root filesystem * * @param folder A folder * @return whether a folder is the root filesystem */ public static boolean isFileSystemRoot(FileObject folder) { return isRoot(folder); } /** * Returns whether a folder contains a given file * * @param folder A folder * @param file A file * @return whether a folder contains a given file */ public static boolean isParent(FileObject folder, FileObject file) { try { FileObject parent = file.getParent(); return parent != null && parent.equals(folder); } catch (FileSystemException ex) { return false; } } public static FileObject getUserHome() throws FileSystemException { return resolveFileObject(System.getProperty("user.home")); } public static void checkForSftpLinks(FileObject[] files, TaskContext taskContext) { LOGGER.debug("Checking for SFTP links"); taskContext.setMax(files.length); long ts = System.currentTimeMillis(); for (int i = 0; i < files.length && !taskContext.isStop(); i++) { FileObject fileObject = files[i]; try { if (fileObject instanceof SftpFileObject && FileType.FILE.equals(fileObject.getType())) { SftpFileObject sftpFileObject = (SftpFileObject) fileObject; long size = sftpFileObject.getContent().getSize(); if (size < SYMBOLIC_LINK_MAX_SIZE && size != 0) { if (!pointToItself(sftpFileObject)) { files[i] = new LinkFileObject(sftpFileObject); } } } } catch (Exception e) { //ignore } finally { taskContext.setCurrentProgress(i); } } long checkDuration = System.currentTimeMillis() - ts; LOGGER.info("Checking SFTP links took {} ms [{}ms/file]", checkDuration, (float) checkDuration / files.length); } public static boolean pointToItself(FileObject fileObject) throws FileSystemException { if (!fileObject.getURL().getProtocol().equalsIgnoreCase("file") && FileType.FILE.equals(fileObject.getType())) { LOGGER.debug("Checking if {} is pointing to itself", fileObject.getName().getFriendlyURI()); FileObject[] children = VFSUtils.getChildren(fileObject); LOGGER.debug("Children number of {} is {}", fileObject.getName().getFriendlyURI(), children.length); if (children.length == 1) { FileObject child = children[0]; if (child.getContent().getSize() != child.getContent().getSize()) { return false; } return child.getName().getBaseName().equals(fileObject.getName().getBaseName()); } } return false; } public static FileObject[] getChildren(FileObject fileObject) throws FileSystemException { FileObject[] result; final FileType type = fileObject.getType(); LOGGER.debug("fileType is {}", type); if (isHttpProtocol(fileObject)) { result = extractHttpFileObjectChildren(fileObject); } else if (isLocalFileSystem(fileObject) && isArchive(fileObject)) { String extension = fileObject.getName().getExtension(); result = VFSUtils.resolveFileObject(extension + ":" + fileObject.getURL().toString() + "!/").getChildren(); } else { result = fileObject.getChildren(); } return result; } public static boolean isArchive(FileObject fileObject) { return isArchive(fileObject.getName()); } public static boolean isArchive(FileName fileName) { String extension = fileName.getExtension(); return archivesSuffixes.contains(extension.toLowerCase()); } private static boolean isLocalFileSystem(FileObject fileObject) { return fileObject.getName().getScheme().equalsIgnoreCase("file"); } private static FileObject[] extractHttpFileObjectChildren(FileObject fileObject) throws FileSystemException { FileObject[] result; HttpFileObject fo = (HttpFileObject) fileObject; FileContent content = fo.getContent(); String contentType = content.getContentInfo().getContentType(); result = new FileObject[]{ fileObject }; if (contentType.equalsIgnoreCase("text/html")) { try { String html = IOUtils.toString(content.getInputStream()); if (html.toLowerCase().contains("index of")) { LOGGER.info("Page contains \"index of\", resolving children"); //a href="DSC_0410.JPG"> Pattern p = Pattern.compile("<A .*?href=\"(.*?)\"", Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(html); ArrayList<FileObject> list = new ArrayList<FileObject>(); while (matcher.find()) { String link = matcher.group(1); LOGGER.info("Getting children from link {}", link); if (StringUtils.isBlank(link)) { LOGGER.debug("URL link is blank"); continue; } FileObject child; URL url = fileObject.getURL(); child = extractHttpFileObject(link, url); list.add(child); } result = list.toArray(result); } //TODO extract links } catch (Exception e) { throw new FileSystemException(e); } } return result; } private static FileObject extractHttpFileObject(String link, URL url) throws FileSystemException, URISyntaxException { FileObject child; LOGGER.info("Extracting {} from URL {}", link, url); if (link.startsWith("/")) { URI uri = url.toURI(); String host = uri.getHost(); int port = uri.getPort(); if (port != -1) { child = resolveFileObject(String.format("%s://%s:%s%s", url.getProtocol(), host, port, link)); } else { child = resolveFileObject(String.format("%s://%s%s", url.getProtocol(), host, link)); } } else if (link.matches("(http|https|smb|ftp|sftp)://.*")) { child = resolveFileObject(link); } else { child = resolveFileObject(url + "/" + link); } return child; } public static Icon getIconForFileSystem(String url) { String schema = "file"; if (null != url) { int indexOf = url.indexOf("://"); if (indexOf > 0) { schema = url.substring(0, indexOf); } } return schemeIconMap.get(schema); } public static boolean isHttpProtocol(FileObject fileObject) throws FileSystemException { return fileObject != null && fileObject.getURL().getProtocol().startsWith("http"); } public static void loadAuthStore() { FileInputStream fin = null; if (!USER_AUTH_FILE.exists()) { return; } try { fin = new FileInputStream(USER_AUTH_FILE); authStoreUtils = new AuthStoreUtils(new StaticPasswordProvider("Password".toCharArray())); authStoreUtils.load(persistentAuthStore, fin); authStoreLoaded = true; } catch (IOException e) { LOGGER.error("Can't load auth store", e); } finally { IOUtils.closeQuietly(fin); } } public static void saveAuthStore() { FileOutputStream out = null; try { if (!CONFIG_DIRECTORY.exists()) { CONFIG_DIRECTORY.mkdirs(); } out = new FileOutputStream(USER_AUTH_FILE_BAK); authStoreUtils.save(persistentAuthStore, out); out.close(); FileUtils.copyFile(USER_AUTH_FILE_BAK, USER_AUTH_FILE); FileUtils.deleteQuietly(USER_AUTH_FILE_BAK); } catch (IOException e) { LOGGER.error("Can't save auth store", e); } finally { IOUtils.closeQuietly(out); } } public static boolean isAuthStoreLoaded() { return authStoreLoaded; } public static boolean canGoUrl(FileObject fileObject) { //http files try { if (!fileObject.getURL().getProtocol().startsWith("http") && VFSUtils.pointToItself(fileObject)) { return false; } } catch (FileSystemException e1) { LOGGER.error("Can't check if file is link", e1); } //Local files return !VFSUtils.isLocalFile(fileObject); } }
otros-systems/otroslogviewer
olv-vfs/src/main/java/pl/otros/vfs/browser/util/VFSUtils.java
6,997
//{}@{}", parser.getProtocol().getName(), user, parser.getHostname());
line_comment
nl
/* * Copyright 2013 Krzysztof Otrebski ([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 pl.otros.vfs.browser.util; import com.google.common.base.Joiner; import com.google.common.base.Throwables; import com.jcraft.jsch.JSchException; import jcifs.smb.SmbAuthException; import net.sf.vfsjfilechooser.utils.VFSURIParser; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.vfs2.*; import org.apache.commons.vfs2.UserAuthenticationData.Type; import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder; import org.apache.commons.vfs2.impl.StandardFileSystemManager; import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder; import org.apache.commons.vfs2.provider.http.HttpFileObject; import org.apache.commons.vfs2.provider.sftp.SftpFileObject; import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.otros.vfs.browser.Icons; import pl.otros.vfs.browser.LinkFileObject; import pl.otros.vfs.browser.TaskContext; import pl.otros.vfs.browser.auth.*; import javax.swing.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A helper class to deal with commons-vfs file abstractions * * @author Yves Zoundi <yveszoundi at users dot sf dot net> * @author Jojada Tirtowidjojo <jojada at users.sourceforge.net> * @author Stephan Schuster <stephanschuster at users.sourceforge.net> * @version 0.0.5 */ public final class VFSUtils { private static final int SYMBOLIC_LINK_MAX_SIZE = 128; private static final String OS_NAME = System.getProperty("os.name").toLowerCase(); private static final String PROTO_PREFIX = "://"; private static final String FILE_PREFIX = OS_NAME.startsWith("windows") ? "file:///" : "file://"; private static final int FILE_PREFIX_LEN = FILE_PREFIX.length(); private static final File HOME_DIRECTORY = new File(System.getProperty("user.home")); // public static final File CONFIG_DIRECTORY = new File(HOME_DIRECTORY, ".vfsjfilechooser"); public static final File CONFIG_DIRECTORY = new File(HOME_DIRECTORY, ".otrosvfsbrowser"); public static final File USER_AUTH_FILE = new File(CONFIG_DIRECTORY, "auth.xml"); public static final File USER_AUTH_FILE_BAK = new File(CONFIG_DIRECTORY, "auth.xml.bak"); private static final Logger LOGGER = LoggerFactory.getLogger(VFSUtils.class); private static final Map<String, Icon> schemeIconMap = new HashMap<String, Icon>(); private static final Set<String> archivesSuffixes = new HashSet<String>(); private static final ReadWriteLock aLock = new ReentrantReadWriteLock(true); private static final AuthStore sessionAuthStore = new MemoryAuthStore(); //TODO change to persistent auth store private static final AuthStore persistentAuthStore = new MemoryAuthStore(); private static final URIUtils URI_UTILS = new URIUtils(); // File size localized strings // private static members private static FileSystemManager fileSystemManager; private static AuthStoreUtils authStoreUtils; private static boolean authStoreLoaded = false; static { schemeIconMap.put("file", Icons.getInstance().getDrive()); schemeIconMap.put("sftp", Icons.getInstance().getNetworkCloud()); schemeIconMap.put("ftp", Icons.getInstance().getNetworkCloud()); schemeIconMap.put("smb", Icons.getInstance().getSambaShare()); schemeIconMap.put("http", Icons.getInstance().getNetworkCloud()); schemeIconMap.put("https", Icons.getInstance().getNetworkCloud()); schemeIconMap.put("zip", Icons.getInstance().getFolderZipper()); schemeIconMap.put("tar", Icons.getInstance().getFolderZipper()); schemeIconMap.put("jar", Icons.getInstance().getFolderZipper()); schemeIconMap.put("tgz", Icons.getInstance().getFolderZipper()); schemeIconMap.put("tbz", Icons.getInstance().getFolderZipper()); archivesSuffixes.add("zip"); archivesSuffixes.add("tar"); archivesSuffixes.add("jar"); archivesSuffixes.add("tgz"); archivesSuffixes.add("gz"); archivesSuffixes.add("tar"); archivesSuffixes.add("tbz"); archivesSuffixes.add("tgz"); //TODO fix this authStoreUtils = new AuthStoreUtils(new StaticPasswordProvider("Password".toCharArray())); } // prevent unnecessary calls private VFSUtils() { throw new AssertionError("Trying to create a VFSUtils object"); } /** * Returns the global filesystem manager * * @return the global filesystem manager */ public static FileSystemManager getFileSystemManager() { aLock.readLock().lock(); try { if (fileSystemManager == null) { try { StandardFileSystemManager fm = new StandardFileSystemManager(); fm.setCacheStrategy(CacheStrategy.MANUAL); fm.init(); LOGGER.info("Supported schemes: {} ", Joiner.on(", ").join(fm.getSchemes())); fileSystemManager = fm; } catch (Exception exc) { throw new RuntimeException(exc); } } return fileSystemManager; } finally { aLock.readLock().unlock(); } } // ----------------------------------------------------------------------- /** * Remove user credentials information * * @param fileName The file name * @return The "safe" display name without username and password information */ public static String getFriendlyName(String fileName) { return getFriendlyName(fileName, true); } public static String getFriendlyName(String fileName, boolean excludeLocalFilePrefix) { if (fileName == null) { return ""; } StringBuilder filePath = new StringBuilder(); int pos = fileName.lastIndexOf('@'); if (pos == -1) { filePath.append(fileName); } else { int pos2 = fileName.indexOf(PROTO_PREFIX); if (pos2 == -1) { filePath.append(fileName); } else { String protocol = fileName.substring(0, pos2); filePath.append(protocol).append(PROTO_PREFIX).append(fileName.substring(pos + 1)); } } String returnedString = filePath.toString(); if (excludeLocalFilePrefix && returnedString.startsWith(FILE_PREFIX)) { return filePath.substring(FILE_PREFIX_LEN); } return returnedString; } /** * Returns the root filesystem of a given file * * @param fileObject A file * @return the root filesystem of a given file */ public static FileObject createFileSystemRoot(FileObject fileObject) { try { return fileObject.getFileSystem().getRoot(); } catch (FileSystemException ex) { return null; } } /** * Returns all the files of a folder * * @param folder A folder * @return the files of a folder */ public static FileObject[] getFiles(FileObject folder) throws FileSystemException { return getChildren(folder); } /** * Returns the root file system of a file representation * * @param fileObject A file abstraction * @return the root file system of a file representation */ public static FileObject getRootFileSystem(FileObject fileObject) { try { if ((fileObject == null) || !fileObject.exists()) { return null; } return fileObject.getFileSystem().getRoot(); } catch (FileSystemException ex) { return null; } } /** * Tells whether a file is hidden * * @param fileObject a file representation * @return whether a file is hidden */ public static boolean isHiddenFile(FileObject fileObject) { try { return fileObject.getName().getBaseName().charAt(0) == '.'; } catch (Exception ex) { return false; } } /** * Tells whether a file is the root file system * * @param fileObject A file representation * @return whether a file is the root file system */ public static boolean isRoot(FileObject fileObject) { try { return fileObject.getParent() == null; } catch (FileSystemException ex) { return false; } } /** * Returns a file representation * * @param filePath The file path * @return a file representation * @throws FileSystemException */ public static FileObject resolveFileObject(String filePath) throws FileSystemException { LOGGER.info("Resolving file: {}", URI_UTILS.getFriendlyURI(filePath)); FileSystemOptions options = new FileSystemOptions(); if (filePath.startsWith("sftp://")) { SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance(); builder.setStrictHostKeyChecking(options, "no"); builder.setUserDirIsRoot(options, false); builder.setCompression(options, "zlib,none"); builder.setDisableDetectExecChannel(options, true); // see https://issues.apache.org/jira/browse/VFS-818 } else if (filePath.startsWith("smb://")) { } else if (filePath.startsWith("ftp://")) { FtpFileSystemConfigBuilder.getInstance().setPassiveMode(options, true); } //Getting user, password, keyfile or pageant auth information and set it. UserAuthenticatorFactory factory = new UserAuthenticatorFactory(); OtrosUserAuthenticator authenticator = factory.getUiUserAuthenticator(persistentAuthStore, sessionAuthStore, filePath, options); if (pathContainsCredentials(filePath)) { authenticator = null; } DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(options, authenticator); return resolveFileObject(filePath, options, null, persistentAuthStore, sessionAuthStore); } private static boolean pathContainsCredentials(String filePath) { VFSURIParser parser = new VFSURIParser(filePath); return StringUtils.isNotBlank(parser.getUsername()) && StringUtils.isNotBlank(parser.getPassword()); } public static FileObject resolveFileObject(URI uri) throws FileSystemException, MalformedURLException { return resolveFileObject(uri.toURL().toExternalForm()); } /** * Returns a file representation * * @param filePath The file path * @param options The filesystem options * @return a file representation * @throws FileSystemException */ private static FileObject resolveFileObject(String filePath, FileSystemOptions options, OtrosUserAuthenticator authenticator, AuthStore persistentAuthStore, AuthStore sessionAuthStore) throws FileSystemException { FileObject resolveFile; VFSURIParser parser = new VFSURIParser(filePath); //Get file type to force authentication try { resolveFile = getFileSystemManager().resolveFile(filePath, options); resolveFile.getType(); } catch (FileSystemException e) { LOGGER.error("Error resolving file " + URI_UTILS.getFriendlyURI(filePath), e); Throwable rootCause = Throwables.getRootCause(e); boolean authorizationFailed = checkForWrongCredentials(rootCause); if (authorizationFailed) { LOGGER.error("Wrong user name or password for " + filePath); //clear last data //authenticator can be null if user/password was entered in URL if (authenticator != null) { Optional.ofNullable(authenticator.getLastUserAuthenticationData()).ifPresent( lastUserAuthenticationData -> { lastUserAuthenticationData.remove(UserAuthenticationDataWrapper.PASSWORD); String user = new String(lastUserAuthenticationData.getData(UserAuthenticationData.USERNAME)); UserAuthenticationInfo auInfo = new UserAuthenticationInfo(parser.getProtocol().getName(), parser.getHostname(), user); sessionAuthStore.remove(auInfo); sessionAuthStore.add(auInfo, lastUserAuthenticationData); LOGGER.info("Removing password for {} on {}", new String(lastUserAuthenticationData.getData(UserAuthenticationData.USERNAME)), filePath); } ); } } throw e; } if (resolveFile != null && authenticator != null && authenticator.getLastUserAuthenticationData() != null) { UserAuthenticationDataWrapper lastUserAuthenticationData = authenticator.getLastUserAuthenticationData(); Map<Type, char[]> addedTypes = lastUserAuthenticationData.getAddedTypes(); String user = new String(addedTypes.get(UserAuthenticationData.USERNAME)); UserAuthenticationInfo auInfo = new UserAuthenticationInfo(parser.getProtocol().getName(), parser.getHostname(), user); sessionAuthStore.add(auInfo, lastUserAuthenticationData.copy()); if (authenticator.isPasswordSave()) { LOGGER.info("Saving password for {}://{}@{}", parser.getProtocol().getName(),<SUF> persistentAuthStore.add(auInfo, lastUserAuthenticationData); saveAuthStore(); } } return resolveFile; } public static boolean checkForWrongCredentials(Throwable exception) { if (exception.getCause() != null) { return checkForWrongCredentials(exception.getCause()); } else { String message = exception.getMessage(); return exception instanceof SmbAuthException && message.contains("The specified network password is not correct") || exception instanceof JSchException && message.contains("Auth fail"); } } /** * Returns a file representation * * @param folder A folder * @param filename A filename * @return a file contained in a given folder */ public static FileObject resolveFileObject(FileObject folder, String filename) { try { return folder.resolveFile(filename); } catch (FileSystemException ex) { return null; } } /** * Tells whether a file exists * * @param fileObject A file representation * @return whether a file exists */ public static boolean exists(FileObject fileObject) { if (fileObject == null) { return false; } try { return fileObject.exists(); } catch (FileSystemException ex) { return false; } } /** * y * * @param fileObject A file object representation * @return whether a file object is a directory */ public static boolean isDirectory(FileObject fileObject) { try { return fileObject.getType().equals(FileType.FOLDER); } catch (FileSystemException ex) { LOGGER.info("Exception when checking if fileobject is folder", ex); return false; } } /** * Returns whether a file object is a local file * * @param fileObject * @return true of {@link FileObject} is a local file */ public static boolean isLocalFile(FileObject fileObject) { try { return fileObject.getURL().getProtocol().equalsIgnoreCase("file") && FileType.FILE.equals(fileObject.getType()); } catch (FileSystemException e) { LOGGER.info("Exception when checking if fileobject is local file", e); return false; } } /** * Tells whether a folder is the root filesystem * * @param folder A folder * @return whether a folder is the root filesystem */ public static boolean isFileSystemRoot(FileObject folder) { return isRoot(folder); } /** * Returns whether a folder contains a given file * * @param folder A folder * @param file A file * @return whether a folder contains a given file */ public static boolean isParent(FileObject folder, FileObject file) { try { FileObject parent = file.getParent(); return parent != null && parent.equals(folder); } catch (FileSystemException ex) { return false; } } public static FileObject getUserHome() throws FileSystemException { return resolveFileObject(System.getProperty("user.home")); } public static void checkForSftpLinks(FileObject[] files, TaskContext taskContext) { LOGGER.debug("Checking for SFTP links"); taskContext.setMax(files.length); long ts = System.currentTimeMillis(); for (int i = 0; i < files.length && !taskContext.isStop(); i++) { FileObject fileObject = files[i]; try { if (fileObject instanceof SftpFileObject && FileType.FILE.equals(fileObject.getType())) { SftpFileObject sftpFileObject = (SftpFileObject) fileObject; long size = sftpFileObject.getContent().getSize(); if (size < SYMBOLIC_LINK_MAX_SIZE && size != 0) { if (!pointToItself(sftpFileObject)) { files[i] = new LinkFileObject(sftpFileObject); } } } } catch (Exception e) { //ignore } finally { taskContext.setCurrentProgress(i); } } long checkDuration = System.currentTimeMillis() - ts; LOGGER.info("Checking SFTP links took {} ms [{}ms/file]", checkDuration, (float) checkDuration / files.length); } public static boolean pointToItself(FileObject fileObject) throws FileSystemException { if (!fileObject.getURL().getProtocol().equalsIgnoreCase("file") && FileType.FILE.equals(fileObject.getType())) { LOGGER.debug("Checking if {} is pointing to itself", fileObject.getName().getFriendlyURI()); FileObject[] children = VFSUtils.getChildren(fileObject); LOGGER.debug("Children number of {} is {}", fileObject.getName().getFriendlyURI(), children.length); if (children.length == 1) { FileObject child = children[0]; if (child.getContent().getSize() != child.getContent().getSize()) { return false; } return child.getName().getBaseName().equals(fileObject.getName().getBaseName()); } } return false; } public static FileObject[] getChildren(FileObject fileObject) throws FileSystemException { FileObject[] result; final FileType type = fileObject.getType(); LOGGER.debug("fileType is {}", type); if (isHttpProtocol(fileObject)) { result = extractHttpFileObjectChildren(fileObject); } else if (isLocalFileSystem(fileObject) && isArchive(fileObject)) { String extension = fileObject.getName().getExtension(); result = VFSUtils.resolveFileObject(extension + ":" + fileObject.getURL().toString() + "!/").getChildren(); } else { result = fileObject.getChildren(); } return result; } public static boolean isArchive(FileObject fileObject) { return isArchive(fileObject.getName()); } public static boolean isArchive(FileName fileName) { String extension = fileName.getExtension(); return archivesSuffixes.contains(extension.toLowerCase()); } private static boolean isLocalFileSystem(FileObject fileObject) { return fileObject.getName().getScheme().equalsIgnoreCase("file"); } private static FileObject[] extractHttpFileObjectChildren(FileObject fileObject) throws FileSystemException { FileObject[] result; HttpFileObject fo = (HttpFileObject) fileObject; FileContent content = fo.getContent(); String contentType = content.getContentInfo().getContentType(); result = new FileObject[]{ fileObject }; if (contentType.equalsIgnoreCase("text/html")) { try { String html = IOUtils.toString(content.getInputStream()); if (html.toLowerCase().contains("index of")) { LOGGER.info("Page contains \"index of\", resolving children"); //a href="DSC_0410.JPG"> Pattern p = Pattern.compile("<A .*?href=\"(.*?)\"", Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(html); ArrayList<FileObject> list = new ArrayList<FileObject>(); while (matcher.find()) { String link = matcher.group(1); LOGGER.info("Getting children from link {}", link); if (StringUtils.isBlank(link)) { LOGGER.debug("URL link is blank"); continue; } FileObject child; URL url = fileObject.getURL(); child = extractHttpFileObject(link, url); list.add(child); } result = list.toArray(result); } //TODO extract links } catch (Exception e) { throw new FileSystemException(e); } } return result; } private static FileObject extractHttpFileObject(String link, URL url) throws FileSystemException, URISyntaxException { FileObject child; LOGGER.info("Extracting {} from URL {}", link, url); if (link.startsWith("/")) { URI uri = url.toURI(); String host = uri.getHost(); int port = uri.getPort(); if (port != -1) { child = resolveFileObject(String.format("%s://%s:%s%s", url.getProtocol(), host, port, link)); } else { child = resolveFileObject(String.format("%s://%s%s", url.getProtocol(), host, link)); } } else if (link.matches("(http|https|smb|ftp|sftp)://.*")) { child = resolveFileObject(link); } else { child = resolveFileObject(url + "/" + link); } return child; } public static Icon getIconForFileSystem(String url) { String schema = "file"; if (null != url) { int indexOf = url.indexOf("://"); if (indexOf > 0) { schema = url.substring(0, indexOf); } } return schemeIconMap.get(schema); } public static boolean isHttpProtocol(FileObject fileObject) throws FileSystemException { return fileObject != null && fileObject.getURL().getProtocol().startsWith("http"); } public static void loadAuthStore() { FileInputStream fin = null; if (!USER_AUTH_FILE.exists()) { return; } try { fin = new FileInputStream(USER_AUTH_FILE); authStoreUtils = new AuthStoreUtils(new StaticPasswordProvider("Password".toCharArray())); authStoreUtils.load(persistentAuthStore, fin); authStoreLoaded = true; } catch (IOException e) { LOGGER.error("Can't load auth store", e); } finally { IOUtils.closeQuietly(fin); } } public static void saveAuthStore() { FileOutputStream out = null; try { if (!CONFIG_DIRECTORY.exists()) { CONFIG_DIRECTORY.mkdirs(); } out = new FileOutputStream(USER_AUTH_FILE_BAK); authStoreUtils.save(persistentAuthStore, out); out.close(); FileUtils.copyFile(USER_AUTH_FILE_BAK, USER_AUTH_FILE); FileUtils.deleteQuietly(USER_AUTH_FILE_BAK); } catch (IOException e) { LOGGER.error("Can't save auth store", e); } finally { IOUtils.closeQuietly(out); } } public static boolean isAuthStoreLoaded() { return authStoreLoaded; } public static boolean canGoUrl(FileObject fileObject) { //http files try { if (!fileObject.getURL().getProtocol().startsWith("http") && VFSUtils.pointToItself(fileObject)) { return false; } } catch (FileSystemException e1) { LOGGER.error("Can't check if file is link", e1); } //Local files return !VFSUtils.isLocalFile(fileObject); } }
68792_129
/*=========================================================================== BASS_FX 2.4 - Copyright (c) 2002-2018 (: JOBnik! :) [Arthur Aminov, ISRAEL] [http://www.jobnik.org] bugs/suggestions/questions: forum : http://www.un4seen.com/forum/?board=1 http://www.jobnik.org/forums e-mail : [email protected] -------------------------------------------------- NOTE: This header will work only with BASS_FX version 2.4.12 Check www.un4seen.com or www.jobnik.org for any later versions. * Requires BASS 2.4 (available at http://www.un4seen.com) ===========================================================================*/ package com.un4seen.bass; public class BASS_FX { // BASS_CHANNELINFO types public static final int BASS_CTYPE_STREAM_TEMPO = 0x1f200; public static final int BASS_CTYPE_STREAM_REVERSE = 0x1f201; // Tempo / Reverse / BPM / Beat flag public static final int BASS_FX_FREESOURCE = 0x10000; // Free the source handle as well? // BASS_FX Version public static native int BASS_FX_GetVersion(); /*=========================================================================== DSP (Digital Signal Processing) ===========================================================================*/ /* Multi-channel order of each channel is as follows: 3 channels left-front, right-front, center. 4 channels left-front, right-front, left-rear/side, right-rear/side. 5 channels left-front, right-front, center, left-rear/side, right-rear/side. 6 channels (5.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side. 8 channels (7.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side, left-rear center, right-rear center. */ // DSP channels flags public static final int BASS_BFX_CHANALL = -1; // all channels at once (as by default) public static final int BASS_BFX_CHANNONE = 0; // disable an effect for all channels public static final int BASS_BFX_CHAN1 = 1; // left-front channel public static final int BASS_BFX_CHAN2 = 2; // right-front channel public static final int BASS_BFX_CHAN3 = 4; // see above info public static final int BASS_BFX_CHAN4 = 8; // see above info public static final int BASS_BFX_CHAN5 = 16; // see above info public static final int BASS_BFX_CHAN6 = 32; // see above info public static final int BASS_BFX_CHAN7 = 64; // see above info public static final int BASS_BFX_CHAN8 = 128; // see above info // if you have more than 8 channels (7.1), use this function public static int BASS_BFX_CHANNEL_N(int n) { return (1<<((n)-1)); } // DSP effects public static final int BASS_FX_BFX_ROTATE = 0x10000; // A channels volume ping-pong / multi channel public static final int BASS_FX_BFX_ECHO = 0x10001; // Echo / 2 channels max (deprecated) public static final int BASS_FX_BFX_FLANGER = 0x10002; // Flanger / multi channel (deprecated) public static final int BASS_FX_BFX_VOLUME = 0x10003; // Volume / multi channel public static final int BASS_FX_BFX_PEAKEQ = 0x10004; // Peaking Equalizer / multi channel public static final int BASS_FX_BFX_REVERB = 0x10005; // Reverb / 2 channels max (deprecated) public static final int BASS_FX_BFX_LPF = 0x10006; // Low Pass Filter 24dB / multi channel (deprecated) public static final int BASS_FX_BFX_MIX = 0x10007; // Swap, remap and mix channels / multi channel public static final int BASS_FX_BFX_DAMP = 0x10008; // Dynamic Amplification / multi channel public static final int BASS_FX_BFX_AUTOWAH = 0x10009; // Auto Wah / multi channel public static final int BASS_FX_BFX_ECHO2 = 0x1000a; // Echo 2 / multi channel (deprecated) public static final int BASS_FX_BFX_PHASER = 0x1000b; // Phaser / multi channel public static final int BASS_FX_BFX_ECHO3 = 0x1000c; // Echo 3 / multi channel (deprecated) public static final int BASS_FX_BFX_CHORUS = 0x1000d; // Chorus/Flanger / multi channel public static final int BASS_FX_BFX_APF = 0x1000e; // All Pass Filter / multi channel (deprecated) public static final int BASS_FX_BFX_COMPRESSOR = 0x1000f; // Compressor / multi channel (deprecated) public static final int BASS_FX_BFX_DISTORTION = 0x10010; // Distortion / multi channel public static final int BASS_FX_BFX_COMPRESSOR2 = 0x10011; // Compressor 2 / multi channel public static final int BASS_FX_BFX_VOLUME_ENV = 0x10012; // Volume envelope / multi channel public static final int BASS_FX_BFX_BQF = 0x10013; // BiQuad filters / multi channel public static final int BASS_FX_BFX_ECHO4 = 0x10014; // Echo 4 / multi channel public static final int BASS_FX_BFX_PITCHSHIFT = 0x10015; // Pitch shift using FFT / multi channel (not available on mobile) public static final int BASS_FX_BFX_FREEVERB = 0x10016; // Reverb using "Freeverb" algo / multi channel /* Deprecated effects in 2.4.10 version: ------------------------------------ BASS_FX_BFX_ECHO -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_ECHO2 -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_ECHO3 -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_REVERB -> use BASS_FX_BFX_FREEVERB BASS_FX_BFX_FLANGER -> use BASS_FX_BFX_CHORUS BASS_FX_BFX_COMPRESSOR -> use BASS_FX_BFX_COMPRESSOR2 BASS_FX_BFX_APF -> use BASS_FX_BFX_BQF with BASS_BFX_BQF_ALLPASS filter BASS_FX_BFX_LPF -> use 2x BASS_FX_BFX_BQF with BASS_BFX_BQF_LOWPASS filter and appropriate fQ values */ // Rotate public static class BASS_BFX_ROTATE { public float fRate; // rotation rate/speed in Hz (A negative rate can be used for reverse direction) public int lChannel; // BASS_BFX_CHANxxx flag/s (supported only even number of channels) } // Echo (deprecated) public static class BASS_BFX_ECHO { public float fLevel; // [0....1....n] linear public int lDelay; // [1200..30000] } // Flanger (deprecated) public static class BASS_BFX_FLANGER { public float fWetDry; // [0....1....n] linear public float fSpeed; // [0......0.09] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Volume public static class BASS_BFX_VOLUME { public int lChannel; // BASS_BFX_CHANxxx flag/s or 0 for global volume control public float fVolume; // [0....1....n] linear } // Peaking Equalizer public static class BASS_BFX_PEAKEQ { public int lBand; // [0...............n] more bands means more memory & cpu usage public float fBandwidth; // [0.1...........<10] in octaves - fQ is not in use (Bandwidth has a priority over fQ) public float fQ; // [0...............1] the EE kinda definition (linear) (if Bandwidth is not in use) public float fCenter; // [1Hz..<info.freq/2] in Hz public float fGain; // [-15dB...0...+15dB] in dB (can be above/below these limits) public int lChannel; // BASS_BFX_CHANxxx flag/s } // Reverb (deprecated) public static class BASS_BFX_REVERB { public float fLevel; // [0....1....n] linear public int lDelay; // [1200..10000] } // Low Pass Filter (deprecated) public static class BASS_BFX_LPF { public float fResonance; // [0.01...........10] public float fCutOffFreq; // [1Hz...info.freq/2] cutoff frequency public int lChannel; // BASS_BFX_CHANxxx flag/s } // Swap, remap and mix public static class BASS_BFX_MIX { public int[] lChannel; // an array of channels to mix using BASS_BFX_CHANxxx flag/s (lChannel[0] is left channel...) } // Dynamic Amplification public static class BASS_BFX_DAMP { public float fTarget; // target volume level [0<......1] linear public float fQuiet; // quiet volume level [0.......1] linear public float fRate; // amp adjustment rate [0.......1] linear public float fGain; // amplification level [0...1...n] linear public float fDelay; // delay in seconds before increasing level [0.......n] linear public int lChannel; // BASS_BFX_CHANxxx flag/s } // Auto Wah public static class BASS_BFX_AUTOWAH { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fRate; // rate of sweep in cycles per second [0<....<10] public float fRange; // sweep range in octaves [0<....<10] public float fFreq; // base frequency of sweep Hz [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 2 (deprecated) public static class BASS_BFX_ECHO2 { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fDelay; // delay sec [0<......n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Phaser public static class BASS_BFX_PHASER { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fRate; // rate of sweep in cycles per second [0<....<10] public float fRange; // sweep range in octaves [0<....<10] public float fFreq; // base frequency of sweep [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 3 (deprecated) public static class BASS_BFX_ECHO3 { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fDelay; // delay sec [0<......n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Chorus/Flanger public static class BASS_BFX_CHORUS { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fMinSweep; // minimal delay ms [0<...6000] public float fMaxSweep; // maximum delay ms [0<...6000] public float fRate; // rate ms/s [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // All Pass Filter (deprecated) public static class BASS_BFX_APF { public float fGain; // reverberation time [-1=<..<=1] public float fDelay; // delay sec [0<....<=n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Compressor (deprecated) public static class BASS_BFX_COMPRESSOR { public float fThreshold; // compressor threshold [0<=...<=1] public float fAttacktime; // attack time ms [0<.<=1000] public float fReleasetime; // release time ms [0<.<=5000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Distortion public static class BASS_BFX_DISTORTION { public float fDrive; // distortion drive [0<=...<=5] public float fDryMix; // dry (unaffected) signal mix [-5<=..<=5] public float fWetMix; // wet (affected) signal mix [-5<=..<=5] public float fFeedback; // output signal to feed back into input [-1<=..<=1] public float fVolume; // distortion volume [0=<...<=2] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Compressor 2 public static class BASS_BFX_COMPRESSOR2 { public float fGain; // output gain of signal after compression [-60....60] in dB public float fThreshold; // point at which compression begins [-60.....0] in dB public float fRatio; // compression ratio [1.......n] public float fAttack; // attack time in ms [0.01.1000] public float fRelease; // release time in ms [0.01.5000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Volume envelope public static class BASS_BFX_VOLUME_ENV { public int lChannel; // BASS_BFX_CHANxxx flag/s public int lNodeCount; // number of nodes public BASS_BFX_ENV_NODE[] pNodes; // the nodes public boolean bFollow; // follow source position } public static class BASS_BFX_ENV_NODE { public double pos; // node position in seconds (1st envelope node must be at position 0) public float val; // node value } // BiQuad Filters public static final int BASS_BFX_BQF_LOWPASS = 0; public static final int BASS_BFX_BQF_HIGHPASS = 1; public static final int BASS_BFX_BQF_BANDPASS = 2; // constant 0 dB peak gain public static final int BASS_BFX_BQF_BANDPASS_Q = 3; // constant skirt gain, peak gain = Q public static final int BASS_BFX_BQF_NOTCH = 4; public static final int BASS_BFX_BQF_ALLPASS = 5; public static final int BASS_BFX_BQF_PEAKINGEQ = 6; public static final int BASS_BFX_BQF_LOWSHELF = 7; public static final int BASS_BFX_BQF_HIGHSHELF = 8; public static class BASS_BFX_BQF { public int lFilter; // BASS_BFX_BQF_xxx filter types public float fCenter; // [1Hz..<info.freq/2] Cutoff (central) frequency in Hz public float fGain; // [-15dB...0...+15dB] Used only for PEAKINGEQ and Shelving filters in dB (can be above/below these limits) public float fBandwidth; // [0.1...........<10] Bandwidth in octaves (fQ is not in use (fBandwidth has a priority over fQ)) // (between -3 dB frequencies for BANDPASS and NOTCH or between midpoint // (fGgain/2) gain frequencies for PEAKINGEQ) public float fQ; // [0.1.............1] The EE kinda definition (linear) (if fBandwidth is not in use) public float fS; // [0.1.............1] A "shelf slope" parameter (linear) (used only with Shelving filters) // when fS = 1, the shelf slope is as steep as you can get it and remain monotonically // increasing or decreasing gain with frequency. public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 4 public static class BASS_BFX_ECHO4 { public float fDryMix; // dry (unaffected) signal mix [-2.......2] public float fWetMix; // wet (affected) signal mix [-2.......2] public float fFeedback; // output signal to feed back into input [-1.......1] public float fDelay; // delay sec [0<.......n] public boolean bStereo; // echo adjoining channels to each other [TRUE/FALSE] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Pitch shift (not available on mobile) public static class BASS_BFX_PITCHSHIFT { public float fPitchShift; // A factor value which is between 0.5 (one octave down) and 2 (one octave up) (1 won't change the pitch) [1 default] // (fSemitones is not in use, fPitchShift has a priority over fSemitones) public float fSemitones; // Semitones (0 won't change the pitch) [0 default] public int lFFTsize; // Defines the FFT frame size used for the processing. Typical values are 1024, 2048 and 4096 [2048 default] // It may be any value <= 8192 but it MUST be a power of 2 public int lOsamp; // Is the STFT oversampling factor which also determines the overlap between adjacent STFT frames [8 default] // It should at least be 4 for moderate scaling ratios. A value of 32 is recommended for best quality (better quality = higher CPU usage) public int lChannel; // BASS_BFX_CHANxxx flag/s } // Freeverb public static final int BASS_BFX_FREEVERB_MODE_FREEZE = 1; public static class BASS_BFX_FREEVERB { public float fDryMix; // dry (unaffected) signal mix [0........1], def. 0 public float fWetMix; // wet (affected) signal mix [0........3], def. 1.0f public float fRoomSize; // room size [0........1], def. 0.5f public float fDamp; // damping [0........1], def. 0.5f public float fWidth; // stereo width [0........1], def. 1 public int lMode; // 0 or BASS_BFX_FREEVERB_MODE_FREEZE, def. 0 (no freeze) public int lChannel; // BASS_BFX_CHANxxx flag/s } /*=========================================================================== set dsp fx - BASS_ChannelSetFX remove dsp fx - BASS_ChannelRemoveFX set parameters - BASS_FXSetParameters retrieve parameters - BASS_FXGetParameters reset the state - BASS_FXReset ===========================================================================*/ /*=========================================================================== Tempo, Pitch scaling and Sample rate changers ===========================================================================*/ // NOTE: Enable Tempo supported flags in BASS_FX_TempoCreate and the others to source handle. // tempo attributes (BASS_ChannelSet/GetAttribute) public static final int BASS_ATTRIB_TEMPO = 0x10000; public static final int BASS_ATTRIB_TEMPO_PITCH = 0x10001; public static final int BASS_ATTRIB_TEMPO_FREQ = 0x10002; // tempo attributes options public static final int BASS_ATTRIB_TEMPO_OPTION_USE_AA_FILTER = 0x10010; // TRUE (default) / FALSE (default for multi-channel on mobile devices for lower CPU usage) public static final int BASS_ATTRIB_TEMPO_OPTION_AA_FILTER_LENGTH = 0x10011; // 32 default (8 .. 128 taps) public static final int BASS_ATTRIB_TEMPO_OPTION_USE_QUICKALGO = 0x10012; // TRUE (default on mobile devices for lower CPU usage) / FALSE (default) public static final int BASS_ATTRIB_TEMPO_OPTION_SEQUENCE_MS = 0x10013; // 82 default, 0 = automatic public static final int BASS_ATTRIB_TEMPO_OPTION_SEEKWINDOW_MS = 0x10014; // 28 default, 0 = automatic public static final int BASS_ATTRIB_TEMPO_OPTION_OVERLAP_MS = 0x10015; // 8 default public static final int BASS_ATTRIB_TEMPO_OPTION_PREVENT_CLICK = 0x10016; // TRUE / FALSE (default) // tempo algorithm flags public static final int BASS_FX_TEMPO_ALGO_LINEAR = 0x200; public static final int BASS_FX_TEMPO_ALGO_CUBIC = 0x400; // default public static final int BASS_FX_TEMPO_ALGO_SHANNON = 0x800; public static native int BASS_FX_TempoCreate(int chan, int flags); public static native int BASS_FX_TempoGetSource(int chan); public static native float BASS_FX_TempoGetRateRatio(int chan); /*=========================================================================== Reverse playback ===========================================================================*/ // NOTES: 1. MODs won't load without BASS_MUSIC_PRESCAN flag. // 2. Enable Reverse supported flags in BASS_FX_ReverseCreate and the others to source handle. // reverse attribute (BASS_ChannelSet/GetAttribute) public static final int BASS_ATTRIB_REVERSE_DIR = 0x11000; // playback directions public static final int BASS_FX_RVS_REVERSE = -1; public static final int BASS_FX_RVS_FORWARD = 1; public static native int BASS_FX_ReverseCreate(int chan, float dec_block, int flags); public static native int BASS_FX_ReverseGetSource(int chan); /*=========================================================================== BPM (Beats Per Minute) ===========================================================================*/ // bpm flags public static final int BASS_FX_BPM_BKGRND = 1; // if in use, then you can do other processing while detection's in progress. Available only in Windows platforms (BPM/Beat) public static final int BASS_FX_BPM_MULT2 = 2; // if in use, then will auto multiply bpm by 2 (if BPM < minBPM*2) // translation options (deprecated) public static final int BASS_FX_BPM_TRAN_X2 = 0; // multiply the original BPM value by 2 (may be called only once & will change the original BPM as well!) public static final int BASS_FX_BPM_TRAN_2FREQ = 1; // BPM value to Frequency public static final int BASS_FX_BPM_TRAN_FREQ2 = 2; // Frequency to BPM value public static final int BASS_FX_BPM_TRAN_2PERCENT = 3; // BPM value to Percents public static final int BASS_FX_BPM_TRAN_PERCENT2 = 4; // Percents to BPM value public interface BPMPROC { void BPMPROC(int chan, float bpm, Object user); } public interface BPMPROGRESSPROC { void BPMPROGRESSPROC(int chan, float percent, Object user); } // back-compatibility public interface BPMPROCESSPROC { void BPMPROCESSPROC(int chan, float percent, Object user); } public static native float BASS_FX_BPM_DecodeGet(int chan, double startSec, double endSec, int minMaxBPM, int flags, Object proc, Object user); public static native boolean BASS_FX_BPM_CallbackSet(int handle, BPMPROC proc, double period, int minMaxBPM, int flags, Object user); public static native boolean BASS_FX_BPM_CallbackReset(int handle); public static native float BASS_FX_BPM_Translate(int handle, float val2tran, int trans); // deprecated public static native boolean BASS_FX_BPM_Free(int handle); /*=========================================================================== Beat position trigger ===========================================================================*/ public interface BPMBEATPROC { void BPMBEATPROC(int chan, double beatpos, Object user); } public static native boolean BASS_FX_BPM_BeatCallbackSet(int handle, BPMBEATPROC proc, Object user); public static native boolean BASS_FX_BPM_BeatCallbackReset(int handle); public static native boolean BASS_FX_BPM_BeatDecodeGet(int chan, double startSec, double endSec, int flags, BPMBEATPROC proc, Object user); public static native boolean BASS_FX_BPM_BeatSetParameters(int handle, float bandwidth, float centerfreq, float beat_rtime); public static native boolean BASS_FX_BPM_BeatGetParameters(int handle, Float bandwidth, Float centerfreq, Float beat_rtime); public static native boolean BASS_FX_BPM_BeatFree(int handle); /*=========================================================================== Macros ===========================================================================*/ // translate linear level to logarithmic dB public static double BASS_BFX_Linear2dB(double level) { return (20*Math.log10(level)); } // translate logarithmic dB level to linear public static double BASS_BFX_dB2Linear(double dB) { return (Math.pow(10,(dB)/20)); } static { System.loadLibrary("bass_fx"); } }
ouarrtaha/react-native-voice-changer
android/src/main/java/com/un4seen/bass/BASS_FX.java
7,860
// room size [0........1], def. 0.5f
line_comment
nl
/*=========================================================================== BASS_FX 2.4 - Copyright (c) 2002-2018 (: JOBnik! :) [Arthur Aminov, ISRAEL] [http://www.jobnik.org] bugs/suggestions/questions: forum : http://www.un4seen.com/forum/?board=1 http://www.jobnik.org/forums e-mail : [email protected] -------------------------------------------------- NOTE: This header will work only with BASS_FX version 2.4.12 Check www.un4seen.com or www.jobnik.org for any later versions. * Requires BASS 2.4 (available at http://www.un4seen.com) ===========================================================================*/ package com.un4seen.bass; public class BASS_FX { // BASS_CHANNELINFO types public static final int BASS_CTYPE_STREAM_TEMPO = 0x1f200; public static final int BASS_CTYPE_STREAM_REVERSE = 0x1f201; // Tempo / Reverse / BPM / Beat flag public static final int BASS_FX_FREESOURCE = 0x10000; // Free the source handle as well? // BASS_FX Version public static native int BASS_FX_GetVersion(); /*=========================================================================== DSP (Digital Signal Processing) ===========================================================================*/ /* Multi-channel order of each channel is as follows: 3 channels left-front, right-front, center. 4 channels left-front, right-front, left-rear/side, right-rear/side. 5 channels left-front, right-front, center, left-rear/side, right-rear/side. 6 channels (5.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side. 8 channels (7.1) left-front, right-front, center, LFE, left-rear/side, right-rear/side, left-rear center, right-rear center. */ // DSP channels flags public static final int BASS_BFX_CHANALL = -1; // all channels at once (as by default) public static final int BASS_BFX_CHANNONE = 0; // disable an effect for all channels public static final int BASS_BFX_CHAN1 = 1; // left-front channel public static final int BASS_BFX_CHAN2 = 2; // right-front channel public static final int BASS_BFX_CHAN3 = 4; // see above info public static final int BASS_BFX_CHAN4 = 8; // see above info public static final int BASS_BFX_CHAN5 = 16; // see above info public static final int BASS_BFX_CHAN6 = 32; // see above info public static final int BASS_BFX_CHAN7 = 64; // see above info public static final int BASS_BFX_CHAN8 = 128; // see above info // if you have more than 8 channels (7.1), use this function public static int BASS_BFX_CHANNEL_N(int n) { return (1<<((n)-1)); } // DSP effects public static final int BASS_FX_BFX_ROTATE = 0x10000; // A channels volume ping-pong / multi channel public static final int BASS_FX_BFX_ECHO = 0x10001; // Echo / 2 channels max (deprecated) public static final int BASS_FX_BFX_FLANGER = 0x10002; // Flanger / multi channel (deprecated) public static final int BASS_FX_BFX_VOLUME = 0x10003; // Volume / multi channel public static final int BASS_FX_BFX_PEAKEQ = 0x10004; // Peaking Equalizer / multi channel public static final int BASS_FX_BFX_REVERB = 0x10005; // Reverb / 2 channels max (deprecated) public static final int BASS_FX_BFX_LPF = 0x10006; // Low Pass Filter 24dB / multi channel (deprecated) public static final int BASS_FX_BFX_MIX = 0x10007; // Swap, remap and mix channels / multi channel public static final int BASS_FX_BFX_DAMP = 0x10008; // Dynamic Amplification / multi channel public static final int BASS_FX_BFX_AUTOWAH = 0x10009; // Auto Wah / multi channel public static final int BASS_FX_BFX_ECHO2 = 0x1000a; // Echo 2 / multi channel (deprecated) public static final int BASS_FX_BFX_PHASER = 0x1000b; // Phaser / multi channel public static final int BASS_FX_BFX_ECHO3 = 0x1000c; // Echo 3 / multi channel (deprecated) public static final int BASS_FX_BFX_CHORUS = 0x1000d; // Chorus/Flanger / multi channel public static final int BASS_FX_BFX_APF = 0x1000e; // All Pass Filter / multi channel (deprecated) public static final int BASS_FX_BFX_COMPRESSOR = 0x1000f; // Compressor / multi channel (deprecated) public static final int BASS_FX_BFX_DISTORTION = 0x10010; // Distortion / multi channel public static final int BASS_FX_BFX_COMPRESSOR2 = 0x10011; // Compressor 2 / multi channel public static final int BASS_FX_BFX_VOLUME_ENV = 0x10012; // Volume envelope / multi channel public static final int BASS_FX_BFX_BQF = 0x10013; // BiQuad filters / multi channel public static final int BASS_FX_BFX_ECHO4 = 0x10014; // Echo 4 / multi channel public static final int BASS_FX_BFX_PITCHSHIFT = 0x10015; // Pitch shift using FFT / multi channel (not available on mobile) public static final int BASS_FX_BFX_FREEVERB = 0x10016; // Reverb using "Freeverb" algo / multi channel /* Deprecated effects in 2.4.10 version: ------------------------------------ BASS_FX_BFX_ECHO -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_ECHO2 -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_ECHO3 -> use BASS_FX_BFX_ECHO4 BASS_FX_BFX_REVERB -> use BASS_FX_BFX_FREEVERB BASS_FX_BFX_FLANGER -> use BASS_FX_BFX_CHORUS BASS_FX_BFX_COMPRESSOR -> use BASS_FX_BFX_COMPRESSOR2 BASS_FX_BFX_APF -> use BASS_FX_BFX_BQF with BASS_BFX_BQF_ALLPASS filter BASS_FX_BFX_LPF -> use 2x BASS_FX_BFX_BQF with BASS_BFX_BQF_LOWPASS filter and appropriate fQ values */ // Rotate public static class BASS_BFX_ROTATE { public float fRate; // rotation rate/speed in Hz (A negative rate can be used for reverse direction) public int lChannel; // BASS_BFX_CHANxxx flag/s (supported only even number of channels) } // Echo (deprecated) public static class BASS_BFX_ECHO { public float fLevel; // [0....1....n] linear public int lDelay; // [1200..30000] } // Flanger (deprecated) public static class BASS_BFX_FLANGER { public float fWetDry; // [0....1....n] linear public float fSpeed; // [0......0.09] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Volume public static class BASS_BFX_VOLUME { public int lChannel; // BASS_BFX_CHANxxx flag/s or 0 for global volume control public float fVolume; // [0....1....n] linear } // Peaking Equalizer public static class BASS_BFX_PEAKEQ { public int lBand; // [0...............n] more bands means more memory & cpu usage public float fBandwidth; // [0.1...........<10] in octaves - fQ is not in use (Bandwidth has a priority over fQ) public float fQ; // [0...............1] the EE kinda definition (linear) (if Bandwidth is not in use) public float fCenter; // [1Hz..<info.freq/2] in Hz public float fGain; // [-15dB...0...+15dB] in dB (can be above/below these limits) public int lChannel; // BASS_BFX_CHANxxx flag/s } // Reverb (deprecated) public static class BASS_BFX_REVERB { public float fLevel; // [0....1....n] linear public int lDelay; // [1200..10000] } // Low Pass Filter (deprecated) public static class BASS_BFX_LPF { public float fResonance; // [0.01...........10] public float fCutOffFreq; // [1Hz...info.freq/2] cutoff frequency public int lChannel; // BASS_BFX_CHANxxx flag/s } // Swap, remap and mix public static class BASS_BFX_MIX { public int[] lChannel; // an array of channels to mix using BASS_BFX_CHANxxx flag/s (lChannel[0] is left channel...) } // Dynamic Amplification public static class BASS_BFX_DAMP { public float fTarget; // target volume level [0<......1] linear public float fQuiet; // quiet volume level [0.......1] linear public float fRate; // amp adjustment rate [0.......1] linear public float fGain; // amplification level [0...1...n] linear public float fDelay; // delay in seconds before increasing level [0.......n] linear public int lChannel; // BASS_BFX_CHANxxx flag/s } // Auto Wah public static class BASS_BFX_AUTOWAH { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fRate; // rate of sweep in cycles per second [0<....<10] public float fRange; // sweep range in octaves [0<....<10] public float fFreq; // base frequency of sweep Hz [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 2 (deprecated) public static class BASS_BFX_ECHO2 { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fDelay; // delay sec [0<......n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Phaser public static class BASS_BFX_PHASER { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fRate; // rate of sweep in cycles per second [0<....<10] public float fRange; // sweep range in octaves [0<....<10] public float fFreq; // base frequency of sweep [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 3 (deprecated) public static class BASS_BFX_ECHO3 { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fDelay; // delay sec [0<......n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Chorus/Flanger public static class BASS_BFX_CHORUS { public float fDryMix; // dry (unaffected) signal mix [-2......2] public float fWetMix; // wet (affected) signal mix [-2......2] public float fFeedback; // output signal to feed back into input [-1......1] public float fMinSweep; // minimal delay ms [0<...6000] public float fMaxSweep; // maximum delay ms [0<...6000] public float fRate; // rate ms/s [0<...1000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // All Pass Filter (deprecated) public static class BASS_BFX_APF { public float fGain; // reverberation time [-1=<..<=1] public float fDelay; // delay sec [0<....<=n] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Compressor (deprecated) public static class BASS_BFX_COMPRESSOR { public float fThreshold; // compressor threshold [0<=...<=1] public float fAttacktime; // attack time ms [0<.<=1000] public float fReleasetime; // release time ms [0<.<=5000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Distortion public static class BASS_BFX_DISTORTION { public float fDrive; // distortion drive [0<=...<=5] public float fDryMix; // dry (unaffected) signal mix [-5<=..<=5] public float fWetMix; // wet (affected) signal mix [-5<=..<=5] public float fFeedback; // output signal to feed back into input [-1<=..<=1] public float fVolume; // distortion volume [0=<...<=2] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Compressor 2 public static class BASS_BFX_COMPRESSOR2 { public float fGain; // output gain of signal after compression [-60....60] in dB public float fThreshold; // point at which compression begins [-60.....0] in dB public float fRatio; // compression ratio [1.......n] public float fAttack; // attack time in ms [0.01.1000] public float fRelease; // release time in ms [0.01.5000] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Volume envelope public static class BASS_BFX_VOLUME_ENV { public int lChannel; // BASS_BFX_CHANxxx flag/s public int lNodeCount; // number of nodes public BASS_BFX_ENV_NODE[] pNodes; // the nodes public boolean bFollow; // follow source position } public static class BASS_BFX_ENV_NODE { public double pos; // node position in seconds (1st envelope node must be at position 0) public float val; // node value } // BiQuad Filters public static final int BASS_BFX_BQF_LOWPASS = 0; public static final int BASS_BFX_BQF_HIGHPASS = 1; public static final int BASS_BFX_BQF_BANDPASS = 2; // constant 0 dB peak gain public static final int BASS_BFX_BQF_BANDPASS_Q = 3; // constant skirt gain, peak gain = Q public static final int BASS_BFX_BQF_NOTCH = 4; public static final int BASS_BFX_BQF_ALLPASS = 5; public static final int BASS_BFX_BQF_PEAKINGEQ = 6; public static final int BASS_BFX_BQF_LOWSHELF = 7; public static final int BASS_BFX_BQF_HIGHSHELF = 8; public static class BASS_BFX_BQF { public int lFilter; // BASS_BFX_BQF_xxx filter types public float fCenter; // [1Hz..<info.freq/2] Cutoff (central) frequency in Hz public float fGain; // [-15dB...0...+15dB] Used only for PEAKINGEQ and Shelving filters in dB (can be above/below these limits) public float fBandwidth; // [0.1...........<10] Bandwidth in octaves (fQ is not in use (fBandwidth has a priority over fQ)) // (between -3 dB frequencies for BANDPASS and NOTCH or between midpoint // (fGgain/2) gain frequencies for PEAKINGEQ) public float fQ; // [0.1.............1] The EE kinda definition (linear) (if fBandwidth is not in use) public float fS; // [0.1.............1] A "shelf slope" parameter (linear) (used only with Shelving filters) // when fS = 1, the shelf slope is as steep as you can get it and remain monotonically // increasing or decreasing gain with frequency. public int lChannel; // BASS_BFX_CHANxxx flag/s } // Echo 4 public static class BASS_BFX_ECHO4 { public float fDryMix; // dry (unaffected) signal mix [-2.......2] public float fWetMix; // wet (affected) signal mix [-2.......2] public float fFeedback; // output signal to feed back into input [-1.......1] public float fDelay; // delay sec [0<.......n] public boolean bStereo; // echo adjoining channels to each other [TRUE/FALSE] public int lChannel; // BASS_BFX_CHANxxx flag/s } // Pitch shift (not available on mobile) public static class BASS_BFX_PITCHSHIFT { public float fPitchShift; // A factor value which is between 0.5 (one octave down) and 2 (one octave up) (1 won't change the pitch) [1 default] // (fSemitones is not in use, fPitchShift has a priority over fSemitones) public float fSemitones; // Semitones (0 won't change the pitch) [0 default] public int lFFTsize; // Defines the FFT frame size used for the processing. Typical values are 1024, 2048 and 4096 [2048 default] // It may be any value <= 8192 but it MUST be a power of 2 public int lOsamp; // Is the STFT oversampling factor which also determines the overlap between adjacent STFT frames [8 default] // It should at least be 4 for moderate scaling ratios. A value of 32 is recommended for best quality (better quality = higher CPU usage) public int lChannel; // BASS_BFX_CHANxxx flag/s } // Freeverb public static final int BASS_BFX_FREEVERB_MODE_FREEZE = 1; public static class BASS_BFX_FREEVERB { public float fDryMix; // dry (unaffected) signal mix [0........1], def. 0 public float fWetMix; // wet (affected) signal mix [0........3], def. 1.0f public float fRoomSize; // room size<SUF> public float fDamp; // damping [0........1], def. 0.5f public float fWidth; // stereo width [0........1], def. 1 public int lMode; // 0 or BASS_BFX_FREEVERB_MODE_FREEZE, def. 0 (no freeze) public int lChannel; // BASS_BFX_CHANxxx flag/s } /*=========================================================================== set dsp fx - BASS_ChannelSetFX remove dsp fx - BASS_ChannelRemoveFX set parameters - BASS_FXSetParameters retrieve parameters - BASS_FXGetParameters reset the state - BASS_FXReset ===========================================================================*/ /*=========================================================================== Tempo, Pitch scaling and Sample rate changers ===========================================================================*/ // NOTE: Enable Tempo supported flags in BASS_FX_TempoCreate and the others to source handle. // tempo attributes (BASS_ChannelSet/GetAttribute) public static final int BASS_ATTRIB_TEMPO = 0x10000; public static final int BASS_ATTRIB_TEMPO_PITCH = 0x10001; public static final int BASS_ATTRIB_TEMPO_FREQ = 0x10002; // tempo attributes options public static final int BASS_ATTRIB_TEMPO_OPTION_USE_AA_FILTER = 0x10010; // TRUE (default) / FALSE (default for multi-channel on mobile devices for lower CPU usage) public static final int BASS_ATTRIB_TEMPO_OPTION_AA_FILTER_LENGTH = 0x10011; // 32 default (8 .. 128 taps) public static final int BASS_ATTRIB_TEMPO_OPTION_USE_QUICKALGO = 0x10012; // TRUE (default on mobile devices for lower CPU usage) / FALSE (default) public static final int BASS_ATTRIB_TEMPO_OPTION_SEQUENCE_MS = 0x10013; // 82 default, 0 = automatic public static final int BASS_ATTRIB_TEMPO_OPTION_SEEKWINDOW_MS = 0x10014; // 28 default, 0 = automatic public static final int BASS_ATTRIB_TEMPO_OPTION_OVERLAP_MS = 0x10015; // 8 default public static final int BASS_ATTRIB_TEMPO_OPTION_PREVENT_CLICK = 0x10016; // TRUE / FALSE (default) // tempo algorithm flags public static final int BASS_FX_TEMPO_ALGO_LINEAR = 0x200; public static final int BASS_FX_TEMPO_ALGO_CUBIC = 0x400; // default public static final int BASS_FX_TEMPO_ALGO_SHANNON = 0x800; public static native int BASS_FX_TempoCreate(int chan, int flags); public static native int BASS_FX_TempoGetSource(int chan); public static native float BASS_FX_TempoGetRateRatio(int chan); /*=========================================================================== Reverse playback ===========================================================================*/ // NOTES: 1. MODs won't load without BASS_MUSIC_PRESCAN flag. // 2. Enable Reverse supported flags in BASS_FX_ReverseCreate and the others to source handle. // reverse attribute (BASS_ChannelSet/GetAttribute) public static final int BASS_ATTRIB_REVERSE_DIR = 0x11000; // playback directions public static final int BASS_FX_RVS_REVERSE = -1; public static final int BASS_FX_RVS_FORWARD = 1; public static native int BASS_FX_ReverseCreate(int chan, float dec_block, int flags); public static native int BASS_FX_ReverseGetSource(int chan); /*=========================================================================== BPM (Beats Per Minute) ===========================================================================*/ // bpm flags public static final int BASS_FX_BPM_BKGRND = 1; // if in use, then you can do other processing while detection's in progress. Available only in Windows platforms (BPM/Beat) public static final int BASS_FX_BPM_MULT2 = 2; // if in use, then will auto multiply bpm by 2 (if BPM < minBPM*2) // translation options (deprecated) public static final int BASS_FX_BPM_TRAN_X2 = 0; // multiply the original BPM value by 2 (may be called only once & will change the original BPM as well!) public static final int BASS_FX_BPM_TRAN_2FREQ = 1; // BPM value to Frequency public static final int BASS_FX_BPM_TRAN_FREQ2 = 2; // Frequency to BPM value public static final int BASS_FX_BPM_TRAN_2PERCENT = 3; // BPM value to Percents public static final int BASS_FX_BPM_TRAN_PERCENT2 = 4; // Percents to BPM value public interface BPMPROC { void BPMPROC(int chan, float bpm, Object user); } public interface BPMPROGRESSPROC { void BPMPROGRESSPROC(int chan, float percent, Object user); } // back-compatibility public interface BPMPROCESSPROC { void BPMPROCESSPROC(int chan, float percent, Object user); } public static native float BASS_FX_BPM_DecodeGet(int chan, double startSec, double endSec, int minMaxBPM, int flags, Object proc, Object user); public static native boolean BASS_FX_BPM_CallbackSet(int handle, BPMPROC proc, double period, int minMaxBPM, int flags, Object user); public static native boolean BASS_FX_BPM_CallbackReset(int handle); public static native float BASS_FX_BPM_Translate(int handle, float val2tran, int trans); // deprecated public static native boolean BASS_FX_BPM_Free(int handle); /*=========================================================================== Beat position trigger ===========================================================================*/ public interface BPMBEATPROC { void BPMBEATPROC(int chan, double beatpos, Object user); } public static native boolean BASS_FX_BPM_BeatCallbackSet(int handle, BPMBEATPROC proc, Object user); public static native boolean BASS_FX_BPM_BeatCallbackReset(int handle); public static native boolean BASS_FX_BPM_BeatDecodeGet(int chan, double startSec, double endSec, int flags, BPMBEATPROC proc, Object user); public static native boolean BASS_FX_BPM_BeatSetParameters(int handle, float bandwidth, float centerfreq, float beat_rtime); public static native boolean BASS_FX_BPM_BeatGetParameters(int handle, Float bandwidth, Float centerfreq, Float beat_rtime); public static native boolean BASS_FX_BPM_BeatFree(int handle); /*=========================================================================== Macros ===========================================================================*/ // translate linear level to logarithmic dB public static double BASS_BFX_Linear2dB(double level) { return (20*Math.log10(level)); } // translate logarithmic dB level to linear public static double BASS_BFX_dB2Linear(double dB) { return (Math.pow(10,(dB)/20)); } static { System.loadLibrary("bass_fx"); } }
33375_3
package com.example.drivedealz2.Fragment; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.Navigation; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.example.drivedealz2.Adapter.CarListAdapter; import com.example.drivedealz2.Model.Car; import com.example.drivedealz2.View.CarViewModel; import com.exemple.DriveDealz.R; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; import java.util.List; public class CarListFragment extends Fragment { private CarListAdapter carListAdapter; private List<Car> carList; private FloatingActionButton fab; public CarListFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_car_list, container, false); // Laad de lijst met auto's en stel deze in op de adapter // carListAdapter.setCarList(loadCarList()); // Implementeer deze methode volgens jouw gegevensbron return rootView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); carList = new ArrayList<>(); // Hier kun je de views gebruiken zoals nodig RecyclerView recyclerView = view.findViewById(R.id.RecyclerViewCarList); carListAdapter = new CarListAdapter(getContext()); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); // Hier wordt de layoutManager ingesteld recyclerView.setAdapter(carListAdapter); fab = view.findViewById(R.id.floatingActionButton); CarViewModel carViewModel = new ViewModelProvider(this).get(CarViewModel.class); carViewModel.getAllCars().observe(getViewLifecycleOwner(), cars -> { carList.clear(); carListAdapter.setCarList(cars); carList.addAll(cars); carListAdapter.notifyDataSetChanged(); }); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Navigation.findNavController(v).navigate(R.id.action_fragment_car_list_to_new_car_fragment); } }); } }
oussamaelh10/DriveDealz2
app/src/main/java/com/example/drivedealz2/Fragment/CarListFragment.java
802
// Hier wordt de layoutManager ingesteld
line_comment
nl
package com.example.drivedealz2.Fragment; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.Navigation; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.example.drivedealz2.Adapter.CarListAdapter; import com.example.drivedealz2.Model.Car; import com.example.drivedealz2.View.CarViewModel; import com.exemple.DriveDealz.R; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; import java.util.List; public class CarListFragment extends Fragment { private CarListAdapter carListAdapter; private List<Car> carList; private FloatingActionButton fab; public CarListFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_car_list, container, false); // Laad de lijst met auto's en stel deze in op de adapter // carListAdapter.setCarList(loadCarList()); // Implementeer deze methode volgens jouw gegevensbron return rootView; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); carList = new ArrayList<>(); // Hier kun je de views gebruiken zoals nodig RecyclerView recyclerView = view.findViewById(R.id.RecyclerViewCarList); carListAdapter = new CarListAdapter(getContext()); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); // Hier wordt<SUF> recyclerView.setAdapter(carListAdapter); fab = view.findViewById(R.id.floatingActionButton); CarViewModel carViewModel = new ViewModelProvider(this).get(CarViewModel.class); carViewModel.getAllCars().observe(getViewLifecycleOwner(), cars -> { carList.clear(); carListAdapter.setCarList(cars); carList.addAll(cars); carListAdapter.notifyDataSetChanged(); }); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Navigation.findNavController(v).navigate(R.id.action_fragment_car_list_to_new_car_fragment); } }); } }
52278_1
/* * Overchan Android (Meta Imageboard Client) * Copyright (C) 2014-2016 miku-nyan <https://github.com/miku-nyan> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nya.miku.wishmaster.chans.monaba; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.tuple.Pair; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.HttpHeaders; import cz.msebera.android.httpclient.client.HttpClient; import cz.msebera.android.httpclient.entity.mime.content.ByteArrayBody; import cz.msebera.android.httpclient.message.BasicHeader; import android.content.SharedPreferences; import android.content.res.Resources; import android.preference.PreferenceGroup; import android.text.TextUtils; import nya.miku.wishmaster.api.CloudflareChanModule; import nya.miku.wishmaster.api.interfaces.CancellableTask; import nya.miku.wishmaster.api.interfaces.ProgressListener; import nya.miku.wishmaster.api.models.CaptchaModel; import nya.miku.wishmaster.api.models.PostModel; import nya.miku.wishmaster.api.models.SendPostModel; import nya.miku.wishmaster.api.models.ThreadModel; import nya.miku.wishmaster.api.models.UrlPageModel; import nya.miku.wishmaster.api.util.ChanModels; import nya.miku.wishmaster.api.util.UrlPathUtils; import nya.miku.wishmaster.common.IOUtils; import nya.miku.wishmaster.http.ExtendedMultipartBuilder; import nya.miku.wishmaster.http.streamer.HttpRequestModel; import nya.miku.wishmaster.http.streamer.HttpResponseModel; import nya.miku.wishmaster.http.streamer.HttpStreamer; import nya.miku.wishmaster.http.streamer.HttpWrongStatusCodeException; public abstract class AbstractMonabaChan extends CloudflareChanModule { static final String[] RATINGS = new String[] { "SFW", "R15", "R18", "R18G" }; private static final Pattern IMAGE_URL_PATTERN = Pattern.compile("<img[^>]*src=\"(.*?)\""); private static final Pattern ERROR_PATTERN = Pattern.compile("<div[^>]*id=\"message\"[^>]*>(.*?)</div>", Pattern.DOTALL); public AbstractMonabaChan(SharedPreferences preferences, Resources resources) { super(preferences, resources); } protected boolean canHttps() { return true; } protected boolean useHttps() { if (!canHttps()) return false; return useHttps(true); } protected abstract String getUsingDomain(); protected String[] getAllDomains() { return new String[] { getUsingDomain() }; } protected String getUsingUrl() { return (useHttps() ? "https://" : "http://") + getUsingDomain() + "/"; } @Override protected boolean canCloudflare() { return false; } @Override public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) { if (canHttps()) addHttpsPreference(preferenceGroup, true); addProxyPreferences(preferenceGroup); addClearCookiesPreference(preferenceGroup); } protected ThreadModel[] readPage(String url, ProgressListener listener, CancellableTask task, boolean checkIfModified) throws Exception { HttpResponseModel responseModel = null; Closeable in = null; HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setCheckIfModified(checkIfModified).build(); try { responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, listener, task); if (responseModel.statusCode == 200) { in = new MonabaReader(responseModel.stream, canCloudflare()); if (task != null && task.isCancelled()) throw new Exception("interrupted"); return ((MonabaReader) in).readPage() ; } else { if (responseModel.notModified()) return null; throw new HttpWrongStatusCodeException(responseModel.statusCode, responseModel.statusCode + " - " + responseModel.statusReason); } } catch (Exception e) { if (responseModel != null) HttpStreamer.getInstance().removeFromModifiedMap(url); throw e; } finally { IOUtils.closeQuietly(in); if (responseModel != null) responseModel.release(); } } @Override public ThreadModel[] getThreadsList(String boardName, int page, ProgressListener listener, CancellableTask task, ThreadModel[] oldList) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = getChanName(); urlModel.type = UrlPageModel.TYPE_BOARDPAGE; urlModel.boardName = boardName; urlModel.boardPage = page; String url = buildUrl(urlModel); ThreadModel[] threads = readPage(url, listener, task, oldList != null); if (threads == null) { return oldList; } else { return threads; } } @Override public PostModel[] getPostsList(String boardName, String threadNumber, ProgressListener listener, CancellableTask task, PostModel[] oldList) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = getChanName(); urlModel.type = UrlPageModel.TYPE_THREADPAGE; urlModel.boardName = boardName; urlModel.threadNumber = threadNumber; String url = buildUrl(urlModel); ThreadModel[] threads = readPage(url, listener, task, oldList != null); if (threads == null) { return oldList; } else { if (threads.length == 0) throw new Exception("Unable to parse response"); return oldList == null ? threads[0].posts : ChanModels.mergePostsLists(Arrays.asList(oldList), Arrays.asList(threads[0].posts)); } } @Override public CaptchaModel getNewCaptcha(String boardName, String threadNumber, ProgressListener listener, CancellableTask task) throws Exception { String captchaUrl = getUsingUrl() + "/captcha"; String html = HttpStreamer.getInstance().getStringFromUrl(captchaUrl, HttpRequestModel.DEFAULT_GET, httpClient, listener, task, false); Matcher matcher = IMAGE_URL_PATTERN.matcher(html); if (matcher.find()) { return downloadCaptcha(fixRelativeUrl(matcher.group(1)), listener, task); } else { throw new Exception("Captcha update failed"); } } @Override public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = getChanName(); urlModel.boardName = model.boardName; if (model.threadNumber == null) { urlModel.type = UrlPageModel.TYPE_BOARDPAGE; urlModel.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE; } else { urlModel.type = UrlPageModel.TYPE_THREADPAGE; urlModel.threadNumber = model.threadNumber; } String referer = buildUrl(urlModel); List<Pair<String, String>> fields = MonabaAntibot.getFormValues(referer, task, httpClient); if (task != null && task.isCancelled()) throw new Exception("interrupted"); ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create(). setCharset(Charset.forName("UTF-8")).setDelegates(listener, task); String rating = (model.icon >= 0 && model.icon < RATINGS.length) ? Integer.toString(model.icon+1) : "1"; int fileCount = 0; for (Pair<String, String> pair : fields) { String val; switch (pair.getKey()) { case "f1": val = model.name; break; case "f2": val = model.subject; break; case "f3": val = model.comment; break; case "f4": val = TextUtils.isEmpty(model.password) ? getDefaultPassword() : model.password; break; case "f5": val = TextUtils.isEmpty(model.captchaAnswer) ? "" : model.captchaAnswer; break; case "f6": val = "1"; break; //noko case "f7": val = model.sage ? pair.getValue() : ""; break; default: val = pair.getValue(); } if (pair.getValue().equals("file")) { if ((model.attachments != null) && (fileCount < model.attachments.length)) { postEntityBuilder.addFile(pair.getKey(), model.attachments[fileCount], model.randomHash); ++fileCount; } else { postEntityBuilder.addPart(pair.getKey(), new ByteArrayBody(new byte[0], "")); } } else if (pair.getValue().equals("rating-input")) { postEntityBuilder.addString(pair.getKey(), rating); } else { postEntityBuilder.addString(pair.getKey(), val); } } String url = getUsingUrl() + model.boardName + (model.threadNumber != null ? "/" + model.threadNumber : ""); Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, referer) }; HttpRequestModel request = HttpRequestModel.builder(). setPOST(postEntityBuilder.build()).setCustomHeaders(customHeaders).setNoRedirect(true).build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task); if (response.statusCode == 303) { for (Header header : response.headers) { if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) { String location = header.getValue(); String html = HttpStreamer.getInstance(). getStringFromUrl(location, HttpRequestModel.DEFAULT_GET, httpClient, null, task, false); if (html.contains("Post has been submitted successfully")) { return location; } Matcher errorMatcher = ERROR_PATTERN.matcher(html); if (errorMatcher.find()) { throw new Exception(StringEscapeUtils.unescapeHtml4(errorMatcher.group(1))); } return null; } } } else throw new Exception(response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); } return null; } @Override public String buildUrl(UrlPageModel model) throws IllegalArgumentException { if (!model.chanName.equals(getChanName())) throw new IllegalArgumentException("wrong chan"); if (model.boardName != null && !model.boardName.matches("\\w*")) throw new IllegalArgumentException("wrong board name"); StringBuilder url = new StringBuilder(getUsingUrl()); switch (model.type) { case UrlPageModel.TYPE_INDEXPAGE: break; case UrlPageModel.TYPE_BOARDPAGE: url.append(model.boardName); if (model.boardPage > 0) url.append("/page/").append(model.boardPage); break; case UrlPageModel.TYPE_THREADPAGE: url.append(model.boardName).append("/").append(model.threadNumber); if (model.postNumber != null && model.postNumber.length() > 0) url.append("#").append(model.postNumber); break; case UrlPageModel.TYPE_OTHERPAGE: url.append(model.otherPath.startsWith("/") ? model.otherPath.substring(1) : model.otherPath); break; default: throw new IllegalArgumentException("wrong page type"); } return url.toString(); } @Override public UrlPageModel parseUrl(String url) throws IllegalArgumentException { String path = UrlPathUtils.getUrlPath(url, getAllDomains()); if (path == null) throw new IllegalArgumentException("wrong domain"); UrlPageModel model = new UrlPageModel(); model.chanName = getChanName(); if (path.length() == 0) { model.type = UrlPageModel.TYPE_INDEXPAGE; return model; } Matcher threadPage = Pattern.compile("^([^/]+)/(\\d+)(?:#(\\d+))?").matcher(path); if (threadPage.find()) { model.type = UrlPageModel.TYPE_THREADPAGE; model.boardName = threadPage.group(1); model.threadNumber = threadPage.group(2); model.postNumber = threadPage.group(3); return model; } Matcher boardPage = Pattern.compile("^([^/]+)(?:/page/(\\d+))?").matcher(path); if (boardPage.find()) { model.type = UrlPageModel.TYPE_BOARDPAGE; model.boardName = boardPage.group(1); String page = boardPage.group(2); model.boardPage = (page == null) ? 0 : Integer.parseInt(page); return model; } model.type = UrlPageModel.TYPE_OTHERPAGE; model.otherPath = path; return model; } protected static class MonabaAntibot { public static List<Pair<String, String>> getFormValues(String url, CancellableTask task, HttpClient httpClient) throws Exception { return getFormValues(url, HttpRequestModel.DEFAULT_GET, task, httpClient, "<form class=\"plain-post-form\"", "<div id=\"board-info\""); } public static List<Pair<String, String>> getFormValues(String url, HttpRequestModel requestModel, CancellableTask task, HttpClient client, String startForm, String endForm) throws Exception { MonabaAntibot reader = null; HttpRequestModel request = requestModel; HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, client, null, task); reader = new MonabaAntibot(response.stream, startForm, endForm); return reader.readForm(); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) {} } if (response != null) response.release(); } } private StringBuilder readBuffer = new StringBuilder(); private List<Pair<String, String>> result = null; private String currentName = null; private String currentValue = null; private String currentType = null; private boolean currentTextarea = false; private boolean currentReading = false; private final char[] start; private final char[][] filters; private final Reader in; private static final int FILTER_INPUT_OPEN = 0; private static final int FILTER_TEXTAREA_OPEN = 1; private static final int FILTER_SELECT_OPEN = 2; private static final int FILTER_NAME_OPEN = 3; private static final int FILTER_VALUE_OPEN = 4; private static final int FILTER_TYPE_OPEN = 5; private static final int FILTER_CLASS_OPEN = 6; private static final int FILTER_TAG_CLOSE = 7; private MonabaAntibot(InputStream in, String start, String end) { this.start = start.toCharArray(); this.filters = new char[][] { "<input".toCharArray(), "<textarea".toCharArray(), "<select".toCharArray(), "name=\"".toCharArray(), "value=\"".toCharArray(), "type=\"".toCharArray(), "class=\"".toCharArray(), ">".toCharArray(), end.toCharArray() }; this.in = new BufferedReader(new InputStreamReader(in)); } private List<Pair<String, String>> readForm() throws IOException { result = new ArrayList<>(); skipUntilSequence(start); int filtersCount = filters.length; int[] pos = new int[filtersCount]; int[] len = new int[filtersCount]; for (int i=0; i<filtersCount; ++i) len[i] = filters[i].length; int curChar; while ((curChar = in.read()) != -1) { for (int i=0; i<filtersCount; ++i) { if (curChar == filters[i][pos[i]]) { ++pos[i]; if (pos[i] == len[i]) { if (i == filtersCount - 1) { return result; } handleFilter(i); pos[i] = 0; } } else { if (pos[i] != 0) pos[i] = curChar == filters[i][0] ? 1 : 0; } } } return result; } private void handleFilter(int i) throws IOException { switch (i) { case FILTER_INPUT_OPEN: case FILTER_SELECT_OPEN: currentReading = true; currentTextarea = false; break; case FILTER_TEXTAREA_OPEN: currentReading = true; currentTextarea = true; break; case FILTER_NAME_OPEN: currentName = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray())); break; case FILTER_VALUE_OPEN: currentValue = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray())); break; case FILTER_CLASS_OPEN: case FILTER_TYPE_OPEN: currentType = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray())); break; case FILTER_TAG_CLOSE: if (currentTextarea) { currentValue = StringEscapeUtils.unescapeHtml4(readUntilSequence("<".toCharArray())); } if (currentReading && currentName != null) { result.add(Pair.of(currentName, currentValue != null ? currentValue : currentType != null ? currentType : "")); } currentName = null; currentValue = null; currentType = null; currentReading = false; currentTextarea = false; break; } } private void skipUntilSequence(char[] sequence) throws IOException { int len = sequence.length; if (len == 0) return; int pos = 0; int curChar; while ((curChar = in.read()) != -1) { if (curChar == sequence[pos]) { ++pos; if (pos == len) break; } else { if (pos != 0) pos = curChar == sequence[0] ? 1 : 0; } } } private String readUntilSequence(char[] sequence) throws IOException { int len = sequence.length; if (len == 0) return ""; readBuffer.setLength(0); int pos = 0; int curChar; while ((curChar = in.read()) != -1) { readBuffer.append((char) curChar); if (curChar == sequence[pos]) { ++pos; if (pos == len) break; } else { if (pos != 0) pos = curChar == sequence[0] ? 1 : 0; } } int buflen = readBuffer.length(); if (buflen >= len) { readBuffer.setLength(buflen - len); return readBuffer.toString(); } else { return ""; } } public void close() throws IOException { in.close(); } } }
overchan-project/Overchan-Android
src/nya/miku/wishmaster/chans/monaba/AbstractMonabaChan.java
5,864
//" : "http://") + getUsingDomain() + "/";
line_comment
nl
/* * Overchan Android (Meta Imageboard Client) * Copyright (C) 2014-2016 miku-nyan <https://github.com/miku-nyan> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nya.miku.wishmaster.chans.monaba; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.tuple.Pair; import cz.msebera.android.httpclient.Header; import cz.msebera.android.httpclient.HttpHeaders; import cz.msebera.android.httpclient.client.HttpClient; import cz.msebera.android.httpclient.entity.mime.content.ByteArrayBody; import cz.msebera.android.httpclient.message.BasicHeader; import android.content.SharedPreferences; import android.content.res.Resources; import android.preference.PreferenceGroup; import android.text.TextUtils; import nya.miku.wishmaster.api.CloudflareChanModule; import nya.miku.wishmaster.api.interfaces.CancellableTask; import nya.miku.wishmaster.api.interfaces.ProgressListener; import nya.miku.wishmaster.api.models.CaptchaModel; import nya.miku.wishmaster.api.models.PostModel; import nya.miku.wishmaster.api.models.SendPostModel; import nya.miku.wishmaster.api.models.ThreadModel; import nya.miku.wishmaster.api.models.UrlPageModel; import nya.miku.wishmaster.api.util.ChanModels; import nya.miku.wishmaster.api.util.UrlPathUtils; import nya.miku.wishmaster.common.IOUtils; import nya.miku.wishmaster.http.ExtendedMultipartBuilder; import nya.miku.wishmaster.http.streamer.HttpRequestModel; import nya.miku.wishmaster.http.streamer.HttpResponseModel; import nya.miku.wishmaster.http.streamer.HttpStreamer; import nya.miku.wishmaster.http.streamer.HttpWrongStatusCodeException; public abstract class AbstractMonabaChan extends CloudflareChanModule { static final String[] RATINGS = new String[] { "SFW", "R15", "R18", "R18G" }; private static final Pattern IMAGE_URL_PATTERN = Pattern.compile("<img[^>]*src=\"(.*?)\""); private static final Pattern ERROR_PATTERN = Pattern.compile("<div[^>]*id=\"message\"[^>]*>(.*?)</div>", Pattern.DOTALL); public AbstractMonabaChan(SharedPreferences preferences, Resources resources) { super(preferences, resources); } protected boolean canHttps() { return true; } protected boolean useHttps() { if (!canHttps()) return false; return useHttps(true); } protected abstract String getUsingDomain(); protected String[] getAllDomains() { return new String[] { getUsingDomain() }; } protected String getUsingUrl() { return (useHttps() ? "https://" :<SUF> } @Override protected boolean canCloudflare() { return false; } @Override public void addPreferencesOnScreen(PreferenceGroup preferenceGroup) { if (canHttps()) addHttpsPreference(preferenceGroup, true); addProxyPreferences(preferenceGroup); addClearCookiesPreference(preferenceGroup); } protected ThreadModel[] readPage(String url, ProgressListener listener, CancellableTask task, boolean checkIfModified) throws Exception { HttpResponseModel responseModel = null; Closeable in = null; HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setCheckIfModified(checkIfModified).build(); try { responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, listener, task); if (responseModel.statusCode == 200) { in = new MonabaReader(responseModel.stream, canCloudflare()); if (task != null && task.isCancelled()) throw new Exception("interrupted"); return ((MonabaReader) in).readPage() ; } else { if (responseModel.notModified()) return null; throw new HttpWrongStatusCodeException(responseModel.statusCode, responseModel.statusCode + " - " + responseModel.statusReason); } } catch (Exception e) { if (responseModel != null) HttpStreamer.getInstance().removeFromModifiedMap(url); throw e; } finally { IOUtils.closeQuietly(in); if (responseModel != null) responseModel.release(); } } @Override public ThreadModel[] getThreadsList(String boardName, int page, ProgressListener listener, CancellableTask task, ThreadModel[] oldList) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = getChanName(); urlModel.type = UrlPageModel.TYPE_BOARDPAGE; urlModel.boardName = boardName; urlModel.boardPage = page; String url = buildUrl(urlModel); ThreadModel[] threads = readPage(url, listener, task, oldList != null); if (threads == null) { return oldList; } else { return threads; } } @Override public PostModel[] getPostsList(String boardName, String threadNumber, ProgressListener listener, CancellableTask task, PostModel[] oldList) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = getChanName(); urlModel.type = UrlPageModel.TYPE_THREADPAGE; urlModel.boardName = boardName; urlModel.threadNumber = threadNumber; String url = buildUrl(urlModel); ThreadModel[] threads = readPage(url, listener, task, oldList != null); if (threads == null) { return oldList; } else { if (threads.length == 0) throw new Exception("Unable to parse response"); return oldList == null ? threads[0].posts : ChanModels.mergePostsLists(Arrays.asList(oldList), Arrays.asList(threads[0].posts)); } } @Override public CaptchaModel getNewCaptcha(String boardName, String threadNumber, ProgressListener listener, CancellableTask task) throws Exception { String captchaUrl = getUsingUrl() + "/captcha"; String html = HttpStreamer.getInstance().getStringFromUrl(captchaUrl, HttpRequestModel.DEFAULT_GET, httpClient, listener, task, false); Matcher matcher = IMAGE_URL_PATTERN.matcher(html); if (matcher.find()) { return downloadCaptcha(fixRelativeUrl(matcher.group(1)), listener, task); } else { throw new Exception("Captcha update failed"); } } @Override public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception { UrlPageModel urlModel = new UrlPageModel(); urlModel.chanName = getChanName(); urlModel.boardName = model.boardName; if (model.threadNumber == null) { urlModel.type = UrlPageModel.TYPE_BOARDPAGE; urlModel.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE; } else { urlModel.type = UrlPageModel.TYPE_THREADPAGE; urlModel.threadNumber = model.threadNumber; } String referer = buildUrl(urlModel); List<Pair<String, String>> fields = MonabaAntibot.getFormValues(referer, task, httpClient); if (task != null && task.isCancelled()) throw new Exception("interrupted"); ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create(). setCharset(Charset.forName("UTF-8")).setDelegates(listener, task); String rating = (model.icon >= 0 && model.icon < RATINGS.length) ? Integer.toString(model.icon+1) : "1"; int fileCount = 0; for (Pair<String, String> pair : fields) { String val; switch (pair.getKey()) { case "f1": val = model.name; break; case "f2": val = model.subject; break; case "f3": val = model.comment; break; case "f4": val = TextUtils.isEmpty(model.password) ? getDefaultPassword() : model.password; break; case "f5": val = TextUtils.isEmpty(model.captchaAnswer) ? "" : model.captchaAnswer; break; case "f6": val = "1"; break; //noko case "f7": val = model.sage ? pair.getValue() : ""; break; default: val = pair.getValue(); } if (pair.getValue().equals("file")) { if ((model.attachments != null) && (fileCount < model.attachments.length)) { postEntityBuilder.addFile(pair.getKey(), model.attachments[fileCount], model.randomHash); ++fileCount; } else { postEntityBuilder.addPart(pair.getKey(), new ByteArrayBody(new byte[0], "")); } } else if (pair.getValue().equals("rating-input")) { postEntityBuilder.addString(pair.getKey(), rating); } else { postEntityBuilder.addString(pair.getKey(), val); } } String url = getUsingUrl() + model.boardName + (model.threadNumber != null ? "/" + model.threadNumber : ""); Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, referer) }; HttpRequestModel request = HttpRequestModel.builder(). setPOST(postEntityBuilder.build()).setCustomHeaders(customHeaders).setNoRedirect(true).build(); HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, httpClient, null, task); if (response.statusCode == 303) { for (Header header : response.headers) { if (header != null && HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) { String location = header.getValue(); String html = HttpStreamer.getInstance(). getStringFromUrl(location, HttpRequestModel.DEFAULT_GET, httpClient, null, task, false); if (html.contains("Post has been submitted successfully")) { return location; } Matcher errorMatcher = ERROR_PATTERN.matcher(html); if (errorMatcher.find()) { throw new Exception(StringEscapeUtils.unescapeHtml4(errorMatcher.group(1))); } return null; } } } else throw new Exception(response.statusCode + " - " + response.statusReason); } finally { if (response != null) response.release(); } return null; } @Override public String buildUrl(UrlPageModel model) throws IllegalArgumentException { if (!model.chanName.equals(getChanName())) throw new IllegalArgumentException("wrong chan"); if (model.boardName != null && !model.boardName.matches("\\w*")) throw new IllegalArgumentException("wrong board name"); StringBuilder url = new StringBuilder(getUsingUrl()); switch (model.type) { case UrlPageModel.TYPE_INDEXPAGE: break; case UrlPageModel.TYPE_BOARDPAGE: url.append(model.boardName); if (model.boardPage > 0) url.append("/page/").append(model.boardPage); break; case UrlPageModel.TYPE_THREADPAGE: url.append(model.boardName).append("/").append(model.threadNumber); if (model.postNumber != null && model.postNumber.length() > 0) url.append("#").append(model.postNumber); break; case UrlPageModel.TYPE_OTHERPAGE: url.append(model.otherPath.startsWith("/") ? model.otherPath.substring(1) : model.otherPath); break; default: throw new IllegalArgumentException("wrong page type"); } return url.toString(); } @Override public UrlPageModel parseUrl(String url) throws IllegalArgumentException { String path = UrlPathUtils.getUrlPath(url, getAllDomains()); if (path == null) throw new IllegalArgumentException("wrong domain"); UrlPageModel model = new UrlPageModel(); model.chanName = getChanName(); if (path.length() == 0) { model.type = UrlPageModel.TYPE_INDEXPAGE; return model; } Matcher threadPage = Pattern.compile("^([^/]+)/(\\d+)(?:#(\\d+))?").matcher(path); if (threadPage.find()) { model.type = UrlPageModel.TYPE_THREADPAGE; model.boardName = threadPage.group(1); model.threadNumber = threadPage.group(2); model.postNumber = threadPage.group(3); return model; } Matcher boardPage = Pattern.compile("^([^/]+)(?:/page/(\\d+))?").matcher(path); if (boardPage.find()) { model.type = UrlPageModel.TYPE_BOARDPAGE; model.boardName = boardPage.group(1); String page = boardPage.group(2); model.boardPage = (page == null) ? 0 : Integer.parseInt(page); return model; } model.type = UrlPageModel.TYPE_OTHERPAGE; model.otherPath = path; return model; } protected static class MonabaAntibot { public static List<Pair<String, String>> getFormValues(String url, CancellableTask task, HttpClient httpClient) throws Exception { return getFormValues(url, HttpRequestModel.DEFAULT_GET, task, httpClient, "<form class=\"plain-post-form\"", "<div id=\"board-info\""); } public static List<Pair<String, String>> getFormValues(String url, HttpRequestModel requestModel, CancellableTask task, HttpClient client, String startForm, String endForm) throws Exception { MonabaAntibot reader = null; HttpRequestModel request = requestModel; HttpResponseModel response = null; try { response = HttpStreamer.getInstance().getFromUrl(url, request, client, null, task); reader = new MonabaAntibot(response.stream, startForm, endForm); return reader.readForm(); } finally { if (reader != null) { try { reader.close(); } catch (Exception e) {} } if (response != null) response.release(); } } private StringBuilder readBuffer = new StringBuilder(); private List<Pair<String, String>> result = null; private String currentName = null; private String currentValue = null; private String currentType = null; private boolean currentTextarea = false; private boolean currentReading = false; private final char[] start; private final char[][] filters; private final Reader in; private static final int FILTER_INPUT_OPEN = 0; private static final int FILTER_TEXTAREA_OPEN = 1; private static final int FILTER_SELECT_OPEN = 2; private static final int FILTER_NAME_OPEN = 3; private static final int FILTER_VALUE_OPEN = 4; private static final int FILTER_TYPE_OPEN = 5; private static final int FILTER_CLASS_OPEN = 6; private static final int FILTER_TAG_CLOSE = 7; private MonabaAntibot(InputStream in, String start, String end) { this.start = start.toCharArray(); this.filters = new char[][] { "<input".toCharArray(), "<textarea".toCharArray(), "<select".toCharArray(), "name=\"".toCharArray(), "value=\"".toCharArray(), "type=\"".toCharArray(), "class=\"".toCharArray(), ">".toCharArray(), end.toCharArray() }; this.in = new BufferedReader(new InputStreamReader(in)); } private List<Pair<String, String>> readForm() throws IOException { result = new ArrayList<>(); skipUntilSequence(start); int filtersCount = filters.length; int[] pos = new int[filtersCount]; int[] len = new int[filtersCount]; for (int i=0; i<filtersCount; ++i) len[i] = filters[i].length; int curChar; while ((curChar = in.read()) != -1) { for (int i=0; i<filtersCount; ++i) { if (curChar == filters[i][pos[i]]) { ++pos[i]; if (pos[i] == len[i]) { if (i == filtersCount - 1) { return result; } handleFilter(i); pos[i] = 0; } } else { if (pos[i] != 0) pos[i] = curChar == filters[i][0] ? 1 : 0; } } } return result; } private void handleFilter(int i) throws IOException { switch (i) { case FILTER_INPUT_OPEN: case FILTER_SELECT_OPEN: currentReading = true; currentTextarea = false; break; case FILTER_TEXTAREA_OPEN: currentReading = true; currentTextarea = true; break; case FILTER_NAME_OPEN: currentName = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray())); break; case FILTER_VALUE_OPEN: currentValue = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray())); break; case FILTER_CLASS_OPEN: case FILTER_TYPE_OPEN: currentType = StringEscapeUtils.unescapeHtml4(readUntilSequence("\"".toCharArray())); break; case FILTER_TAG_CLOSE: if (currentTextarea) { currentValue = StringEscapeUtils.unescapeHtml4(readUntilSequence("<".toCharArray())); } if (currentReading && currentName != null) { result.add(Pair.of(currentName, currentValue != null ? currentValue : currentType != null ? currentType : "")); } currentName = null; currentValue = null; currentType = null; currentReading = false; currentTextarea = false; break; } } private void skipUntilSequence(char[] sequence) throws IOException { int len = sequence.length; if (len == 0) return; int pos = 0; int curChar; while ((curChar = in.read()) != -1) { if (curChar == sequence[pos]) { ++pos; if (pos == len) break; } else { if (pos != 0) pos = curChar == sequence[0] ? 1 : 0; } } } private String readUntilSequence(char[] sequence) throws IOException { int len = sequence.length; if (len == 0) return ""; readBuffer.setLength(0); int pos = 0; int curChar; while ((curChar = in.read()) != -1) { readBuffer.append((char) curChar); if (curChar == sequence[pos]) { ++pos; if (pos == len) break; } else { if (pos != 0) pos = curChar == sequence[0] ? 1 : 0; } } int buflen = readBuffer.length(); if (buflen >= len) { readBuffer.setLength(buflen - len); return readBuffer.toString(); } else { return ""; } } public void close() throws IOException { in.close(); } } }
177768_1
package com.ozguryazilim.telve.calendar; import com.ozguryazilim.telve.dashboard.AbstractDashlet; import com.ozguryazilim.telve.dashboard.Dashlet; import com.ozguryazilim.telve.dashboard.DashletCapability; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.inject.Inject; import org.apache.deltaspike.core.api.provider.BeanProvider; import org.joda.time.LocalDate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Yakın tarihte yapılması gereken olayları sunar. * * @author Hakan Uygun */ @Dashlet(capability = {DashletCapability.canHide, DashletCapability.canMinimize, DashletCapability.canRefresh}) public class EventsDashlet extends AbstractDashlet { private static final Logger LOG = LoggerFactory.getLogger(EventsDashlet.class); @Inject private CalendarFilterModel filterModel; private LocalDate date; List<CalendarEventModel> todayEvents; List<CalendarEventModel> tomorrowEvents; List<CalendarEventModel> soonEvents; @Override public void load() { date = new LocalDate(); } @Override public void refresh() { todayEvents = null; tomorrowEvents = null; soonEvents = null; } public Date getDate() { return date.toDate(); } public List<CalendarEventModel> getTodayEvents() { if (todayEvents == null) { todayEvents = new ArrayList<>(); populateEvents(todayEvents, date.toDate(), date.plusDays(1).toDate()); //todayEvents = eventStore.getEvents(date.toDate(), date.plusDays(1).toDate()); } return todayEvents; } public List<CalendarEventModel> getTomorrowEvents() { if (tomorrowEvents == null) { tomorrowEvents = new ArrayList<>(); populateEvents(tomorrowEvents, date.plusDays(1).toDate(), date.plusDays(2).toDate()); //tomorrowEvents = eventStore.getEvents(date.plusDays(1).toDate(), date.plusDays(2).toDate()); } return tomorrowEvents; } public List<CalendarEventModel> getSoonEvents() { if (soonEvents == null) { soonEvents = new ArrayList<>(); populateEvents(soonEvents, date.plusDays(2).toDate(), date.plusDays(7).toDate()); //soonEvents = eventStore.getEvents(date.plusDays(2).toDate(), date.plusDays(7).toDate()); } return soonEvents; } public void nextDay() { date = date.plusDays(1); refresh(); } public void prevDay() { date = date.minusDays(1); refresh(); } public void toDay() { date = new LocalDate(); refresh(); } public LocalDate getDateTime() { return date; } protected void populateEvents(List<CalendarEventModel> list, Date start, Date end) { for (String s : filterModel.getCalendarSources()) { try { CalendarEventSource cec = (CalendarEventSource) BeanProvider.getContextualReference(s); List<CalendarEventModel> res = cec.getEvents(start, end); for (CalendarEventModel em : res) { em.setSource(s); } list.addAll(res); } catch (Exception e) { LOG.warn("Event Source not found {}", s); } } } public void onEventSelect(String source, String eventId) { try { CalendarEventSource cec = (CalendarEventSource) BeanProvider.getContextualReference(source); cec.process(eventId); } catch (Exception e) { LOG.warn("Event Source not found {}", source); } } }
ozguryazilimas/telve4
modules/telve-calendar/src/main/java/com/ozguryazilim/telve/calendar/EventsDashlet.java
1,112
//todayEvents = eventStore.getEvents(date.toDate(), date.plusDays(1).toDate());
line_comment
nl
package com.ozguryazilim.telve.calendar; import com.ozguryazilim.telve.dashboard.AbstractDashlet; import com.ozguryazilim.telve.dashboard.Dashlet; import com.ozguryazilim.telve.dashboard.DashletCapability; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.inject.Inject; import org.apache.deltaspike.core.api.provider.BeanProvider; import org.joda.time.LocalDate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Yakın tarihte yapılması gereken olayları sunar. * * @author Hakan Uygun */ @Dashlet(capability = {DashletCapability.canHide, DashletCapability.canMinimize, DashletCapability.canRefresh}) public class EventsDashlet extends AbstractDashlet { private static final Logger LOG = LoggerFactory.getLogger(EventsDashlet.class); @Inject private CalendarFilterModel filterModel; private LocalDate date; List<CalendarEventModel> todayEvents; List<CalendarEventModel> tomorrowEvents; List<CalendarEventModel> soonEvents; @Override public void load() { date = new LocalDate(); } @Override public void refresh() { todayEvents = null; tomorrowEvents = null; soonEvents = null; } public Date getDate() { return date.toDate(); } public List<CalendarEventModel> getTodayEvents() { if (todayEvents == null) { todayEvents = new ArrayList<>(); populateEvents(todayEvents, date.toDate(), date.plusDays(1).toDate()); //todayEvents =<SUF> } return todayEvents; } public List<CalendarEventModel> getTomorrowEvents() { if (tomorrowEvents == null) { tomorrowEvents = new ArrayList<>(); populateEvents(tomorrowEvents, date.plusDays(1).toDate(), date.plusDays(2).toDate()); //tomorrowEvents = eventStore.getEvents(date.plusDays(1).toDate(), date.plusDays(2).toDate()); } return tomorrowEvents; } public List<CalendarEventModel> getSoonEvents() { if (soonEvents == null) { soonEvents = new ArrayList<>(); populateEvents(soonEvents, date.plusDays(2).toDate(), date.plusDays(7).toDate()); //soonEvents = eventStore.getEvents(date.plusDays(2).toDate(), date.plusDays(7).toDate()); } return soonEvents; } public void nextDay() { date = date.plusDays(1); refresh(); } public void prevDay() { date = date.minusDays(1); refresh(); } public void toDay() { date = new LocalDate(); refresh(); } public LocalDate getDateTime() { return date; } protected void populateEvents(List<CalendarEventModel> list, Date start, Date end) { for (String s : filterModel.getCalendarSources()) { try { CalendarEventSource cec = (CalendarEventSource) BeanProvider.getContextualReference(s); List<CalendarEventModel> res = cec.getEvents(start, end); for (CalendarEventModel em : res) { em.setSource(s); } list.addAll(res); } catch (Exception e) { LOG.warn("Event Source not found {}", s); } } } public void onEventSelect(String source, String eventId) { try { CalendarEventSource cec = (CalendarEventSource) BeanProvider.getContextualReference(source); cec.process(eventId); } catch (Exception e) { LOG.warn("Event Source not found {}", source); } } }
105965_2
package de.dhbwka.java.exercise.classes.swapgame; import java.awt.Color; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Spielfeld */ public class Spielfeld { // #region private members private final int SIZE = 9; private final int COLOR_COUNT = 7; @SuppressWarnings("unused") private Color[] colors = generateColors(COLOR_COUNT); private Integer[][] matchfield = new Integer[SIZE][SIZE]; // [Spalte][Zeile] private int points; private PropertyChangeSupport pointsChange = new PropertyChangeSupport(points); private PropertyChangeSupport matchfieldChanged = new PropertyChangeSupport(matchfield); // #endregion private members // #region constructors public Spielfeld() { Random r = new Random(); for (Integer[] col : matchfield) for (int i = 0; i < SIZE; i++) col[i] = r.nextInt(COLOR_COUNT); calcPoints(); } // #endregion constructors // #region private methods /** * Generiert {@code i} unterschiedliche Farben * * @param i Anzahl der zu generierenden Farben * @return Liste an Farben */ private Color[] generateColors(int i) { Color[] colors = new Color[i]; int offSet = Integer.parseInt("FFFFFF", 16) / i; for (int c = 0; c < i; c++) colors[c] = new Color(offSet * (c + 1)); return colors; } /** * Berechnet, fuer die aktuelle Spielsituation erzielbare Punkte. Wenn ja, * werden die Felder aufgeloest. Felder rutschen nach / werden neu generiert und * es werden dadurch neue moegliche Punkte berechnet. * * @return insgesamt erzielte Punkte */ private int calcPoints() { Position[] pos = getPointFields(); if (pos.length > 0) { // Zerstörte Felder auf null setzen for (Position p : pos) setFieldValue(p, null); Integer[][] oldMatchfield = this.matchfield; // null Felder nach vorne sortieren for (Integer[] col : matchfield) { java.util.Arrays.sort(col, (a, b) -> (a == null ? -1 : 1) - (b == null ? -1 : 1)); // null Felder neu befüllen Random r = new Random(); for (int i = 0; i < SIZE; i++) { if (col[i] != null) break; col[i] = r.nextInt(COLOR_COUNT); } } matchfieldChanged.firePropertyChange("matchfield", oldMatchfield, this.matchfield); return (10 * pos.length) + calcPoints(); } return 0; } /** * Liste von Feldern, durch welche Punkte erzielt werden. mehrfache Aufführugen * sind möglich, wenn das Feld sowohl Senkrecht als auch Wagerecht Punkte erzielt. * * @return Liste mit Felder, fuer die Punkte vergeben werden */ private Position[] getPointFields() { List<Position> positions = new ArrayList<Position>(); for (int c = 0; c < SIZE; c++) { for (int r = 0; r < SIZE; r++) { positions = searchBlocks(c, r, positions); } // letzter Block, incl. beginnendem [null] entfernen, wenn kein vollständiger // Block int lastBlockSize = positions.size() - positions.lastIndexOf(null); lastBlockSize = lastBlockSize < 0 || lastBlockSize > positions.size() ? positions.size() : lastBlockSize; if (lastBlockSize < 4) positions = positions.subList(0, positions.size() - lastBlockSize); positions.add(null); } for (int r = 0; r < SIZE; r++) { for (int c = 0; c < SIZE; c++) { positions = searchBlocks(c, r, positions); } // letzter Block, incl. beginnendem [null] entfernen, wenn kein vollständiger // Block int lastBlockSize = positions.size() - positions.lastIndexOf(null); lastBlockSize = lastBlockSize < 0 || lastBlockSize > positions.size() ? positions.size() : lastBlockSize; if (lastBlockSize < 4) positions = positions.subList(0, positions.size() - lastBlockSize); positions.add(null); } positions.removeAll(Collections.singleton(null)); return positions.toArray(new Position[positions.size()]); } /** * Vergleicht eine Position auf dem Spielfeld mit den vorherigen. Speichert den * Block ggfs. als Wertbar ab, wenn es min. 3 gleiche Felder in Folge sind. Die * Felder muessen in der Liste mit {@code null} separiert werden. * * @param c aktuelle Spalte * @param r aktuelle Zeile * @param positions Positionsliste, mit bereits erkannten Blöcken * @return neue Positionsliste, da es Probleme mit der Referenz-Liste bei * neuinitialisierung in der Methode gibt. */ private List<Position> searchBlocks(int c, int r, List<Position> positions) { // Wenn dieses Feld das erste ist, oder das vorherige gleich / null ist, kann es // hinzugefügt werden if (positions.size() == 0 || positions.get(positions.size() - 1) == null || getFieldValue(positions.get(positions.size() - 1)) == getFieldValue(c, r)) { positions.add(new Position(c, r)); } else { // wenn min. 3 vorgänger gleich sind, kann null eingefügt werden, um den Block // abzuschließen und mit diesem Feld einen neuen zu beginnen. // ansonsten werden die Vorgänger bis zum Ende des letzten Blocks (null) // gelöscht. if (positions.size() < 3) { positions = new ArrayList<Position>(); positions.add(null); } else { // min 3 gleiche: null einfügen; Integer curVal = getFieldValue(positions.get(positions.size() - 1)); if (curVal == getFieldValue(positions.get(positions.size() - 2)) && curVal == getFieldValue(positions.get(positions.size() - 3))) positions.add(null); else positions = positions.subList(0, positions.lastIndexOf(null) + 1); } // dieses Feld hinzufügen positions.add(new Position(c, r)); } return positions; } private Integer getFieldValue(Position p) { return p == null ? null : getFieldValue(p.getColArrayIndex(), p.getRowArrayIndex()); } private Integer getFieldValue(int col, int row) { return matchfield[col][row]; } private void setFieldValue(Position p, Integer value) { if(p == null) return; setFieldValue(p.getColArrayIndex(), p.getRowArrayIndex(), value); } private void setFieldValue(int col, int row, Integer value) { matchfield[col][row] = value; } private void increasePoints(int points) { if (points != 0) pointsChange.firePropertyChange("points", this.points, this.points += points); } // #endregion private methods // #region public methods /** * Tauscht zwei Felder auf dem Spielfeld, falls dadurch Punkte erzielt werden * koennen. * * @param pos1 Zeilennummer & Spalte des ersten Feldes * @param pos2 Zeilennummer & Spalte des zweiten Feldes * @return durch diesen Spielzug verdiente Punkte. 0 für einen ungueltigen * Spielzug. */ public int swap(Position pos1, Position pos2) { // Nur tauschen, wenn die Felder nebeneinander liegen if (Math.abs(pos1.getColArrayIndex() - pos2.getColArrayIndex()) + Math.abs(pos1.getRowArrayIndex() - pos2.getRowArrayIndex()) != 1) return 0; Integer cell1 = getFieldValue(pos1); Integer cell2 = getFieldValue(pos2); setFieldValue(pos1, cell2); setFieldValue(pos2, cell1); int points = calcPoints(); if (points == 0) { setFieldValue(pos1, cell1); setFieldValue(pos2, cell2); } else { increasePoints(points); } return points; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" "); for (int i = 0; i < SIZE; i++) sb.append(new Position(i, i).getCol() + " "); sb.append("\r\n"); sb.append(" __________________\r\n"); for (int i = 0; i < SIZE; i++) { sb.append((i + 1) + "| "); for (int j = 0; j < SIZE; j++) { sb.append(matchfield[j][i] + " "); } sb.append("\r\n"); } sb.append("Punkte: [" + points + "]"); return sb.toString(); } public void addPointsChangeListener(PropertyChangeListener listener) { pointsChange.addPropertyChangeListener(listener); } public void removePointsChangeListener(PropertyChangeListener listener) { pointsChange.removePropertyChangeListener(listener); } public void addMatchfieldChangeListener(PropertyChangeListener listener) { matchfieldChanged.addPropertyChangeListener(listener); } public void removeMatchfieldChangeListener(PropertyChangeListener listener) { matchfieldChanged.removePropertyChangeListener(listener); } // #endregion public methods }
pa-ssch/study-java-exercises
src/de/dhbwka/java/exercise/classes/swapgame/Spielfeld.java
2,749
// #region private methods
line_comment
nl
package de.dhbwka.java.exercise.classes.swapgame; import java.awt.Color; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Spielfeld */ public class Spielfeld { // #region private members private final int SIZE = 9; private final int COLOR_COUNT = 7; @SuppressWarnings("unused") private Color[] colors = generateColors(COLOR_COUNT); private Integer[][] matchfield = new Integer[SIZE][SIZE]; // [Spalte][Zeile] private int points; private PropertyChangeSupport pointsChange = new PropertyChangeSupport(points); private PropertyChangeSupport matchfieldChanged = new PropertyChangeSupport(matchfield); // #endregion private members // #region constructors public Spielfeld() { Random r = new Random(); for (Integer[] col : matchfield) for (int i = 0; i < SIZE; i++) col[i] = r.nextInt(COLOR_COUNT); calcPoints(); } // #endregion constructors // #region private<SUF> /** * Generiert {@code i} unterschiedliche Farben * * @param i Anzahl der zu generierenden Farben * @return Liste an Farben */ private Color[] generateColors(int i) { Color[] colors = new Color[i]; int offSet = Integer.parseInt("FFFFFF", 16) / i; for (int c = 0; c < i; c++) colors[c] = new Color(offSet * (c + 1)); return colors; } /** * Berechnet, fuer die aktuelle Spielsituation erzielbare Punkte. Wenn ja, * werden die Felder aufgeloest. Felder rutschen nach / werden neu generiert und * es werden dadurch neue moegliche Punkte berechnet. * * @return insgesamt erzielte Punkte */ private int calcPoints() { Position[] pos = getPointFields(); if (pos.length > 0) { // Zerstörte Felder auf null setzen for (Position p : pos) setFieldValue(p, null); Integer[][] oldMatchfield = this.matchfield; // null Felder nach vorne sortieren for (Integer[] col : matchfield) { java.util.Arrays.sort(col, (a, b) -> (a == null ? -1 : 1) - (b == null ? -1 : 1)); // null Felder neu befüllen Random r = new Random(); for (int i = 0; i < SIZE; i++) { if (col[i] != null) break; col[i] = r.nextInt(COLOR_COUNT); } } matchfieldChanged.firePropertyChange("matchfield", oldMatchfield, this.matchfield); return (10 * pos.length) + calcPoints(); } return 0; } /** * Liste von Feldern, durch welche Punkte erzielt werden. mehrfache Aufführugen * sind möglich, wenn das Feld sowohl Senkrecht als auch Wagerecht Punkte erzielt. * * @return Liste mit Felder, fuer die Punkte vergeben werden */ private Position[] getPointFields() { List<Position> positions = new ArrayList<Position>(); for (int c = 0; c < SIZE; c++) { for (int r = 0; r < SIZE; r++) { positions = searchBlocks(c, r, positions); } // letzter Block, incl. beginnendem [null] entfernen, wenn kein vollständiger // Block int lastBlockSize = positions.size() - positions.lastIndexOf(null); lastBlockSize = lastBlockSize < 0 || lastBlockSize > positions.size() ? positions.size() : lastBlockSize; if (lastBlockSize < 4) positions = positions.subList(0, positions.size() - lastBlockSize); positions.add(null); } for (int r = 0; r < SIZE; r++) { for (int c = 0; c < SIZE; c++) { positions = searchBlocks(c, r, positions); } // letzter Block, incl. beginnendem [null] entfernen, wenn kein vollständiger // Block int lastBlockSize = positions.size() - positions.lastIndexOf(null); lastBlockSize = lastBlockSize < 0 || lastBlockSize > positions.size() ? positions.size() : lastBlockSize; if (lastBlockSize < 4) positions = positions.subList(0, positions.size() - lastBlockSize); positions.add(null); } positions.removeAll(Collections.singleton(null)); return positions.toArray(new Position[positions.size()]); } /** * Vergleicht eine Position auf dem Spielfeld mit den vorherigen. Speichert den * Block ggfs. als Wertbar ab, wenn es min. 3 gleiche Felder in Folge sind. Die * Felder muessen in der Liste mit {@code null} separiert werden. * * @param c aktuelle Spalte * @param r aktuelle Zeile * @param positions Positionsliste, mit bereits erkannten Blöcken * @return neue Positionsliste, da es Probleme mit der Referenz-Liste bei * neuinitialisierung in der Methode gibt. */ private List<Position> searchBlocks(int c, int r, List<Position> positions) { // Wenn dieses Feld das erste ist, oder das vorherige gleich / null ist, kann es // hinzugefügt werden if (positions.size() == 0 || positions.get(positions.size() - 1) == null || getFieldValue(positions.get(positions.size() - 1)) == getFieldValue(c, r)) { positions.add(new Position(c, r)); } else { // wenn min. 3 vorgänger gleich sind, kann null eingefügt werden, um den Block // abzuschließen und mit diesem Feld einen neuen zu beginnen. // ansonsten werden die Vorgänger bis zum Ende des letzten Blocks (null) // gelöscht. if (positions.size() < 3) { positions = new ArrayList<Position>(); positions.add(null); } else { // min 3 gleiche: null einfügen; Integer curVal = getFieldValue(positions.get(positions.size() - 1)); if (curVal == getFieldValue(positions.get(positions.size() - 2)) && curVal == getFieldValue(positions.get(positions.size() - 3))) positions.add(null); else positions = positions.subList(0, positions.lastIndexOf(null) + 1); } // dieses Feld hinzufügen positions.add(new Position(c, r)); } return positions; } private Integer getFieldValue(Position p) { return p == null ? null : getFieldValue(p.getColArrayIndex(), p.getRowArrayIndex()); } private Integer getFieldValue(int col, int row) { return matchfield[col][row]; } private void setFieldValue(Position p, Integer value) { if(p == null) return; setFieldValue(p.getColArrayIndex(), p.getRowArrayIndex(), value); } private void setFieldValue(int col, int row, Integer value) { matchfield[col][row] = value; } private void increasePoints(int points) { if (points != 0) pointsChange.firePropertyChange("points", this.points, this.points += points); } // #endregion private methods // #region public methods /** * Tauscht zwei Felder auf dem Spielfeld, falls dadurch Punkte erzielt werden * koennen. * * @param pos1 Zeilennummer & Spalte des ersten Feldes * @param pos2 Zeilennummer & Spalte des zweiten Feldes * @return durch diesen Spielzug verdiente Punkte. 0 für einen ungueltigen * Spielzug. */ public int swap(Position pos1, Position pos2) { // Nur tauschen, wenn die Felder nebeneinander liegen if (Math.abs(pos1.getColArrayIndex() - pos2.getColArrayIndex()) + Math.abs(pos1.getRowArrayIndex() - pos2.getRowArrayIndex()) != 1) return 0; Integer cell1 = getFieldValue(pos1); Integer cell2 = getFieldValue(pos2); setFieldValue(pos1, cell2); setFieldValue(pos2, cell1); int points = calcPoints(); if (points == 0) { setFieldValue(pos1, cell1); setFieldValue(pos2, cell2); } else { increasePoints(points); } return points; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" "); for (int i = 0; i < SIZE; i++) sb.append(new Position(i, i).getCol() + " "); sb.append("\r\n"); sb.append(" __________________\r\n"); for (int i = 0; i < SIZE; i++) { sb.append((i + 1) + "| "); for (int j = 0; j < SIZE; j++) { sb.append(matchfield[j][i] + " "); } sb.append("\r\n"); } sb.append("Punkte: [" + points + "]"); return sb.toString(); } public void addPointsChangeListener(PropertyChangeListener listener) { pointsChange.addPropertyChangeListener(listener); } public void removePointsChangeListener(PropertyChangeListener listener) { pointsChange.removePropertyChangeListener(listener); } public void addMatchfieldChangeListener(PropertyChangeListener listener) { matchfieldChanged.addPropertyChangeListener(listener); } public void removeMatchfieldChangeListener(PropertyChangeListener listener) { matchfieldChanged.removePropertyChangeListener(listener); } // #endregion public methods }
10274_17
package jmri.jmrix.zimo; /** * Represents a single command or response to the Zimo Binary Protocol. * <p> * Content is represented with ints to avoid the problems with sign-extension * that bytes have, and because a Java char is actually a variable number of * bytes in Unicode. * * @author Kevin Dickerson Copyright (C) 2014 * * Adapted by Sip Bosch for use with zimo MX-1 * */ public class Mx1Message extends jmri.jmrix.NetMessage { public Mx1Message(int len) { this(len, Mx1Packetizer.ASCII); } /** * Create a new object, representing a specific-length message. * * @param len Total bytes in message, including opcode and * error-detection byte. * @param protocol one of {@link Mx1Packetizer#ASCII} or * {@link Mx1Packetizer#BINARY} */ public Mx1Message(int len, boolean protocol) { super(len); this.protocol = protocol; if (!protocol) { if (len > 15 || len < 0) { log.error("Invalid length in ctor: {}", len); } } } boolean protocol = Mx1Packetizer.ASCII; //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(Integer[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, contents[i]); } } //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(byte[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, (contents[i] & 0xff)); } } public boolean getLongMessage() { if (protocol == Mx1Packetizer.BINARY) { if ((getElement(1) & 0x80) == 0x80) { return true; } } return false; } final static int PRIMARY = 0x00; final static int ACKREP1 = 0x40; final static int REPLY2 = 0x20; final static int ACK2 = 0x60; /** * Indicates where the message is to/from in the header byte. * <p> * Up to JMRI 4.3.5, this was doing {@code ((mod & MX1) == MX1)} for the * first test, which is really 0 == 0 and always true. At that point it was * changed to just check the bottom two bits. * * @return one of {@link #MX1}, {@link #MX8}, {@link #MX9} or 0x0F */ public int getModule() { int mod = getElement(1) & 0x0F; if ((mod & 0x03) == MX1) { return MX1; } if ((mod & 0x03) == MX8) { return MX8; } if ((mod & 0x03) == MX9) { return MX9; } return mod; } public int getMessageType() { return getElement(1) & 0x60; } public int getPrimaryMessage() { return getElement(2); } /** * Message to/from Command Station MX1 */ static final int MX1 = 0x00; /** * Message to/from Accessory module MX8 */ static final int MX8 = 0x01; /** * Message to/from Track Section module MX9 */ static final int MX9 = 0x02; /** * Indicates the message source is a command station. {@value #CS} * * @see #messageSource() */ final static boolean CS = true; /** * Indicates the message source is a command station. {@value #PC} * * @see #messageSource() */ final static boolean PC = false; /** * Indicates the source of the message. * * @return {@link #PC} or {@link #CS} */ public boolean messageSource() { if ((getElement(0) & 0x08) == 0x08) { return PC; } return CS; } long timeStamp = 0L; protected long getTimeStamp() { return timeStamp; } protected void setTimeStamp(long ts) { timeStamp = ts; } int retries = 3; public int getRetry() { return retries; } public void setRetries(int i) { retries = i; } //byte sequenceNo = 0x00; public boolean replyL1Expected() { return true; } byte[] rawPacket; public void setRawPacket(byte[] b) { rawPacket = b; } protected byte[] getRawPacket() { return rawPacket; } public void setSequenceNo(byte s) { setElement(0, (s & 0xff)); } public int getSequenceNo() { return (getElement(0) & 0xff); } boolean crcError = false; public void setCRCError() { crcError = true; } public boolean isCRCError() { return crcError; } /** * Check if the message has a valid parity (actually check for CR or LF as * end of message). * * @return true if message has correct parity bit */ @Override public boolean checkParity() { //jmri.util.swing.JmriJOptionPane.showMessageDialog(null, "A-Programma komt tot hier!"); int len = getNumDataElements(); return (getElement(len - 1) == (0x0D | 0x0A)); } // programma komt hier volgens mij nooit // in fact set CR as end of message @Override public void setParity() { jmri.util.swing.JmriJOptionPane.showMessageDialog(null, "B-Programma komt tot hier!"); int len = getNumDataElements(); setElement(len - 1, 0x0D); } // decode messages of a particular form public String getStringMsg() { StringBuilder txt = new StringBuilder(); if (protocol == Mx1Packetizer.BINARY) { if (isCRCError()) { txt.append(" === CRC ERROR === "); } if (getNumDataElements() <= 3) { txt.append("Short Packet "); return txt.toString(); } if ((getElement(1) & 0x10) == 0x10) { txt.append("From PC"); } else { txt.append("From CS"); } txt.append(" Seq ").append(getElement(0) & 0xff); if (getLongMessage()) { txt.append(" (L)"); } else { txt.append(" (S)"); } int offset; switch (getMessageType()) { case PRIMARY: txt.append(" Prim"); break; case ACKREP1: txt.append(" Ack/Reply 1"); break; case REPLY2: txt.append(" Reply 2"); break; case ACK2: txt.append(" Ack 2"); break; default: txt.append(" Unknown msg"); break; } if (getModule() == MX1) { //was (getElement(1)&0x00) == 0x00 txt.append(" to/from CS (MX1)"); switch (getPrimaryMessage()) { //was getElement(2) case TRACKCTL: offset = 0; if (getMessageType() == ACKREP1) { offset++; } txt.append(" Track Control "); if ((getElement(3 + offset) & 0x03) == 0x03) { txt.append(" Query Track Status "); } else if ((getElement(3 + offset) & 0x01) == 0x01) { txt.append(" Turn Track Off "); } else if ((getElement(3 + offset) & 0x02) == 0x02) { txt.append(" Turn Track On "); } else { txt.append(" Stop All Locos "); } break; case 3: txt.append(" Loco Control : "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(6) & 0x20) == 0x20) ? " Fwd " : " Rev "); txt.append(((getElement(6) & 0x10) == 0x10) ? " F0: On " : " F0: Off "); txt.append(decodeFunctionStates(getElement(7), getElement(8))); } break; case 4: txt.append(" Loco Funct "); break; case 5: txt.append(" Loco Acc/Dec "); break; case 6: txt.append(" Shuttle "); break; case 7: txt.append(" Accessory "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(5) & 0x04) == 0x04) ? " Thrown " : " Closed "); } break; case 8: txt.append(" Loco Status "); break; case 9: txt.append(" Acc Status "); break; case 10: txt.append(" Address Control "); break; case 11: txt.append(" CS State "); break; case 12: txt.append(" Read/Write CS CV "); break; case 13: txt.append(" CS Equip Query "); break; case 17: txt.append(" Tool Type "); break; case PROGCMD: offset = 0; if (getMessageType() == ACKREP1) { txt.append(" Prog CV "); break; } if (getMessageType() == REPLY2) { offset++; } if (getMessageType() == ACK2) { txt.append("Ack to CS Message"); break; } if (getNumDataElements() == 7 && getMessageType() == ACKREP1) { txt.append(" Error Occured "); txt.append(getErrorCode(getElement(6))); txt.append(" Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); break; } /*if(getNumDataElements()<7){ txt.append(" Ack L1 "); break; }*/ if ((getMessageType() == PRIMARY && getNumDataElements() == 8)) { txt.append(" Write CV "); } else { txt.append(" Read CV "); } txt.append("Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); if ((getElement(3 + offset) & 0x80) == 0x80) { txt.append(" DCC"); } int cv = (((getElement(5 + offset) & 0xff) << 8) + (getElement(6 + offset) & 0xff)); txt.append(" CV: ").append(cv); if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet txt.append(" Set To: ").append(getElement(7 + offset) & 0xff); } break; case 254: txt.append(" Cur Acc Memory "); break; case 255: txt.append(" Cur Loco Memory "); break; default: txt.append(" Unknown "); } } else if ((getElement(1) & 0x01) == 0x01) { txt.append(" to/from Accessory Mod (MX8)"); } else if ((getElement(1) & 0x02) == 0x02) { txt.append(" to/from Track Section (MX9)"); } else { txt.append(" unknown"); } } //int type = getElement(2); return txt.toString(); } private String decodeFunctionStates(int cData2, int cData3) { StringBuilder txt = new StringBuilder(); txt.append(((cData2 & 0x1) == 0x1) ? " F1: On " : " F1: Off "); txt.append(((cData2 & 0x2) == 0x2) ? " F2: On " : " F2: Off "); txt.append(((cData2 & 0x4) == 0x4) ? " F3: On " : " F3: Off "); txt.append(((cData2 & 0x8) == 0x8) ? " F4: On " : " F4: Off "); txt.append(((cData2 & 0x10) == 0x10) ? " F5: On " : " F5: Off "); txt.append(((cData2 & 0x20) == 0x20) ? " F6: On " : " F6: Off "); txt.append(((cData2 & 0x40) == 0x40) ? " F7: On " : " F7: Off "); txt.append(((cData2 & 0x80) == 0x80) ? " F8: On " : " F8: Off "); txt.append(((cData3 & 0x1) == 0x1) ? " F9: On " : " F9: Off "); txt.append(((cData3 & 0x2) == 0x2) ? " F10: On " : " F10: Off "); txt.append(((cData3 & 0x4) == 0x4) ? " F11: On " : " F11: Off "); txt.append(((cData3 & 0x8) == 0x8) ? " F12: On " : " F12: Off "); return txt.toString(); } public int getLocoAddress() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() == (4 + offset)) { return getLocoAddress(getElement(3 + offset), getElement(4 + offset)); } return -1; } public int getCvValue() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet return (getElement(7 + offset) & 0xff); } return -1; } int getLocoAddress(int hi, int lo) { hi = hi & 0x3F; if (hi == 0) { return lo; } else { hi = (((hi & 255) - 192) << 8); hi = hi + (lo & 255); return hi; } } String getErrorCode(int i) { switch (i) { case NO_ERROR: return "No Error"; case ERR_ADDRESS: return "Invalid Address"; case ERR_INDEX: return "Invalid Index"; case ERR_FORWARD: return "Could not be Forwarded"; case ERR_BUSY: return "CMD Busy"; case ERR_NO_MOT: return "Motorola Jump Off"; case ERR_NO_DCC: return "DCC Jump Off"; case ERR_CV_ADDRESS: return "Invalid CV"; case ERR_SECTION: return "Invalid Section"; case ERR_NO_MODUL: return "No Module Found"; case ERR_MESSAGE: return "Error in Message"; case ERR_SPEED: return "Invalid Speed"; default: return "Unknown Error"; } } final static int NO_ERROR = 0x00; final static int ERR_ADDRESS = 0x01; final static int ERR_INDEX = 0x02; final static int ERR_FORWARD = 0x03; final static int ERR_BUSY = 0x04; final static int ERR_NO_MOT = 0x05; final static int ERR_NO_DCC = 0x06; final static int ERR_CV_ADDRESS = 0x07; final static int ERR_SECTION = 0x08; final static int ERR_NO_MODUL = 0x09; final static int ERR_MESSAGE = 0x0a; final static int ERR_SPEED = 0x0b; final static int TRACKCTL = 0x02; final static int PROGCMD = 0x13; final static int LOCOCMD = 0x03; final static int ACCCMD = 0x07; static public Mx1Message getCmdStnDetails() { Mx1Message m = new Mx1Message(4); m.setElement(1, 0x10); m.setElement(2, 0x13); m.setElement(3, 0x00); return m; } /** * Set Track Power Off/Emergency Stop * * @return MrcMessage */ static public Mx1Message setPowerOff() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x01); return m; } static public Mx1Message setPowerOn() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x02); return m; } static public Mx1Message getTrackStatus() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x03); return m; } /** * Create a message to read or write a CV. * * @param locoAddress address of the loco * @param cv CV to read or write * @param value value to write to CV, if -1 CV is read * @param dcc true if decoder is DCC; false if decoder is Motorola * @return a message to read or write a CV */ // javadoc did indicate locoAddress could be blank to use programming track, but that's not possible with an int static public Mx1Message getDecProgCmd(int locoAddress, int cv, int value, boolean dcc) { Mx1Message m; if (value == -1) { m = new Mx1Message(7, Mx1Packetizer.BINARY); } else { m = new Mx1Message(8, Mx1Packetizer.BINARY); } m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, PROGCMD); int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, cv >> 8); m.setElement(6, cv & 0xff); if (value != -1) { m.setElement(7, value); } return m; } /** * Create a locomotive control message. * * @param locoAddress address of the loco * @param speed Speed Step in the actual Speed Step System * @param dcc true if decoder is DCC; false if decoder is Motorola * @param cData1 ??? * @param cData2 functions output 0-7 * @param cData3 functions output 9-12 * @return message controlling a locomotive */ static public Mx1Message getLocoControl(int locoAddress, int speed, boolean dcc, int cData1, int cData2, int cData3) { Mx1Message m = new Mx1Message(9, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, LOCOCMD); //High add 80 to indicate DCC int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, speed); m.setElement(6, cData1); m.setElement(7, cData2); m.setElement(8, cData3); return m; } static public Mx1Message getSwitchMsg(int accAddress, int setting, boolean dcc) { Mx1Message m = new Mx1Message(6, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, ACCCMD); //High add 80 to indicate DCC int accHi = accAddress >> 8; if (dcc) { accHi = accHi + 128; } else { accHi = accHi + 64; } m.setElement(3, (accHi)); m.setElement(4, (accAddress & 0xff)); m.setElement(5, 0x00); if (setting == jmri.Turnout.THROWN) { m.setElement(5, 0x04); } return m; } private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Mx1Message.class); }
pabender/JMRI
java/src/jmri/jmrix/zimo/Mx1Message.java
6,423
//was (getElement(1)&0x00) == 0x00
line_comment
nl
package jmri.jmrix.zimo; /** * Represents a single command or response to the Zimo Binary Protocol. * <p> * Content is represented with ints to avoid the problems with sign-extension * that bytes have, and because a Java char is actually a variable number of * bytes in Unicode. * * @author Kevin Dickerson Copyright (C) 2014 * * Adapted by Sip Bosch for use with zimo MX-1 * */ public class Mx1Message extends jmri.jmrix.NetMessage { public Mx1Message(int len) { this(len, Mx1Packetizer.ASCII); } /** * Create a new object, representing a specific-length message. * * @param len Total bytes in message, including opcode and * error-detection byte. * @param protocol one of {@link Mx1Packetizer#ASCII} or * {@link Mx1Packetizer#BINARY} */ public Mx1Message(int len, boolean protocol) { super(len); this.protocol = protocol; if (!protocol) { if (len > 15 || len < 0) { log.error("Invalid length in ctor: {}", len); } } } boolean protocol = Mx1Packetizer.ASCII; //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(Integer[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, contents[i]); } } //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(byte[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, (contents[i] & 0xff)); } } public boolean getLongMessage() { if (protocol == Mx1Packetizer.BINARY) { if ((getElement(1) & 0x80) == 0x80) { return true; } } return false; } final static int PRIMARY = 0x00; final static int ACKREP1 = 0x40; final static int REPLY2 = 0x20; final static int ACK2 = 0x60; /** * Indicates where the message is to/from in the header byte. * <p> * Up to JMRI 4.3.5, this was doing {@code ((mod & MX1) == MX1)} for the * first test, which is really 0 == 0 and always true. At that point it was * changed to just check the bottom two bits. * * @return one of {@link #MX1}, {@link #MX8}, {@link #MX9} or 0x0F */ public int getModule() { int mod = getElement(1) & 0x0F; if ((mod & 0x03) == MX1) { return MX1; } if ((mod & 0x03) == MX8) { return MX8; } if ((mod & 0x03) == MX9) { return MX9; } return mod; } public int getMessageType() { return getElement(1) & 0x60; } public int getPrimaryMessage() { return getElement(2); } /** * Message to/from Command Station MX1 */ static final int MX1 = 0x00; /** * Message to/from Accessory module MX8 */ static final int MX8 = 0x01; /** * Message to/from Track Section module MX9 */ static final int MX9 = 0x02; /** * Indicates the message source is a command station. {@value #CS} * * @see #messageSource() */ final static boolean CS = true; /** * Indicates the message source is a command station. {@value #PC} * * @see #messageSource() */ final static boolean PC = false; /** * Indicates the source of the message. * * @return {@link #PC} or {@link #CS} */ public boolean messageSource() { if ((getElement(0) & 0x08) == 0x08) { return PC; } return CS; } long timeStamp = 0L; protected long getTimeStamp() { return timeStamp; } protected void setTimeStamp(long ts) { timeStamp = ts; } int retries = 3; public int getRetry() { return retries; } public void setRetries(int i) { retries = i; } //byte sequenceNo = 0x00; public boolean replyL1Expected() { return true; } byte[] rawPacket; public void setRawPacket(byte[] b) { rawPacket = b; } protected byte[] getRawPacket() { return rawPacket; } public void setSequenceNo(byte s) { setElement(0, (s & 0xff)); } public int getSequenceNo() { return (getElement(0) & 0xff); } boolean crcError = false; public void setCRCError() { crcError = true; } public boolean isCRCError() { return crcError; } /** * Check if the message has a valid parity (actually check for CR or LF as * end of message). * * @return true if message has correct parity bit */ @Override public boolean checkParity() { //jmri.util.swing.JmriJOptionPane.showMessageDialog(null, "A-Programma komt tot hier!"); int len = getNumDataElements(); return (getElement(len - 1) == (0x0D | 0x0A)); } // programma komt hier volgens mij nooit // in fact set CR as end of message @Override public void setParity() { jmri.util.swing.JmriJOptionPane.showMessageDialog(null, "B-Programma komt tot hier!"); int len = getNumDataElements(); setElement(len - 1, 0x0D); } // decode messages of a particular form public String getStringMsg() { StringBuilder txt = new StringBuilder(); if (protocol == Mx1Packetizer.BINARY) { if (isCRCError()) { txt.append(" === CRC ERROR === "); } if (getNumDataElements() <= 3) { txt.append("Short Packet "); return txt.toString(); } if ((getElement(1) & 0x10) == 0x10) { txt.append("From PC"); } else { txt.append("From CS"); } txt.append(" Seq ").append(getElement(0) & 0xff); if (getLongMessage()) { txt.append(" (L)"); } else { txt.append(" (S)"); } int offset; switch (getMessageType()) { case PRIMARY: txt.append(" Prim"); break; case ACKREP1: txt.append(" Ack/Reply 1"); break; case REPLY2: txt.append(" Reply 2"); break; case ACK2: txt.append(" Ack 2"); break; default: txt.append(" Unknown msg"); break; } if (getModule() == MX1) { //was (getElement(1)&0x00)<SUF> txt.append(" to/from CS (MX1)"); switch (getPrimaryMessage()) { //was getElement(2) case TRACKCTL: offset = 0; if (getMessageType() == ACKREP1) { offset++; } txt.append(" Track Control "); if ((getElement(3 + offset) & 0x03) == 0x03) { txt.append(" Query Track Status "); } else if ((getElement(3 + offset) & 0x01) == 0x01) { txt.append(" Turn Track Off "); } else if ((getElement(3 + offset) & 0x02) == 0x02) { txt.append(" Turn Track On "); } else { txt.append(" Stop All Locos "); } break; case 3: txt.append(" Loco Control : "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(6) & 0x20) == 0x20) ? " Fwd " : " Rev "); txt.append(((getElement(6) & 0x10) == 0x10) ? " F0: On " : " F0: Off "); txt.append(decodeFunctionStates(getElement(7), getElement(8))); } break; case 4: txt.append(" Loco Funct "); break; case 5: txt.append(" Loco Acc/Dec "); break; case 6: txt.append(" Shuttle "); break; case 7: txt.append(" Accessory "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(5) & 0x04) == 0x04) ? " Thrown " : " Closed "); } break; case 8: txt.append(" Loco Status "); break; case 9: txt.append(" Acc Status "); break; case 10: txt.append(" Address Control "); break; case 11: txt.append(" CS State "); break; case 12: txt.append(" Read/Write CS CV "); break; case 13: txt.append(" CS Equip Query "); break; case 17: txt.append(" Tool Type "); break; case PROGCMD: offset = 0; if (getMessageType() == ACKREP1) { txt.append(" Prog CV "); break; } if (getMessageType() == REPLY2) { offset++; } if (getMessageType() == ACK2) { txt.append("Ack to CS Message"); break; } if (getNumDataElements() == 7 && getMessageType() == ACKREP1) { txt.append(" Error Occured "); txt.append(getErrorCode(getElement(6))); txt.append(" Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); break; } /*if(getNumDataElements()<7){ txt.append(" Ack L1 "); break; }*/ if ((getMessageType() == PRIMARY && getNumDataElements() == 8)) { txt.append(" Write CV "); } else { txt.append(" Read CV "); } txt.append("Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); if ((getElement(3 + offset) & 0x80) == 0x80) { txt.append(" DCC"); } int cv = (((getElement(5 + offset) & 0xff) << 8) + (getElement(6 + offset) & 0xff)); txt.append(" CV: ").append(cv); if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet txt.append(" Set To: ").append(getElement(7 + offset) & 0xff); } break; case 254: txt.append(" Cur Acc Memory "); break; case 255: txt.append(" Cur Loco Memory "); break; default: txt.append(" Unknown "); } } else if ((getElement(1) & 0x01) == 0x01) { txt.append(" to/from Accessory Mod (MX8)"); } else if ((getElement(1) & 0x02) == 0x02) { txt.append(" to/from Track Section (MX9)"); } else { txt.append(" unknown"); } } //int type = getElement(2); return txt.toString(); } private String decodeFunctionStates(int cData2, int cData3) { StringBuilder txt = new StringBuilder(); txt.append(((cData2 & 0x1) == 0x1) ? " F1: On " : " F1: Off "); txt.append(((cData2 & 0x2) == 0x2) ? " F2: On " : " F2: Off "); txt.append(((cData2 & 0x4) == 0x4) ? " F3: On " : " F3: Off "); txt.append(((cData2 & 0x8) == 0x8) ? " F4: On " : " F4: Off "); txt.append(((cData2 & 0x10) == 0x10) ? " F5: On " : " F5: Off "); txt.append(((cData2 & 0x20) == 0x20) ? " F6: On " : " F6: Off "); txt.append(((cData2 & 0x40) == 0x40) ? " F7: On " : " F7: Off "); txt.append(((cData2 & 0x80) == 0x80) ? " F8: On " : " F8: Off "); txt.append(((cData3 & 0x1) == 0x1) ? " F9: On " : " F9: Off "); txt.append(((cData3 & 0x2) == 0x2) ? " F10: On " : " F10: Off "); txt.append(((cData3 & 0x4) == 0x4) ? " F11: On " : " F11: Off "); txt.append(((cData3 & 0x8) == 0x8) ? " F12: On " : " F12: Off "); return txt.toString(); } public int getLocoAddress() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() == (4 + offset)) { return getLocoAddress(getElement(3 + offset), getElement(4 + offset)); } return -1; } public int getCvValue() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet return (getElement(7 + offset) & 0xff); } return -1; } int getLocoAddress(int hi, int lo) { hi = hi & 0x3F; if (hi == 0) { return lo; } else { hi = (((hi & 255) - 192) << 8); hi = hi + (lo & 255); return hi; } } String getErrorCode(int i) { switch (i) { case NO_ERROR: return "No Error"; case ERR_ADDRESS: return "Invalid Address"; case ERR_INDEX: return "Invalid Index"; case ERR_FORWARD: return "Could not be Forwarded"; case ERR_BUSY: return "CMD Busy"; case ERR_NO_MOT: return "Motorola Jump Off"; case ERR_NO_DCC: return "DCC Jump Off"; case ERR_CV_ADDRESS: return "Invalid CV"; case ERR_SECTION: return "Invalid Section"; case ERR_NO_MODUL: return "No Module Found"; case ERR_MESSAGE: return "Error in Message"; case ERR_SPEED: return "Invalid Speed"; default: return "Unknown Error"; } } final static int NO_ERROR = 0x00; final static int ERR_ADDRESS = 0x01; final static int ERR_INDEX = 0x02; final static int ERR_FORWARD = 0x03; final static int ERR_BUSY = 0x04; final static int ERR_NO_MOT = 0x05; final static int ERR_NO_DCC = 0x06; final static int ERR_CV_ADDRESS = 0x07; final static int ERR_SECTION = 0x08; final static int ERR_NO_MODUL = 0x09; final static int ERR_MESSAGE = 0x0a; final static int ERR_SPEED = 0x0b; final static int TRACKCTL = 0x02; final static int PROGCMD = 0x13; final static int LOCOCMD = 0x03; final static int ACCCMD = 0x07; static public Mx1Message getCmdStnDetails() { Mx1Message m = new Mx1Message(4); m.setElement(1, 0x10); m.setElement(2, 0x13); m.setElement(3, 0x00); return m; } /** * Set Track Power Off/Emergency Stop * * @return MrcMessage */ static public Mx1Message setPowerOff() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x01); return m; } static public Mx1Message setPowerOn() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x02); return m; } static public Mx1Message getTrackStatus() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x03); return m; } /** * Create a message to read or write a CV. * * @param locoAddress address of the loco * @param cv CV to read or write * @param value value to write to CV, if -1 CV is read * @param dcc true if decoder is DCC; false if decoder is Motorola * @return a message to read or write a CV */ // javadoc did indicate locoAddress could be blank to use programming track, but that's not possible with an int static public Mx1Message getDecProgCmd(int locoAddress, int cv, int value, boolean dcc) { Mx1Message m; if (value == -1) { m = new Mx1Message(7, Mx1Packetizer.BINARY); } else { m = new Mx1Message(8, Mx1Packetizer.BINARY); } m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, PROGCMD); int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, cv >> 8); m.setElement(6, cv & 0xff); if (value != -1) { m.setElement(7, value); } return m; } /** * Create a locomotive control message. * * @param locoAddress address of the loco * @param speed Speed Step in the actual Speed Step System * @param dcc true if decoder is DCC; false if decoder is Motorola * @param cData1 ??? * @param cData2 functions output 0-7 * @param cData3 functions output 9-12 * @return message controlling a locomotive */ static public Mx1Message getLocoControl(int locoAddress, int speed, boolean dcc, int cData1, int cData2, int cData3) { Mx1Message m = new Mx1Message(9, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, LOCOCMD); //High add 80 to indicate DCC int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, speed); m.setElement(6, cData1); m.setElement(7, cData2); m.setElement(8, cData3); return m; } static public Mx1Message getSwitchMsg(int accAddress, int setting, boolean dcc) { Mx1Message m = new Mx1Message(6, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, ACCCMD); //High add 80 to indicate DCC int accHi = accAddress >> 8; if (dcc) { accHi = accHi + 128; } else { accHi = accHi + 64; } m.setElement(3, (accHi)); m.setElement(4, (accAddress & 0xff)); m.setElement(5, 0x00); if (setting == jmri.Turnout.THROWN) { m.setElement(5, 0x04); } return m; } private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Mx1Message.class); }
158697_56
/* * Copyright (c) 2008 Kasper Nielsen. * * 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 sandbox.lifetime.old; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import app.packed.container.Wirelet; import app.packed.extension.Extension; /** * Wirelets that can only be specified when building an application. * <p> * Attempts to use them when {@link ApplicationLauncher#launch(Wirelet...) launching} an image will fail with * {@link IllegalArgumentException}. */ // Jeg tror den doer og ryger over paa andre wirelets... Saa vi udelukkende gruppere dem efter type... IDK... Maaske beholder vi den alligevel... public final class BuildWirelets { /** Not for you my friend. */ private BuildWirelets() {} // Only shows interesting stack frames when failing // This means we need to invocations for AssemblySetup.build // And filter the stack frames static Wirelet compressedBuildtimeExceptions() { throw new UnsupportedOperationException(); } public static Wirelet alwaysThrowBuildException() { // I don't think we can specify both this and onExceptionInBuild throw new UnsupportedOperationException(); } public static Wirelet onExceptionInBuild(Consumer<Exception> handler) { // consumer must throw, // handler.consumer() // throw new BuildException("handler did not throw"); throw new UnsupportedOperationException(); } public static Wirelet disableRuntimeWirelets() { // En optimering der goer at vi ved der aldrig kommer nogle runtime wirelets // Taenker kun den er brugbar for saadan noget som Session der skal spawne hurtigt // Men altsaa hvad fx med navn // driver.named() throw new UnsupportedOperationException(); } // if (ic.isRestarting()-> ServiceWirelets.Provide("Cool") : ServiceWirelets.Provide("FirstRun) static Wirelet delayToRuntime(Function<InstantiationContext, app.packed.container.Wirelet> wireletSupplier) { throw new UnsupportedOperationException(); } static Wirelet delayToRuntime(Supplier<Wirelet> wireletSupplier) { throw new UnsupportedOperationException(); } // Ideen er lidt at wireletten, ikke bliver processeret som en del af builded static Wirelet delayToRuntime(Wirelet wirelet) { throw new UnsupportedOperationException(); } // Maaske er det en build wirelet??? // Taenker @SafeVarargs public static Wirelet disableExtension(Class<? extends Extension<?>>... extensionTypes) { throw new UnsupportedOperationException(); } // /** // * Returns a 'spying' wirelet that will perform the specified action every time a component has been wired. // * <p> // * If you only want to spy on specific types of components you can use {@link #spyOnWire(Class, Consumer)} instead. // * // * @param action // * the action to perform // * @return the wirelet // */ // public static Wirelet spyOnWire(Consumer<? super ComponentMirror> action) { // return new InternalWirelet.OnWireActionWirelet(action, null); // } // // public static <T extends ComponentMirror> Wirelet spyOnWire(Class<T> mirrorType, Consumer<? super T> action) { // requireNonNull(mirrorType, "mirrorType is null"); // requireNonNull(action, "action is null"); // return spyOnWire(m -> { // if (mirrorType.isInstance(m)) { // action.accept(mirrorType.cast(m)); // } // }); // } // Ved ikke om scope er noedvendigt... // Det er jo udelukkende for test scenarier... Saa kan ikke rigtig // Hmmm, hvad med applikation hosts... Beholder vi den der??? // static Wirelet spyOnWire(Consumer<? super ComponentMirror> action, ComponentScope scope) { // requireNonNull(scope, "scope is null"); // return new InternalWirelet.OnWireActionWirelet(action, scope); // } interface InstantiationContext {} } class SandboxBuild { // Features // Debuggin // We could have app.packed.build package. // Taenker de kan bruges paa alle componenter. Og ikke kun rod.. // Eller??? Skal de fx. cachnes af en host??? // Saa nye guests ogsaa skal kunne overtage dem?? // Det samme gaelder med NameSpaceRules // De her regner gaelder for build'et... // Return InheritableWirelet(). // Wirelet printDebug().inherit(); // printDebug().inherit(); // Additional to people overridding artifacts, assemblies, ect. public static Wirelet checkRuleset(Object... ruleset) { throw new UnsupportedOperationException(); } // NO FAIL <--- maaske brugbart for analyse // fail on warnings. // Throw XX exception instead of // Taenker vi printer dem... // Og er det kun roden der kan disable dem??? public static Wirelet disableWarnings() { throw new UnsupportedOperationException(); } // Because it is just much easier than fiddling with loggers /** * A wirelet that will print various build information to {@code system.out}. * * @return the wirelet */ // Maaske til DevWirelets public static Wirelet printDebug() { throw new UnsupportedOperationException(); } // NoBootstrapCaching... // BootstrapWirelets.noBootstrap() public static Wirelet sidecarCacheLess() { throw new UnsupportedOperationException(); } static Wirelet sidecarCacheSpecific() { // The wirelet itself contains the cache... // And can be reused (also concurrently) // Maaske kan man styre noget reload praecist... // Maaske kan man optionalt tage en Runnable? // Som brugere kan invoke throw new UnsupportedOperationException(); } // Disable Host <--- Nej, det er et ruleset.... } //// Problemet med en wirelet og ikke en metode er at vi ikke beregne ApplicationBuildKind foerend //// vi har processeret alle wirelets //// Alternativ paa Driveren -> Fungere daarlig naar vi har child apps //// eller selvstaendig metode -> Er nok den bedste //@Deprecated //static Wirelet reusableImage() { // throw new UnsupportedOperationException(); //} //Wirelet assemblyTimeOnly(Wirelet w); Hmmm idk if useful /// Interface with only static methods are
packedapp/packedtmp
modules/packed/src/main/java/sandbox/lifetime/old/BuildWirelets.java
1,874
//// Alternativ paa Driveren -> Fungere daarlig naar vi har child apps
line_comment
nl
/* * Copyright (c) 2008 Kasper Nielsen. * * 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 sandbox.lifetime.old; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import app.packed.container.Wirelet; import app.packed.extension.Extension; /** * Wirelets that can only be specified when building an application. * <p> * Attempts to use them when {@link ApplicationLauncher#launch(Wirelet...) launching} an image will fail with * {@link IllegalArgumentException}. */ // Jeg tror den doer og ryger over paa andre wirelets... Saa vi udelukkende gruppere dem efter type... IDK... Maaske beholder vi den alligevel... public final class BuildWirelets { /** Not for you my friend. */ private BuildWirelets() {} // Only shows interesting stack frames when failing // This means we need to invocations for AssemblySetup.build // And filter the stack frames static Wirelet compressedBuildtimeExceptions() { throw new UnsupportedOperationException(); } public static Wirelet alwaysThrowBuildException() { // I don't think we can specify both this and onExceptionInBuild throw new UnsupportedOperationException(); } public static Wirelet onExceptionInBuild(Consumer<Exception> handler) { // consumer must throw, // handler.consumer() // throw new BuildException("handler did not throw"); throw new UnsupportedOperationException(); } public static Wirelet disableRuntimeWirelets() { // En optimering der goer at vi ved der aldrig kommer nogle runtime wirelets // Taenker kun den er brugbar for saadan noget som Session der skal spawne hurtigt // Men altsaa hvad fx med navn // driver.named() throw new UnsupportedOperationException(); } // if (ic.isRestarting()-> ServiceWirelets.Provide("Cool") : ServiceWirelets.Provide("FirstRun) static Wirelet delayToRuntime(Function<InstantiationContext, app.packed.container.Wirelet> wireletSupplier) { throw new UnsupportedOperationException(); } static Wirelet delayToRuntime(Supplier<Wirelet> wireletSupplier) { throw new UnsupportedOperationException(); } // Ideen er lidt at wireletten, ikke bliver processeret som en del af builded static Wirelet delayToRuntime(Wirelet wirelet) { throw new UnsupportedOperationException(); } // Maaske er det en build wirelet??? // Taenker @SafeVarargs public static Wirelet disableExtension(Class<? extends Extension<?>>... extensionTypes) { throw new UnsupportedOperationException(); } // /** // * Returns a 'spying' wirelet that will perform the specified action every time a component has been wired. // * <p> // * If you only want to spy on specific types of components you can use {@link #spyOnWire(Class, Consumer)} instead. // * // * @param action // * the action to perform // * @return the wirelet // */ // public static Wirelet spyOnWire(Consumer<? super ComponentMirror> action) { // return new InternalWirelet.OnWireActionWirelet(action, null); // } // // public static <T extends ComponentMirror> Wirelet spyOnWire(Class<T> mirrorType, Consumer<? super T> action) { // requireNonNull(mirrorType, "mirrorType is null"); // requireNonNull(action, "action is null"); // return spyOnWire(m -> { // if (mirrorType.isInstance(m)) { // action.accept(mirrorType.cast(m)); // } // }); // } // Ved ikke om scope er noedvendigt... // Det er jo udelukkende for test scenarier... Saa kan ikke rigtig // Hmmm, hvad med applikation hosts... Beholder vi den der??? // static Wirelet spyOnWire(Consumer<? super ComponentMirror> action, ComponentScope scope) { // requireNonNull(scope, "scope is null"); // return new InternalWirelet.OnWireActionWirelet(action, scope); // } interface InstantiationContext {} } class SandboxBuild { // Features // Debuggin // We could have app.packed.build package. // Taenker de kan bruges paa alle componenter. Og ikke kun rod.. // Eller??? Skal de fx. cachnes af en host??? // Saa nye guests ogsaa skal kunne overtage dem?? // Det samme gaelder med NameSpaceRules // De her regner gaelder for build'et... // Return InheritableWirelet(). // Wirelet printDebug().inherit(); // printDebug().inherit(); // Additional to people overridding artifacts, assemblies, ect. public static Wirelet checkRuleset(Object... ruleset) { throw new UnsupportedOperationException(); } // NO FAIL <--- maaske brugbart for analyse // fail on warnings. // Throw XX exception instead of // Taenker vi printer dem... // Og er det kun roden der kan disable dem??? public static Wirelet disableWarnings() { throw new UnsupportedOperationException(); } // Because it is just much easier than fiddling with loggers /** * A wirelet that will print various build information to {@code system.out}. * * @return the wirelet */ // Maaske til DevWirelets public static Wirelet printDebug() { throw new UnsupportedOperationException(); } // NoBootstrapCaching... // BootstrapWirelets.noBootstrap() public static Wirelet sidecarCacheLess() { throw new UnsupportedOperationException(); } static Wirelet sidecarCacheSpecific() { // The wirelet itself contains the cache... // And can be reused (also concurrently) // Maaske kan man styre noget reload praecist... // Maaske kan man optionalt tage en Runnable? // Som brugere kan invoke throw new UnsupportedOperationException(); } // Disable Host <--- Nej, det er et ruleset.... } //// Problemet med en wirelet og ikke en metode er at vi ikke beregne ApplicationBuildKind foerend //// vi har processeret alle wirelets //// Alternativ paa<SUF> //// eller selvstaendig metode -> Er nok den bedste //@Deprecated //static Wirelet reusableImage() { // throw new UnsupportedOperationException(); //} //Wirelet assemblyTimeOnly(Wirelet w); Hmmm idk if useful /// Interface with only static methods are
208303_18
package de.paginagmbh.epubchecker; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.JOptionPane; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import de.paginagmbh.common.gui.StatusBar; import de.paginagmbh.common.internet.FileDownloader; import de.paginagmbh.common.internet.NetTest; /** * checks for updates * * @author Tobias Fischer * @copyright pagina GmbH, Tübingen * @date 2019-01-22 */ public class UpdateCheck { // check for updates via https/SSL starting with v1.7.2 private final String updateCheckURL = "https://download.pagina.gmbh/epubchecker/updatecheck.php?from="+ PaginaEPUBChecker.PROGRAMVERSION; private Boolean backgroundTask; private DocumentBuilder builder; private XPath xpath; public FileDownloader dlgui; private static GuiManager guiManager; private StatusBar statusBar; public FileDownloader getFileDownloaderGui() { return dlgui; } /* ***************************************************************************************************************** */ public UpdateCheck(Boolean performInBackground) { guiManager = GuiManager.getInstance(); statusBar = guiManager.getCurrentGUI().getStatusBar(); if(performInBackground) { backgroundTask = true; } else { backgroundTask = false; } // date object Calendar cal = Calendar.getInstance(); // today's date SimpleDateFormat sdfCheck = new SimpleDateFormat("yyyyMMdd"); String UpdateCheckToday = sdfCheck.format(cal.getTime()).toString(); // check for last updatecheck if check runs in background at startup if(backgroundTask && new File(FileManager.path_LastUpdateCheckFile).exists()) { String UpdateCheckLast = null; try { UpdateCheckLast = StringHelper.readFileAsString(FileManager.path_LastUpdateCheckFile); } catch (IOException e) { e.printStackTrace(); } // return if the updater checked once today if(Integer.parseInt(UpdateCheckLast) == Integer.parseInt(UpdateCheckToday) && UpdateCheckLast != null ) { return; } } statusBar.update(FileManager.iconLoading, __("Checking for updates...")); // InternetConnection Test statusBar.update(FileManager.iconLoading, __("Checking internet connection...")); try { NetTest internetTest = new NetTest("https://www.google.com"); boolean hasInternetConnection = internetTest.testInternetConnection(); // cancel updateCheck with message if failing if(hasInternetConnection == false) { errorInternetConnectionNotAvailable(); return; } } catch (MalformedURLException e1) { errorUpdateCheck(e1); return; } // UpdateServer Test statusBar.update(FileManager.iconLoading, __("Checking update server...")); try { NetTest updateserverTest = new NetTest(updateCheckURL); boolean updateserverReady = updateserverTest.testWebsiteConnection(NetTest.HTTP_OK); // cancel updateCheck with message if failing if(updateserverReady == false) { errorUpdateServerNotAvailable(); return; } } catch (MalformedURLException e2) { errorUpdateCheck(e2); return; } statusBar.update(FileManager.iconLoading, __("Gathering update information...")); // Dokument instanzieren DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); // never forget this! try { builder = domFactory.newDocumentBuilder(); // XPath instanzieren XPathFactory factory = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI, "net.sf.saxon.xpath.XPathFactoryImpl", ClassLoader.getSystemClassLoader()); xpath = factory.newXPath(); // write today's date in updatecheckFile StringHelper.writeStringToFile(FileManager.path_LastUpdateCheckFile, UpdateCheckToday); // read update info from server // [0] BuildVersion // [1] BuildDate // [2] DownloadURL // [3] ReleaseNotes String[] UpdateInfo = retrieve_UpdateInfo(FileManager.os_name + PaginaEPUBChecker.PROGRAMRELEASE); // lokale Version ist niedriger als Server-Version // Ein Update steht bereit! if(Integer.parseInt(PaginaEPUBChecker.PROGRAMVERSION.replace(".", "")) < Integer.parseInt(UpdateInfo[0].replace(".", ""))) { statusBar.reset(); MessageGUI msg = new MessageGUI(); int answer = msg.showQuestion( __("Version %NEW_VERSION% is now available for download!") .replaceAll("%NEW_VERSION%", UpdateInfo[0]) + "<br/>" + __("You are currently using %CURRENT_VERSION%") .replaceAll("%CURRENT_VERSION%", PaginaEPUBChecker.PROGRAMVERSION) + "<br/><br/>" + __("New version %NEW_VERSION% includes these features:") .replaceAll("%NEW_VERSION%", UpdateInfo[0]) + "<br/><br/>" + UpdateInfo[3] + "<br/><br/><br/>" + __("Do you want to download the update?")); if(answer == JOptionPane.YES_OPTION) { // download the update dlgui = new FileDownloader( // download updates via https/SSL starting with v1.7.2, keep http download-URL for old versions UpdateInfo[2].replaceAll("^http://", "https://"), System.getProperty("user.home") + File.separator + "Desktop", String.format( __("An update (v%1$s, %2$s) for your current installation (v%3$s, %4$s) is being downloaded right now..."), UpdateInfo[0], UpdateInfo[1], PaginaEPUBChecker.PROGRAMVERSION, PaginaEPUBChecker.VERSIONDATE)); } else { return; } // lokale Version ist höher als oder gleich wie Server-Version // Es gibt kein Update! } else { if(backgroundTask) { statusBar.update(null, __("There are no new updates available.")); } else { MessageGUI msg = new MessageGUI(); statusBar.reset(); msg.showMessage(__("There are no new updates available."), __("You're up-to-date!")); } return; } } catch (Exception e) { errorUpdateCheck(e); return; } } /* ***************************************************************************************************************** */ public void errorUpdateCheck(Exception e) { if(backgroundTask) { statusBar.update(null, __("Update check failed!") + " " + __("Please check manually for updates").replace("<br/>", " ")); } else { MessageGUI msg = new MessageGUI(); statusBar.reset(); msg.showMessage(__("Please check manually for updates") + "<br/><br/>["+ e.getClass().getName() +"]<br/>"+ e.getMessage().replace(System.getProperty("line.separator"), "<br/>"), __("Update check failed!")); } } /* ***************************************************************************************************************** */ public void errorInternetConnectionNotAvailable() { if(backgroundTask) { statusBar.update(null, __("Update check failed!") + " " + __("Can't establish internet connection.")); } else { MessageGUI msg = new MessageGUI(); statusBar.reset(); msg.showError(__("Update check failed!") + "<br/>" + __("Can't establish internet connection.")); } } /* ***************************************************************************************************************** */ public void errorUpdateServerNotAvailable() { String failureReason = __("Update server not available."); /* pagina'S SSL certificate root authority (DigiCert Global Root G2) is only accepted by * - Java 7u101 and later https://bugs.openjdk.java.net/browse/JDK-8151321 * - Java 8u91 and later https://www.oracle.com/technetwork/java/javase/8u91-relnotes-2949462.html * - Java 9 and later */ String javaVersion = System.getProperty("java.version"); if(javaVersion.startsWith("1.7") || javaVersion.startsWith("1.8")) { int minorVersion = Integer.parseInt(javaVersion.split("_")[1]); if((javaVersion.startsWith("1.7") && minorVersion <= 101) || (javaVersion.startsWith("1.8") && minorVersion <= 91)) { failureReason = __("Java version too old") + " " + __("Please check manually for updates").replace("<br/>", " "); } } if(backgroundTask) { statusBar.update(null, __("Update check failed!") + " " + failureReason); } else { MessageGUI msg = new MessageGUI(); statusBar.reset(); msg.showError(__("Update check failed!") + "<br/>" + failureReason); } } /* ***************************************************************************************************************** */ public String[] retrieve_UpdateInfo(String OSname) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { String[] UpdateInfo = {null, null, null, null}; // read update information Document docUpdate = builder.parse(updateCheckURL); // BuildVersion UpdateInfo[0] = xpath.compile("//package[@os='" + OSname + "']/entry[@key='buildversion']/value").evaluate(docUpdate); // BuildDate UpdateInfo[1] = xpath.compile("//package[@os='" + OSname + "']/entry[@key='builddate']/value").evaluate(docUpdate); // DownloadURL UpdateInfo[2] = xpath.compile("//package[@os='" + OSname + "']/entry[@key='downloadURL']/value").evaluate(docUpdate); // ReleaseNotes UpdateInfo[3] = xpath.compile("//package[@os='" + OSname + "']/entry[@key='releaseNotes']/value").evaluate(docUpdate); return UpdateInfo; } /* ********************************************************************************************************** */ private String __(String s) { return GuiManager.getInstance().getCurrentLocalizationObject().getString(s); } }
paginagmbh/EPUB-Checker
src/main/java/de/paginagmbh/epubchecker/UpdateCheck.java
2,968
//package[@os='" + OSname + "']/entry[@key='builddate']/value").evaluate(docUpdate);
line_comment
nl
package de.paginagmbh.epubchecker; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.text.SimpleDateFormat; import java.util.Calendar; import javax.swing.JOptionPane; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import de.paginagmbh.common.gui.StatusBar; import de.paginagmbh.common.internet.FileDownloader; import de.paginagmbh.common.internet.NetTest; /** * checks for updates * * @author Tobias Fischer * @copyright pagina GmbH, Tübingen * @date 2019-01-22 */ public class UpdateCheck { // check for updates via https/SSL starting with v1.7.2 private final String updateCheckURL = "https://download.pagina.gmbh/epubchecker/updatecheck.php?from="+ PaginaEPUBChecker.PROGRAMVERSION; private Boolean backgroundTask; private DocumentBuilder builder; private XPath xpath; public FileDownloader dlgui; private static GuiManager guiManager; private StatusBar statusBar; public FileDownloader getFileDownloaderGui() { return dlgui; } /* ***************************************************************************************************************** */ public UpdateCheck(Boolean performInBackground) { guiManager = GuiManager.getInstance(); statusBar = guiManager.getCurrentGUI().getStatusBar(); if(performInBackground) { backgroundTask = true; } else { backgroundTask = false; } // date object Calendar cal = Calendar.getInstance(); // today's date SimpleDateFormat sdfCheck = new SimpleDateFormat("yyyyMMdd"); String UpdateCheckToday = sdfCheck.format(cal.getTime()).toString(); // check for last updatecheck if check runs in background at startup if(backgroundTask && new File(FileManager.path_LastUpdateCheckFile).exists()) { String UpdateCheckLast = null; try { UpdateCheckLast = StringHelper.readFileAsString(FileManager.path_LastUpdateCheckFile); } catch (IOException e) { e.printStackTrace(); } // return if the updater checked once today if(Integer.parseInt(UpdateCheckLast) == Integer.parseInt(UpdateCheckToday) && UpdateCheckLast != null ) { return; } } statusBar.update(FileManager.iconLoading, __("Checking for updates...")); // InternetConnection Test statusBar.update(FileManager.iconLoading, __("Checking internet connection...")); try { NetTest internetTest = new NetTest("https://www.google.com"); boolean hasInternetConnection = internetTest.testInternetConnection(); // cancel updateCheck with message if failing if(hasInternetConnection == false) { errorInternetConnectionNotAvailable(); return; } } catch (MalformedURLException e1) { errorUpdateCheck(e1); return; } // UpdateServer Test statusBar.update(FileManager.iconLoading, __("Checking update server...")); try { NetTest updateserverTest = new NetTest(updateCheckURL); boolean updateserverReady = updateserverTest.testWebsiteConnection(NetTest.HTTP_OK); // cancel updateCheck with message if failing if(updateserverReady == false) { errorUpdateServerNotAvailable(); return; } } catch (MalformedURLException e2) { errorUpdateCheck(e2); return; } statusBar.update(FileManager.iconLoading, __("Gathering update information...")); // Dokument instanzieren DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); // never forget this! try { builder = domFactory.newDocumentBuilder(); // XPath instanzieren XPathFactory factory = XPathFactory.newInstance(XPathFactory.DEFAULT_OBJECT_MODEL_URI, "net.sf.saxon.xpath.XPathFactoryImpl", ClassLoader.getSystemClassLoader()); xpath = factory.newXPath(); // write today's date in updatecheckFile StringHelper.writeStringToFile(FileManager.path_LastUpdateCheckFile, UpdateCheckToday); // read update info from server // [0] BuildVersion // [1] BuildDate // [2] DownloadURL // [3] ReleaseNotes String[] UpdateInfo = retrieve_UpdateInfo(FileManager.os_name + PaginaEPUBChecker.PROGRAMRELEASE); // lokale Version ist niedriger als Server-Version // Ein Update steht bereit! if(Integer.parseInt(PaginaEPUBChecker.PROGRAMVERSION.replace(".", "")) < Integer.parseInt(UpdateInfo[0].replace(".", ""))) { statusBar.reset(); MessageGUI msg = new MessageGUI(); int answer = msg.showQuestion( __("Version %NEW_VERSION% is now available for download!") .replaceAll("%NEW_VERSION%", UpdateInfo[0]) + "<br/>" + __("You are currently using %CURRENT_VERSION%") .replaceAll("%CURRENT_VERSION%", PaginaEPUBChecker.PROGRAMVERSION) + "<br/><br/>" + __("New version %NEW_VERSION% includes these features:") .replaceAll("%NEW_VERSION%", UpdateInfo[0]) + "<br/><br/>" + UpdateInfo[3] + "<br/><br/><br/>" + __("Do you want to download the update?")); if(answer == JOptionPane.YES_OPTION) { // download the update dlgui = new FileDownloader( // download updates via https/SSL starting with v1.7.2, keep http download-URL for old versions UpdateInfo[2].replaceAll("^http://", "https://"), System.getProperty("user.home") + File.separator + "Desktop", String.format( __("An update (v%1$s, %2$s) for your current installation (v%3$s, %4$s) is being downloaded right now..."), UpdateInfo[0], UpdateInfo[1], PaginaEPUBChecker.PROGRAMVERSION, PaginaEPUBChecker.VERSIONDATE)); } else { return; } // lokale Version ist höher als oder gleich wie Server-Version // Es gibt kein Update! } else { if(backgroundTask) { statusBar.update(null, __("There are no new updates available.")); } else { MessageGUI msg = new MessageGUI(); statusBar.reset(); msg.showMessage(__("There are no new updates available."), __("You're up-to-date!")); } return; } } catch (Exception e) { errorUpdateCheck(e); return; } } /* ***************************************************************************************************************** */ public void errorUpdateCheck(Exception e) { if(backgroundTask) { statusBar.update(null, __("Update check failed!") + " " + __("Please check manually for updates").replace("<br/>", " ")); } else { MessageGUI msg = new MessageGUI(); statusBar.reset(); msg.showMessage(__("Please check manually for updates") + "<br/><br/>["+ e.getClass().getName() +"]<br/>"+ e.getMessage().replace(System.getProperty("line.separator"), "<br/>"), __("Update check failed!")); } } /* ***************************************************************************************************************** */ public void errorInternetConnectionNotAvailable() { if(backgroundTask) { statusBar.update(null, __("Update check failed!") + " " + __("Can't establish internet connection.")); } else { MessageGUI msg = new MessageGUI(); statusBar.reset(); msg.showError(__("Update check failed!") + "<br/>" + __("Can't establish internet connection.")); } } /* ***************************************************************************************************************** */ public void errorUpdateServerNotAvailable() { String failureReason = __("Update server not available."); /* pagina'S SSL certificate root authority (DigiCert Global Root G2) is only accepted by * - Java 7u101 and later https://bugs.openjdk.java.net/browse/JDK-8151321 * - Java 8u91 and later https://www.oracle.com/technetwork/java/javase/8u91-relnotes-2949462.html * - Java 9 and later */ String javaVersion = System.getProperty("java.version"); if(javaVersion.startsWith("1.7") || javaVersion.startsWith("1.8")) { int minorVersion = Integer.parseInt(javaVersion.split("_")[1]); if((javaVersion.startsWith("1.7") && minorVersion <= 101) || (javaVersion.startsWith("1.8") && minorVersion <= 91)) { failureReason = __("Java version too old") + " " + __("Please check manually for updates").replace("<br/>", " "); } } if(backgroundTask) { statusBar.update(null, __("Update check failed!") + " " + failureReason); } else { MessageGUI msg = new MessageGUI(); statusBar.reset(); msg.showError(__("Update check failed!") + "<br/>" + failureReason); } } /* ***************************************************************************************************************** */ public String[] retrieve_UpdateInfo(String OSname) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { String[] UpdateInfo = {null, null, null, null}; // read update information Document docUpdate = builder.parse(updateCheckURL); // BuildVersion UpdateInfo[0] = xpath.compile("//package[@os='" + OSname + "']/entry[@key='buildversion']/value").evaluate(docUpdate); // BuildDate UpdateInfo[1] = xpath.compile("//package[@os='" +<SUF> // DownloadURL UpdateInfo[2] = xpath.compile("//package[@os='" + OSname + "']/entry[@key='downloadURL']/value").evaluate(docUpdate); // ReleaseNotes UpdateInfo[3] = xpath.compile("//package[@os='" + OSname + "']/entry[@key='releaseNotes']/value").evaluate(docUpdate); return UpdateInfo; } /* ********************************************************************************************************** */ private String __(String s) { return GuiManager.getInstance().getCurrentLocalizationObject().getString(s); } }
107768_9
/* * 2007-2016 [PagSeguro Internet Ltda.] * * NOTICE OF LICENSE * * 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. * * Copyright: 2007-2016 PagSeguro Internet Ltda. * Licence: http://www.apache.org/licenses/LICENSE-2.0 */ package br.com.uol.pagseguro.api.checkout; import java.math.BigDecimal; import java.util.List; import br.com.uol.pagseguro.api.common.domain.*; import br.com.uol.pagseguro.api.common.domain.PreApprovalRequest; import br.com.uol.pagseguro.api.common.domain.enums.Currency; /** * Interface to make payments through payment API * * @author PagSeguro Internet Ltda. */ public interface CheckoutRegistration { /** * Define a code to refer to the payment. * This code is associated with the transaction created by the payment and is useful * to link PagSeguro transactions to sales registered on your system. * Format: Free, with the 200-character limit. * * Optional * * @return Reference Code. */ String getReference(); /** * Extra value. Specifies an extra value to be added or subtracted from the total amount of * payment. This value may represent an extra fee to be charged in the payment or a discount to be * granted if the value is negative. Format: Decimal (positive or negative), to two decimal places * separated by a point (bp, or 1234.56 -1234.56), greater than or equal to -9999999.00 and less * than or equal to 9999999.00. When negative, this value can not be greater than or equal to the * sum of the values ​​of the products. * * Optional * * @return Extra Amout */ BigDecimal getExtraAmount(); /** * Indicates the currency in which payment will be made. * * Required * * @return Currency used * @see Currency */ Currency getCurrency(); /** * Shipping data * * @return Shipping * * Optional * @see Shipping */ Shipping getShipping(); /** * Sender data * * @return Sender Data * * Optional * @see Sender */ Sender getSender(); /** * List of items contained in the payment * * @return List of Payment Items * @see PaymentItem */ List<? extends PaymentItem> getItems(); /** * Pre Approval * * @return Pre Approval * @see PreApprovalRequest */ PreApprovalRequest getPreApproval(); /** * Get Parameters * * @return Parameters * @see Parameter */ List<? extends Parameter> getParameters(); /** * Used to include and exclude groups of means of payment and means of payment for a transaction * * @return Accepted Payment Methods * @see AcceptedPaymentMethods */ AcceptedPaymentMethods getAcceptedPaymentMethods(); /** * Configurations to payment methods. * * @return Configurations to payment methods. */ List<? extends PaymentMethodConfig> getPaymentMethodConfigs(); }
pagseguro/pagseguro-sdk-java
source/src/main/java/br/com/uol/pagseguro/api/checkout/CheckoutRegistration.java
994
/** * Get Parameters * * @return Parameters * @see Parameter */
block_comment
nl
/* * 2007-2016 [PagSeguro Internet Ltda.] * * NOTICE OF LICENSE * * 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. * * Copyright: 2007-2016 PagSeguro Internet Ltda. * Licence: http://www.apache.org/licenses/LICENSE-2.0 */ package br.com.uol.pagseguro.api.checkout; import java.math.BigDecimal; import java.util.List; import br.com.uol.pagseguro.api.common.domain.*; import br.com.uol.pagseguro.api.common.domain.PreApprovalRequest; import br.com.uol.pagseguro.api.common.domain.enums.Currency; /** * Interface to make payments through payment API * * @author PagSeguro Internet Ltda. */ public interface CheckoutRegistration { /** * Define a code to refer to the payment. * This code is associated with the transaction created by the payment and is useful * to link PagSeguro transactions to sales registered on your system. * Format: Free, with the 200-character limit. * * Optional * * @return Reference Code. */ String getReference(); /** * Extra value. Specifies an extra value to be added or subtracted from the total amount of * payment. This value may represent an extra fee to be charged in the payment or a discount to be * granted if the value is negative. Format: Decimal (positive or negative), to two decimal places * separated by a point (bp, or 1234.56 -1234.56), greater than or equal to -9999999.00 and less * than or equal to 9999999.00. When negative, this value can not be greater than or equal to the * sum of the values ​​of the products. * * Optional * * @return Extra Amout */ BigDecimal getExtraAmount(); /** * Indicates the currency in which payment will be made. * * Required * * @return Currency used * @see Currency */ Currency getCurrency(); /** * Shipping data * * @return Shipping * * Optional * @see Shipping */ Shipping getShipping(); /** * Sender data * * @return Sender Data * * Optional * @see Sender */ Sender getSender(); /** * List of items contained in the payment * * @return List of Payment Items * @see PaymentItem */ List<? extends PaymentItem> getItems(); /** * Pre Approval * * @return Pre Approval * @see PreApprovalRequest */ PreApprovalRequest getPreApproval(); /** * Get Parameters <SUF>*/ List<? extends Parameter> getParameters(); /** * Used to include and exclude groups of means of payment and means of payment for a transaction * * @return Accepted Payment Methods * @see AcceptedPaymentMethods */ AcceptedPaymentMethods getAcceptedPaymentMethods(); /** * Configurations to payment methods. * * @return Configurations to payment methods. */ List<? extends PaymentMethodConfig> getPaymentMethodConfigs(); }
58283_16
//package ws.palladian.extraction.entity.tagger; // //import com.aliasi.chunk.BioTagChunkCodec; //import com.aliasi.chunk.Chunking; //import com.aliasi.chunk.TagChunkCodec; //import com.aliasi.chunk.TagChunkCodecAdapters; //import com.aliasi.corpus.StringParser; //import com.aliasi.tag.LineTaggingParser; //import com.aliasi.tag.Tagging; // ///** // * Here's a corpus sample from CoNLL 2002 test file <code>ned.testa</code>, // * which is encoded in the character set ISO-8859-1 (aka Latin1): // * // * <blockquote> // * // * <pre> // * ... // * de Art O // * orde N O // * . Punc O // * // * -DOCSTART- -DOCSTART- O // * Met Prep O // * tien Num O // * miljoen Num O // * komen V O // * we Pron O // * , Punc O // * denk V O // * ik Pron O // * , Punc O // * al Adv O // * een Art O // * heel Adj O // * eind N O // * . Punc O // * // * Dirk N B-PER // * ... // * </pre> // * // * </blockquote> // */ //class Conll2002ChunkTagParser extends StringParser<com.aliasi.corpus.ObjectHandler<Chunking>> { // // static final String TOKEN_TAG_LINE_REGEX = "(\\S+)\\s(\\S+\\s)?(O|[B|I]-\\S+)"; // token ?posTag entityTag // static final int TOKEN_GROUP = 1; // token // static final int TAG_GROUP = 3; // entityTag // static final String IGNORE_LINE_REGEX = "-DOCSTART(.*)"; // lines that start with "-DOCSTART" // static final String EOS_REGEX = "\\A\\Z"; // empty lines // // static final String BEGIN_TAG_PREFIX = "B-"; // static final String IN_TAG_PREFIX = "I-"; // static final String OUT_TAG = "O"; // // private final LineTaggingParser mParser = new LineTaggingParser(TOKEN_TAG_LINE_REGEX, TOKEN_GROUP, TAG_GROUP, // IGNORE_LINE_REGEX, EOS_REGEX); // // private final TagChunkCodec mCodec = new BioTagChunkCodec(null, // no tokenizer // false, // don't enforce consistency // BEGIN_TAG_PREFIX, // custom BIO tag coding matches regex // IN_TAG_PREFIX, OUT_TAG); // // @Override // public void parseString(char[] cs, int start, int end) { // mParser.parseString(cs, start, end); // } // // @Override // public void setHandler(com.aliasi.corpus.ObjectHandler<Chunking> handler) { // com.aliasi.corpus.ObjectHandler<Tagging<String>> taggingHandler = TagChunkCodecAdapters.chunkingToTagging( // mCodec, handler); // mParser.setHandler(taggingHandler); // } // //}
palladian/palladian
palladian-experimental/src/main/java/ws/palladian/extraction/entity/tagger/Conll2002ChunkTagParser.java
889
// * een Art O
line_comment
nl
//package ws.palladian.extraction.entity.tagger; // //import com.aliasi.chunk.BioTagChunkCodec; //import com.aliasi.chunk.Chunking; //import com.aliasi.chunk.TagChunkCodec; //import com.aliasi.chunk.TagChunkCodecAdapters; //import com.aliasi.corpus.StringParser; //import com.aliasi.tag.LineTaggingParser; //import com.aliasi.tag.Tagging; // ///** // * Here's a corpus sample from CoNLL 2002 test file <code>ned.testa</code>, // * which is encoded in the character set ISO-8859-1 (aka Latin1): // * // * <blockquote> // * // * <pre> // * ... // * de Art O // * orde N O // * . Punc O // * // * -DOCSTART- -DOCSTART- O // * Met Prep O // * tien Num O // * miljoen Num O // * komen V O // * we Pron O // * , Punc O // * denk V O // * ik Pron O // * , Punc O // * al Adv O // * een Art<SUF> // * heel Adj O // * eind N O // * . Punc O // * // * Dirk N B-PER // * ... // * </pre> // * // * </blockquote> // */ //class Conll2002ChunkTagParser extends StringParser<com.aliasi.corpus.ObjectHandler<Chunking>> { // // static final String TOKEN_TAG_LINE_REGEX = "(\\S+)\\s(\\S+\\s)?(O|[B|I]-\\S+)"; // token ?posTag entityTag // static final int TOKEN_GROUP = 1; // token // static final int TAG_GROUP = 3; // entityTag // static final String IGNORE_LINE_REGEX = "-DOCSTART(.*)"; // lines that start with "-DOCSTART" // static final String EOS_REGEX = "\\A\\Z"; // empty lines // // static final String BEGIN_TAG_PREFIX = "B-"; // static final String IN_TAG_PREFIX = "I-"; // static final String OUT_TAG = "O"; // // private final LineTaggingParser mParser = new LineTaggingParser(TOKEN_TAG_LINE_REGEX, TOKEN_GROUP, TAG_GROUP, // IGNORE_LINE_REGEX, EOS_REGEX); // // private final TagChunkCodec mCodec = new BioTagChunkCodec(null, // no tokenizer // false, // don't enforce consistency // BEGIN_TAG_PREFIX, // custom BIO tag coding matches regex // IN_TAG_PREFIX, OUT_TAG); // // @Override // public void parseString(char[] cs, int start, int end) { // mParser.parseString(cs, start, end); // } // // @Override // public void setHandler(com.aliasi.corpus.ObjectHandler<Chunking> handler) { // com.aliasi.corpus.ObjectHandler<Tagging<String>> taggingHandler = TagChunkCodecAdapters.chunkingToTagging( // mCodec, handler); // mParser.setHandler(taggingHandler); // } // //}
199647_1
package opennlp; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import features.helpers.POSTagEntry; import main.Config; import nlp.pos.AbstractPOSTagger; import nlp.pos.POSTaggerFactory; import nlp.stopwords.StopWordItem; import nlp.stopwords.StopWords; import nlp.tokenize.AbstractTokenizer; import nlp.tokenize.TokenizerFactory; public class Tester { public static void main(String[] args) { try { String input = "and the hell comes near Hi. How are you? This is Mike."; AbstractTokenizer tokenizer = TokenizerFactory.get(Config.LANG_EN); String[] tokens = tokenizer.tokenize(input); StopWords ws = new StopWords(Config.LANG_EN, tokens); HashMap<String, StopWordItem> ls = ws.count(input); for (String key : ls.keySet()) { // System.out.println(ls.get(key)); } AbstractPOSTagger tagger = POSTaggerFactory.get(Config.LANG_EN); LinkedList<POSTagEntry> tags = tagger.tag(input); for (POSTagEntry entry : tags) { // System.out.println(entry.getWord() + " -> " + entry.getPostag() + ": " + entry.getNumberOfOccurrences()); } String dutchInput = "hej";//"Er zijn in de Europese Unie in verscheidene landen verkiezingen op komst en dat verlamt het Spaanse EU-voorzitterschap."; //TODO fix problems with the NL classifier AbstractPOSTagger dutchTagger = POSTaggerFactory.get(Config.LANG_NL); LinkedList<POSTagEntry> dutchTags = dutchTagger.tag(dutchInput); for (POSTagEntry entry : dutchTags) { System.out.println(entry.getWord() + " -> " + entry.getPostag() + ": " + entry.getNumberOfOccurrences()); } String greekInput = "Στο ΠΙΑΤΣΑ ΜΕΖΕΔΑΚΙ με οδήγησε ουσιαστικά το κινητό μου τηλέφωνο! Μετά από δουλειές στη γύρω περιοχή βρεθήκαμε ένα Σάββατο απόγευμα πεινασμένοι, να αναρωτιόμαστε, τι να φάμε και σήμερα."; AbstractPOSTagger greekTagger = POSTaggerFactory.get(Config.LANG_GR); LinkedList<POSTagEntry> greekTags = greekTagger.tag(greekInput); for (POSTagEntry entry : greekTags) { // System.out.println(entry.getWord() + " -> " + entry.getPostag() + ": " + entry.getNumberOfOccurrences()); } } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
pan-webis-de/zmiycharov16
src/main/java/opennlp/Tester.java
811
//"Er zijn in de Europese Unie in verscheidene landen verkiezingen op komst en dat verlamt het Spaanse EU-voorzitterschap.";
line_comment
nl
package opennlp; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import features.helpers.POSTagEntry; import main.Config; import nlp.pos.AbstractPOSTagger; import nlp.pos.POSTaggerFactory; import nlp.stopwords.StopWordItem; import nlp.stopwords.StopWords; import nlp.tokenize.AbstractTokenizer; import nlp.tokenize.TokenizerFactory; public class Tester { public static void main(String[] args) { try { String input = "and the hell comes near Hi. How are you? This is Mike."; AbstractTokenizer tokenizer = TokenizerFactory.get(Config.LANG_EN); String[] tokens = tokenizer.tokenize(input); StopWords ws = new StopWords(Config.LANG_EN, tokens); HashMap<String, StopWordItem> ls = ws.count(input); for (String key : ls.keySet()) { // System.out.println(ls.get(key)); } AbstractPOSTagger tagger = POSTaggerFactory.get(Config.LANG_EN); LinkedList<POSTagEntry> tags = tagger.tag(input); for (POSTagEntry entry : tags) { // System.out.println(entry.getWord() + " -> " + entry.getPostag() + ": " + entry.getNumberOfOccurrences()); } String dutchInput = "hej";//"Er zijn<SUF> //TODO fix problems with the NL classifier AbstractPOSTagger dutchTagger = POSTaggerFactory.get(Config.LANG_NL); LinkedList<POSTagEntry> dutchTags = dutchTagger.tag(dutchInput); for (POSTagEntry entry : dutchTags) { System.out.println(entry.getWord() + " -> " + entry.getPostag() + ": " + entry.getNumberOfOccurrences()); } String greekInput = "Στο ΠΙΑΤΣΑ ΜΕΖΕΔΑΚΙ με οδήγησε ουσιαστικά το κινητό μου τηλέφωνο! Μετά από δουλειές στη γύρω περιοχή βρεθήκαμε ένα Σάββατο απόγευμα πεινασμένοι, να αναρωτιόμαστε, τι να φάμε και σήμερα."; AbstractPOSTagger greekTagger = POSTaggerFactory.get(Config.LANG_GR); LinkedList<POSTagEntry> greekTags = greekTagger.tag(greekInput); for (POSTagEntry entry : greekTags) { // System.out.println(entry.getWord() + " -> " + entry.getPostag() + ": " + entry.getNumberOfOccurrences()); } } catch (Exception ex) { System.out.println(ex.getMessage()); } } }
131995_15
// // ======================================================================== // Copyright (c) 2018-2019 HuJian/Pandening soft collection. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the #{license} Public License #{version} // EG: // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // You should bear the consequences of using the software (named 'java-debug-tool') // and any modify must be create an new pull request and attach an text to describe // the change detail. // ======================================================================== // package io.javadebug.core.data; import sun.management.ManagementFactoryHelper; import java.lang.management.BufferPoolMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.OperatingSystemMXBean; import java.math.BigDecimal; import java.util.List; /** * the memory information * * Auth : pandening * Date : 2020-01-11 23:37 */ public class JVMMemoryInfo { // heap size eden + survivor (from + to) + old private long usedHeapMem = -1; private long maxHeapMem = -1; // young -> eden private long usedEdenMem = -1; private long maxEdenMem = -1; // young -> survivor private long usedSurvivorMem = -1; private long maxSurvivorMem = -1; // old gen private long usedOldGenMem = -1; private long maxOldGenMem = -1; // metaspace private long usedMetaspaceMem = -1; private long maxMetaspaceMem = -1; // non-heap private long usedNonHeapMem = -1; private long maxNonHeapMem = -1; // physical (mem + swap) private long usedSwapMem = -1; private long maxSwapMem = -1; private long usedPhysicalMem = -1; private long maxPhysicalMem = -1; // direct & mapped private long maxDirectMem = -1; private long usedDirectMem = -1; private long maxMappedMem = -1; private long usedMappedMem = -1; public JVMMemoryInfo() { // init heap mem usedHeapMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); maxHeapMem = Runtime.getRuntime().maxMemory(); // young gen [Eden] MemoryPoolMXBean youngGen = getSpecialGenMemoryPool("Eden"); if (youngGen != null) { usedEdenMem = youngGen.getUsage().getUsed(); maxEdenMem = youngGen.getUsage().getMax(); } // young gen [survivor] MemoryPoolMXBean survivorGen = getSpecialGenMemoryPool("Survivor"); if (survivorGen != null) { usedSurvivorMem = survivorGen.getUsage().getUsed(); maxSurvivorMem = survivorGen.getUsage().getMax(); } // metaspace MemoryPoolMXBean metaspace = getSpecialGenMemoryPool("Metaspace"); if (metaspace != null) { usedMetaspaceMem = metaspace.getUsage().getUsed(); maxMetaspaceMem = metaspace.getUsage().getMax(); } // old gen MemoryPoolMXBean oldGen = getSpecialGenMemoryPool("Old"); if (oldGen != null) { usedOldGenMem = oldGen.getUsage().getUsed(); maxOldGenMem = oldGen.getUsage().getMax(); } // non-heap usedNonHeapMem = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed(); maxNonHeapMem = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getMax(); // direct & mapped List<BufferPoolMXBean> bufferPoolMXBeanList = ManagementFactoryHelper.getBufferPoolMXBeans(); BufferPoolMXBean directPool = getDirectOrMappedMem(bufferPoolMXBeanList, "direct"); BufferPoolMXBean mappedPool = getDirectOrMappedMem(bufferPoolMXBeanList, "mapped"); if (directPool != null) { maxDirectMem = directPool.getTotalCapacity(); usedDirectMem = directPool.getMemoryUsed(); } if (mappedPool != null) { maxMappedMem = mappedPool.getTotalCapacity(); usedMappedMem = mappedPool.getMemoryUsed(); } // physic OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean(); if (operatingSystem instanceof com.sun.management.OperatingSystemMXBean) { usedPhysicalMem = ((com.sun.management.OperatingSystemMXBean) operatingSystem).getTotalPhysicalMemorySize() - ((com.sun.management.OperatingSystemMXBean) operatingSystem).getFreePhysicalMemorySize(); maxPhysicalMem = ((com.sun.management.OperatingSystemMXBean) operatingSystem).getTotalPhysicalMemorySize(); usedSwapMem = ((com.sun.management.OperatingSystemMXBean) operatingSystem).getTotalSwapSpaceSize() - ((com.sun.management.OperatingSystemMXBean) operatingSystem).getFreeSwapSpaceSize(); maxSwapMem = ((com.sun.management.OperatingSystemMXBean) operatingSystem).getTotalSwapSpaceSize(); } } /** * "direct" * "mapped" * * @param bufferPoolMXBeanList {@link ManagementFactoryHelper#getBufferPoolMXBeans()} * @param key which pool * @return the target pool */ private static BufferPoolMXBean getDirectOrMappedMem(List<BufferPoolMXBean> bufferPoolMXBeanList, String key) { for (BufferPoolMXBean bufferPoolMXBean : bufferPoolMXBeanList) { if (bufferPoolMXBean.getName().contains(key)) { return bufferPoolMXBean; } } return null; } /** * get special gen memory pool {@link MemoryPoolMXBean} * * @param gen the target gen like 'Old Gen' / 'Old' * @return the target pool, maybe null */ private static MemoryPoolMXBean getSpecialGenMemoryPool(String gen) { for (final MemoryPoolMXBean memoryPool : ManagementFactory.getMemoryPoolMXBeans()) { if (memoryPool.getName().contains(gen)) { return memoryPool; } } return null; } private static final String MEM_SHOW_FORMAT = "%-30.30s " + "%-30.30s " + "%-30.30s"; private static final String MEM_TITLE = String.format(MEM_SHOW_FORMAT, "Heap", "Non-Heap", "Physical"); @Override public String toString() { String ph = String.format(MEM_SHOW_FORMAT, "--------", "--------", "--------"); StringBuilder rsb = new StringBuilder(); // header rsb.append(ph).append("\n").append(MEM_TITLE).append("\n").append(ph).append("\n"); // line 1 String line = String.format(MEM_SHOW_FORMAT, "|_Heap :[" + tramMem(maxHeapMem) + "," + tramMem(usedHeapMem) + "]", "|_NonHeap :[" + tramMem(maxNonHeapMem) + "," + tramMem(usedNonHeapMem) + "]", "|_Physical :[" + tramMem(maxPhysicalMem) + "," + tramMem(usedPhysicalMem) + "]" ); rsb.append(line).append("\n"); // line 2 line = String.format(MEM_SHOW_FORMAT, "|_Eden :[" + tramMem(maxEdenMem) + "," + tramMem(usedEdenMem) + "]", "|_Direct :[" + tramMem(maxDirectMem) + "," + tramMem(usedDirectMem) + "]", "|_Swap :[" + tramMem(maxSwapMem) + "," + tramMem(usedSwapMem) + "]" ); rsb.append(line).append("\n"); // line 3 line = String.format(MEM_SHOW_FORMAT, "|_Survivor :[" + tramMem(maxSurvivorMem) + "," + tramMem(usedSurvivorMem) + "]", "|_Mapped :[" + tramMem(maxMappedMem) + "," + tramMem(usedMappedMem) + "]", "" ); rsb.append(line).append("\n"); // line 4 line = String.format(MEM_SHOW_FORMAT, "|_OldGen :[" + tramMem(maxOldGenMem) + "," + tramMem(usedOldGenMem) + "]", "|_Metaspace :[" + tramMem(maxMetaspaceMem) + "," + tramMem(usedMetaspaceMem) + "]", "" ); rsb.append(line).append("\n"); //result return rsb.toString(); } private static String tramMem(long bytes) { if (bytes < 0) { return bytes + ""; } if (bytes <= 1024) { // b return bytes + " b"; } else if (bytes <= (1024.0 * 1024.0)) { return trimDouble((bytes) / (1024.0 * 1024.0), 1) + "kb"; } else if (bytes <= (1024.0 * 1024.0 * 1024)) { return trimDouble((bytes / (1024.0 * 1024.0)), 1) + "mb"; } else if (bytes <= (1024.0 * 1024.0 * 1024.0 * 1024)) { return trimDouble((bytes / (1024.0 * 1024.0 * 1024.0)), 2) + "gb"; } else if (bytes <= (1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024)) { return trimDouble((bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0)), 2) + "tb"; } else { return trimDouble((bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0)), 3) + "pb"; } } private static double trimDouble(double d, int s) { BigDecimal bigDecimal = new BigDecimal(d); bigDecimal = bigDecimal.setScale(s, BigDecimal.ROUND_HALF_UP); return bigDecimal.doubleValue(); } public long getUsedHeapMem() { return usedHeapMem; } public long getMaxHeapMem() { return maxHeapMem; } public long getUsedEdenMem() { return usedEdenMem; } public long getMaxEdenMem() { return maxEdenMem; } public long getUsedSurvivorMem() { return usedSurvivorMem; } public long getMaxSurvivorMem() { return maxSurvivorMem; } public long getUsedOldGenMem() { return usedOldGenMem; } public long getMaxOldGenMem() { return maxOldGenMem; } public long getUsedMetaspaceMem() { return usedMetaspaceMem; } public long getMaxMetaspaceMem() { return maxMetaspaceMem; } public long getUsedNonHeapMem() { return usedNonHeapMem; } public long getMaxNonHeapMem() { return maxNonHeapMem; } public long getUsedSwapMem() { return usedSwapMem; } public long getMaxSwapMem() { return maxSwapMem; } public long getUsedPhysicalMem() { return usedPhysicalMem; } public long getMaxPhysicalMem() { return maxPhysicalMem; } public long getMaxDirectMem() { return maxDirectMem; } public long getUsedDirectMem() { return usedDirectMem; } public long getMaxMappedMem() { return maxMappedMem; } public long getUsedMappedMem() { return usedMappedMem; } }
pandening/Java-debug-tool
core/src/main/java/io/javadebug/core/data/JVMMemoryInfo.java
3,337
// init heap mem
line_comment
nl
// // ======================================================================== // Copyright (c) 2018-2019 HuJian/Pandening soft collection. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the #{license} Public License #{version} // EG: // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // You should bear the consequences of using the software (named 'java-debug-tool') // and any modify must be create an new pull request and attach an text to describe // the change detail. // ======================================================================== // package io.javadebug.core.data; import sun.management.ManagementFactoryHelper; import java.lang.management.BufferPoolMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.OperatingSystemMXBean; import java.math.BigDecimal; import java.util.List; /** * the memory information * * Auth : pandening * Date : 2020-01-11 23:37 */ public class JVMMemoryInfo { // heap size eden + survivor (from + to) + old private long usedHeapMem = -1; private long maxHeapMem = -1; // young -> eden private long usedEdenMem = -1; private long maxEdenMem = -1; // young -> survivor private long usedSurvivorMem = -1; private long maxSurvivorMem = -1; // old gen private long usedOldGenMem = -1; private long maxOldGenMem = -1; // metaspace private long usedMetaspaceMem = -1; private long maxMetaspaceMem = -1; // non-heap private long usedNonHeapMem = -1; private long maxNonHeapMem = -1; // physical (mem + swap) private long usedSwapMem = -1; private long maxSwapMem = -1; private long usedPhysicalMem = -1; private long maxPhysicalMem = -1; // direct & mapped private long maxDirectMem = -1; private long usedDirectMem = -1; private long maxMappedMem = -1; private long usedMappedMem = -1; public JVMMemoryInfo() { // init heap<SUF> usedHeapMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); maxHeapMem = Runtime.getRuntime().maxMemory(); // young gen [Eden] MemoryPoolMXBean youngGen = getSpecialGenMemoryPool("Eden"); if (youngGen != null) { usedEdenMem = youngGen.getUsage().getUsed(); maxEdenMem = youngGen.getUsage().getMax(); } // young gen [survivor] MemoryPoolMXBean survivorGen = getSpecialGenMemoryPool("Survivor"); if (survivorGen != null) { usedSurvivorMem = survivorGen.getUsage().getUsed(); maxSurvivorMem = survivorGen.getUsage().getMax(); } // metaspace MemoryPoolMXBean metaspace = getSpecialGenMemoryPool("Metaspace"); if (metaspace != null) { usedMetaspaceMem = metaspace.getUsage().getUsed(); maxMetaspaceMem = metaspace.getUsage().getMax(); } // old gen MemoryPoolMXBean oldGen = getSpecialGenMemoryPool("Old"); if (oldGen != null) { usedOldGenMem = oldGen.getUsage().getUsed(); maxOldGenMem = oldGen.getUsage().getMax(); } // non-heap usedNonHeapMem = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getUsed(); maxNonHeapMem = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage().getMax(); // direct & mapped List<BufferPoolMXBean> bufferPoolMXBeanList = ManagementFactoryHelper.getBufferPoolMXBeans(); BufferPoolMXBean directPool = getDirectOrMappedMem(bufferPoolMXBeanList, "direct"); BufferPoolMXBean mappedPool = getDirectOrMappedMem(bufferPoolMXBeanList, "mapped"); if (directPool != null) { maxDirectMem = directPool.getTotalCapacity(); usedDirectMem = directPool.getMemoryUsed(); } if (mappedPool != null) { maxMappedMem = mappedPool.getTotalCapacity(); usedMappedMem = mappedPool.getMemoryUsed(); } // physic OperatingSystemMXBean operatingSystem = ManagementFactory.getOperatingSystemMXBean(); if (operatingSystem instanceof com.sun.management.OperatingSystemMXBean) { usedPhysicalMem = ((com.sun.management.OperatingSystemMXBean) operatingSystem).getTotalPhysicalMemorySize() - ((com.sun.management.OperatingSystemMXBean) operatingSystem).getFreePhysicalMemorySize(); maxPhysicalMem = ((com.sun.management.OperatingSystemMXBean) operatingSystem).getTotalPhysicalMemorySize(); usedSwapMem = ((com.sun.management.OperatingSystemMXBean) operatingSystem).getTotalSwapSpaceSize() - ((com.sun.management.OperatingSystemMXBean) operatingSystem).getFreeSwapSpaceSize(); maxSwapMem = ((com.sun.management.OperatingSystemMXBean) operatingSystem).getTotalSwapSpaceSize(); } } /** * "direct" * "mapped" * * @param bufferPoolMXBeanList {@link ManagementFactoryHelper#getBufferPoolMXBeans()} * @param key which pool * @return the target pool */ private static BufferPoolMXBean getDirectOrMappedMem(List<BufferPoolMXBean> bufferPoolMXBeanList, String key) { for (BufferPoolMXBean bufferPoolMXBean : bufferPoolMXBeanList) { if (bufferPoolMXBean.getName().contains(key)) { return bufferPoolMXBean; } } return null; } /** * get special gen memory pool {@link MemoryPoolMXBean} * * @param gen the target gen like 'Old Gen' / 'Old' * @return the target pool, maybe null */ private static MemoryPoolMXBean getSpecialGenMemoryPool(String gen) { for (final MemoryPoolMXBean memoryPool : ManagementFactory.getMemoryPoolMXBeans()) { if (memoryPool.getName().contains(gen)) { return memoryPool; } } return null; } private static final String MEM_SHOW_FORMAT = "%-30.30s " + "%-30.30s " + "%-30.30s"; private static final String MEM_TITLE = String.format(MEM_SHOW_FORMAT, "Heap", "Non-Heap", "Physical"); @Override public String toString() { String ph = String.format(MEM_SHOW_FORMAT, "--------", "--------", "--------"); StringBuilder rsb = new StringBuilder(); // header rsb.append(ph).append("\n").append(MEM_TITLE).append("\n").append(ph).append("\n"); // line 1 String line = String.format(MEM_SHOW_FORMAT, "|_Heap :[" + tramMem(maxHeapMem) + "," + tramMem(usedHeapMem) + "]", "|_NonHeap :[" + tramMem(maxNonHeapMem) + "," + tramMem(usedNonHeapMem) + "]", "|_Physical :[" + tramMem(maxPhysicalMem) + "," + tramMem(usedPhysicalMem) + "]" ); rsb.append(line).append("\n"); // line 2 line = String.format(MEM_SHOW_FORMAT, "|_Eden :[" + tramMem(maxEdenMem) + "," + tramMem(usedEdenMem) + "]", "|_Direct :[" + tramMem(maxDirectMem) + "," + tramMem(usedDirectMem) + "]", "|_Swap :[" + tramMem(maxSwapMem) + "," + tramMem(usedSwapMem) + "]" ); rsb.append(line).append("\n"); // line 3 line = String.format(MEM_SHOW_FORMAT, "|_Survivor :[" + tramMem(maxSurvivorMem) + "," + tramMem(usedSurvivorMem) + "]", "|_Mapped :[" + tramMem(maxMappedMem) + "," + tramMem(usedMappedMem) + "]", "" ); rsb.append(line).append("\n"); // line 4 line = String.format(MEM_SHOW_FORMAT, "|_OldGen :[" + tramMem(maxOldGenMem) + "," + tramMem(usedOldGenMem) + "]", "|_Metaspace :[" + tramMem(maxMetaspaceMem) + "," + tramMem(usedMetaspaceMem) + "]", "" ); rsb.append(line).append("\n"); //result return rsb.toString(); } private static String tramMem(long bytes) { if (bytes < 0) { return bytes + ""; } if (bytes <= 1024) { // b return bytes + " b"; } else if (bytes <= (1024.0 * 1024.0)) { return trimDouble((bytes) / (1024.0 * 1024.0), 1) + "kb"; } else if (bytes <= (1024.0 * 1024.0 * 1024)) { return trimDouble((bytes / (1024.0 * 1024.0)), 1) + "mb"; } else if (bytes <= (1024.0 * 1024.0 * 1024.0 * 1024)) { return trimDouble((bytes / (1024.0 * 1024.0 * 1024.0)), 2) + "gb"; } else if (bytes <= (1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024)) { return trimDouble((bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0)), 2) + "tb"; } else { return trimDouble((bytes / (1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0)), 3) + "pb"; } } private static double trimDouble(double d, int s) { BigDecimal bigDecimal = new BigDecimal(d); bigDecimal = bigDecimal.setScale(s, BigDecimal.ROUND_HALF_UP); return bigDecimal.doubleValue(); } public long getUsedHeapMem() { return usedHeapMem; } public long getMaxHeapMem() { return maxHeapMem; } public long getUsedEdenMem() { return usedEdenMem; } public long getMaxEdenMem() { return maxEdenMem; } public long getUsedSurvivorMem() { return usedSurvivorMem; } public long getMaxSurvivorMem() { return maxSurvivorMem; } public long getUsedOldGenMem() { return usedOldGenMem; } public long getMaxOldGenMem() { return maxOldGenMem; } public long getUsedMetaspaceMem() { return usedMetaspaceMem; } public long getMaxMetaspaceMem() { return maxMetaspaceMem; } public long getUsedNonHeapMem() { return usedNonHeapMem; } public long getMaxNonHeapMem() { return maxNonHeapMem; } public long getUsedSwapMem() { return usedSwapMem; } public long getMaxSwapMem() { return maxSwapMem; } public long getUsedPhysicalMem() { return usedPhysicalMem; } public long getMaxPhysicalMem() { return maxPhysicalMem; } public long getMaxDirectMem() { return maxDirectMem; } public long getUsedDirectMem() { return usedDirectMem; } public long getMaxMappedMem() { return maxMappedMem; } public long getUsedMappedMem() { return usedMappedMem; } }
797_41
import java.util.ArrayList; import java.util.PriorityQueue; import java.util.LinkedList; import java.util.Arrays; public class l001 { public static class Edge { int v, w; Edge(int v, int w) { this.v = v; this.w = w; } } public static void addEdge(ArrayList<Edge>[] graph, int u, int v, int w) { graph[u].add(new Edge(v, w)); graph[v].add(new Edge(u, w)); } public static void display(ArrayList<Edge>[] graph) { for (int i = 0; i < graph.length; i++) { System.out.print(i + " -> "); for (Edge e : graph[i]) { System.out.print("(" + e.v + ", " + e.w + ") "); } System.out.println(); } } public static int findVtx(ArrayList<Edge>[] graph, int u, int v) { int idx = -1; ArrayList<Edge> al = graph[u]; for (int i = 0; i < al.size(); i++) { Edge e = al.get(i); if (e.v == v) { idx = i; break; } } return idx; } public static void removeEdge(ArrayList<Edge>[] graph, int u, int v) { int idx1 = findVtx(graph, u, v); int idx2 = findVtx(graph, v, u); graph[u].remove(idx1); graph[v].remove(idx2); } public static void removeVtx(ArrayList<Edge>[] graph, int u) { ArrayList<Edge> al = graph[u]; while (al.size() != 0) { int v = al.get(al.size() - 1).v; removeEdge(graph, u, v); } } public static boolean hasPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis) { if (src == dest) return true; vis[src] = true; boolean res = false; for (Edge e : graph[src]) { if (!vis[e.v]) res = res || hasPath(graph, e.v, dest, vis); } return res; } public static int printAllPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis, String ans) { if (src == dest) { System.out.println(ans + dest); return 1; } int count = 0; vis[src] = true; for (Edge e : graph[src]) { if (!vis[e.v]) { count += printAllPath(graph, e.v, dest, vis, ans + src); } } vis[src] = false; return count; } public static void printpreOrder(ArrayList<Edge>[] graph, int src, int wsf, boolean[] vis, String ans) { System.out.println(src + " -> " + ans + src + "@" + wsf); vis[src] = true; for (Edge e : graph[src]) { if (!vis[e.v]) printpreOrder(graph, e.v, wsf + e.w, vis, ans + src); } vis[src] = false; } public static class pair { String psf = ""; int wsf = 0; pair(String psf, int wsf) { this.wsf = wsf; this.psf = psf; } pair() { } } public static pair heavyWeightPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis) { if (src == dest) { return new pair(src + "", 0); } vis[src] = true; pair myAns = new pair("", -(int) 1e9); for (Edge e : graph[src]) { if (!vis[e.v]) { pair recAns = heavyWeightPath(graph, e.v, dest, vis); if (recAns.wsf != -(int) 1e9 && recAns.wsf + e.w > myAns.wsf) { myAns.wsf = recAns.wsf + e.w; myAns.psf = src + recAns.psf; } } } vis[src] = false; return myAns; } public static pair lightWeightPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis) { if (src == dest) { return new pair(src + "", 0); } vis[src] = true; pair myAns = new pair("", (int) 1e9); for (Edge e : graph[src]) { if (!vis[e.v]) { pair recAns = lightWeightPath(graph, e.v, dest, vis); if (recAns.wsf != -(int) 1e9 && recAns.wsf + e.w < myAns.wsf) { myAns.wsf = recAns.wsf + e.w; myAns.psf = src + recAns.psf; } } } vis[src] = false; return myAns; } // static class Pair implements Comparable<Pair> { // int wsf; // String psf; // Pair(int wsf, String psf) { // this.wsf = wsf; // this.psf = psf; // } // public int compareTo(Pair o) { // return this.wsf - o.wsf; // } // } // static String spath; // static Integer spathwt = Integer.MAX_VALUE; // static String lpath; // static Integer lpathwt = Integer.MIN_VALUE; // static String cpath; // static Integer cpathwt = Integer.MAX_VALUE; // static String fpath; // static Integer fpathwt = Integer.MIN_VALUE; // static PriorityQueue<Pair> pq = new PriorityQueue<>(); // public static void multisolver(ArrayList<Edge>[] graph, int src, int dest, // boolean[] vis, int criteria, int k, // String psf, int wsf) { // if (src == dest) { // if (wsf < spathwt) { // spathwt = wsf; // spath = psf; // } // if (lpathwt < wsf) { // lpathwt = wsf; // lpath = psf; // } // if (wsf < criteria && wsf > fpathwt) { // fpathwt = wsf; // fpath = psf; // } // if (wsf > criteria && wsf < cpathwt) { // cpathwt = wsf; // cpath = psf; // } // pq.add(new Pair(wsf, psf)); // if (pq.size() > k) // pq.remove(); // return; // } // vis[src] = true; // for (Edge e : graph[src]) { // if (!vis[e.v]) // multisolver(graph, e.v, dest, vis, criteria, k, psf + e.v, wsf + e.w); // } // vis[src] = false; // } // Get Connected Components public static void dfs(ArrayList<Edge>[] graph, int src, boolean[] vis) { vis[src] = true; for (Edge e : graph[src]) { if (!vis[e.v]) dfs(graph, e.v, vis); } } public static int GCC(ArrayList<Edge>[] graph) { int N = graph.length; boolean[] vis = new boolean[N]; int components = 0; for (int i = 0; i < N; i++) { if (!vis[i]) { components++; dfs(graph, i, vis); } } return components; } public static int dfs_hamintonianPath(ArrayList<Edge>[] graph, boolean[] vis, int src, int osrc, int count, String psf) { if (count == graph.length - 1) { int idx = findVtx(graph, src, osrc); if (idx != -1) System.out.println(psf + "*"); else System.out.println(psf + "."); return 1; } int totalPaths = 0; vis[src] = true; for (Edge e : graph[src]) { if (!vis[e.v]) { totalPaths += dfs_hamintonianPath(graph, vis, e.v, osrc, count + 1, psf + e.v); } } vis[src] = false; return totalPaths; } // Hamintonian Path public static void hamintonianPath(int src, ArrayList<Edge>[] graph, int N) { boolean[] vis = new boolean[N]; dfs_hamintonianPath(graph, vis, src, src, 0, src + ""); } // BFS.=========================================================== public static void BFS(ArrayList<Edge>[] graph, int src, boolean[] vis) { LinkedList<Integer> que = new LinkedList<>(); // que -> addLast, removeFirst que.addLast(src); int level = 0; boolean isCycle = false; while (que.size() != 0) { int size = que.size(); System.out.print(level + " No Of Edges Required for: "); while (size-- > 0) { Integer rvtx = que.removeFirst(); if (vis[rvtx]) { isCycle = true; continue; } System.out.print(rvtx + " "); vis[rvtx] = true; for (Edge e : graph[rvtx]) { if (!vis[e.v]) que.addLast(e.v); } } level++; System.out.println(); } } public static void BFS_forNoCycle(ArrayList<Edge>[] graph, int src, boolean[] vis) { LinkedList<Integer> que = new LinkedList<>(); // que -> addLast, removeFirst que.addLast(src); vis[src] = true; int level = 0; while (que.size() != 0) { int size = que.size(); System.out.print(level + " No Of Edges Required for: "); while (size-- > 0) { Integer rvtx = que.removeFirst(); System.out.print(rvtx + " "); for (Edge e : graph[rvtx]) { if (!vis[e.v]) { vis[e.v] = true; que.addLast(e.v); } } } level++; System.out.println(); } } public static boolean isBipartite(ArrayList<Edge>[] graph, int src, int[] vis) { LinkedList<Integer> que = new LinkedList<>(); // que -> addLast, removeFirst que.addLast(src); int color = 0; // 0 -> red, 1 -> green boolean isBipartite = true; while (que.size() != 0) { int size = que.size(); while (size != 0) { int rvtx = que.removeFirst(); if (vis[rvtx] != -1) { if (vis[rvtx] != color) isBipartite = false; continue; } vis[rvtx] = color; for (Edge e : graph[rvtx]) { if (vis[e.v] == -1) que.addLast(e.v); } } color = (color + 1) % 2; } return isBipartite; } public static boolean isBipartit(ArrayList<Edge>[] graph) { int[] vis = new int[graph.length]; Arrays.fill(vis, -1); for (int i = 0; i < graph.length; i++) { if (vis[i] == -1) { if (!isBipartite(graph, i, vis)) return false; } } return true; } public static class diji_pair implements Comparable<diji_pair> { int vtx, par, wt, wsf; String psf; diji_pair(int vtx, int par, int wt, int wsf, String psf) { this.vtx = vtx; this.par = par; this.wt = wt; this.wsf = wsf; this.psf = psf; } @Override public int compareTo(diji_pair o) { return this.wsf - o.wsf; } } public static void dijikstrAlgo_01(ArrayList<Edge>[] graph, int src) { int N = 7; ArrayList<Edge>[] myGraph = new ArrayList[N]; for (int i = 0; i < N; i++) myGraph[i] = new ArrayList<>(); boolean[] vis = new boolean[N]; PriorityQueue<diji_pair> pq = new PriorityQueue<>(); pq.add(new diji_pair(src, -1, 0, 0, src + "")); int[] dis = new int[N]; while (pq.size() != 0) { diji_pair rp = pq.remove(); if (vis[rp.vtx]) continue; if (rp.par != -1) addEdge(myGraph, rp.vtx, rp.par, rp.wt); System.out.println(rp.vtx + " via " + rp.psf + " @ " + rp.wsf); dis[rp.vtx] = rp.wsf; vis[rp.vtx] = true; for (Edge e : graph[rp.vtx]) { if (!vis[e.v]) pq.add(new diji_pair(e.v, rp.vtx, e.w, rp.wsf + e.w, rp.psf + e.v)); } } display(myGraph); for (int ele : dis) System.out.print(ele + " "); } public static int[] dijikstrAlgo_forQuestionSolving(ArrayList<Edge>[] graph, int src) { int N = graph.length; boolean[] vis = new boolean[N]; PriorityQueue<diji_pair> pq = new PriorityQueue<>(); pq.add(new diji_pair(src, -1, 0, 0, src + "")); int[] dis = new int[N]; while (pq.size() != 0) { diji_pair rp = pq.remove(); if (vis[rp.vtx]) continue; dis[rp.vtx] = rp.wsf; vis[rp.vtx] = true; for (Edge e : graph[rp.vtx]) { if (!vis[e.v]) pq.add(new diji_pair(e.v, rp.vtx, e.w, rp.wsf + e.w, rp.psf + e.v)); } } return dis; } public static class diji_pair2 implements Comparable<diji_pair2> { int vtx, wsf; diji_pair2(int vtx, int wsf) { this.vtx = vtx; this.wsf = wsf; } @Override public int compareTo(diji_pair2 o) { return this.wsf - o.wsf; } } public static int[] dijikstrAlgo_bestMethod(ArrayList<Edge>[] graph, int src) { int N = graph.length; PriorityQueue<diji_pair2> pq = new PriorityQueue<>(); int[] dis = new int[N]; int[] par = new int[N]; boolean[] vis = new boolean[N]; Arrays.fill(dis, (int) 1e9); Arrays.fill(par, -1); pq.add(new diji_pair2(src, 0)); dis[src] = 0; while (pq.size() != 0) { diji_pair2 rp = pq.remove(); if (vis[rp.vtx]) continue; vis[rp.vtx] = true; for (Edge e : graph[rp.vtx]) { if (!vis[e.v] && e.w + rp.wsf < dis[e.v]) { dis[e.v] = e.w + rp.wsf; par[e.v] = rp.vtx; pq.add(new diji_pair2(e.v, rp.wsf + e.w)); } } } return dis; } private static class primsPair { int vtx, wt; primsPair(int vtx, int wt) { this.vtx = vtx; this.wt = wt; } } private static void prims(ArrayList<Edge>[] graph, int src, ArrayList<Edge>[] primsGraph, boolean[] vis) { int N = graph.length; PriorityQueue<primsPair> pq = new PriorityQueue<>((a, b) -> { return a.wt - b.wt; }); int[] dis = new int[N]; int[] par = new int[N]; Arrays.fill(dis, (int) 1e9); Arrays.fill(par, -1); pq.add(new primsPair(src, 0)); dis[src] = 0; while (pq.size() != 0) { primsPair p = pq.remove(); if (vis[p.vtx]) continue; vis[p.vtx] = true; for (Edge e : graph[p.vtx]) { if (!vis[e.v] && e.w < dis[e.v]) { dis[e.v] = e.w; par[e.v] = p.vtx; pq.add(new primsPair(e.v, e.w)); } } } } public static void prims(ArrayList<Edge>[] graph) { int N = 7; ArrayList<Edge>[] primsg = new ArrayList[N]; for (int i = 0; i < N; i++) primsg[i] = new ArrayList<>(); boolean[] vis = new boolean[N]; for (int i = 0; i < N; i++) { if (!vis[i]) { prims(graph, i, primsg, vis); } } display(primsg); } public static void graphConstruct() { int N = 7; ArrayList<Edge>[] graph = new ArrayList[N]; for (int i = 0; i < N; i++) graph[i] = new ArrayList<>(); addEdge(graph, 0, 1, 10); addEdge(graph, 0, 3, 40); addEdge(graph, 1, 2, 10); addEdge(graph, 2, 3, 10); addEdge(graph, 3, 4, 2); addEdge(graph, 4, 5, 3); addEdge(graph, 5, 6, 3); addEdge(graph, 4, 6, 8); addEdge(graph, 2, 5, 5); display(graph); // boolean[] vis = new boolean[N]; // System.out.println(printAllPath(graph, 0, 6, vis, "")); // printpreOrder(graph, 0, 0, vis, ""); // pair ans = heavyWeightPath(graph, 0, 6, vis); // pair ans = lightWeightPath(graph, 0, 6, vis); // if (ans.wsf != -(int) 1e9) // System.out.println(ans.psf + "@" + ans.wsf); // hamintonianPath(0, graph, N); // BFS(graph, 0, vis); System.out.println(); dijikstrAlgo_01(graph, 0); } public static void main(String[] args) { graphConstruct(); } }
pankajmahato/pepcoding-Batches
2020/NIET/graph/l001.java
5,566
// 0 -> red, 1 -> green
line_comment
nl
import java.util.ArrayList; import java.util.PriorityQueue; import java.util.LinkedList; import java.util.Arrays; public class l001 { public static class Edge { int v, w; Edge(int v, int w) { this.v = v; this.w = w; } } public static void addEdge(ArrayList<Edge>[] graph, int u, int v, int w) { graph[u].add(new Edge(v, w)); graph[v].add(new Edge(u, w)); } public static void display(ArrayList<Edge>[] graph) { for (int i = 0; i < graph.length; i++) { System.out.print(i + " -> "); for (Edge e : graph[i]) { System.out.print("(" + e.v + ", " + e.w + ") "); } System.out.println(); } } public static int findVtx(ArrayList<Edge>[] graph, int u, int v) { int idx = -1; ArrayList<Edge> al = graph[u]; for (int i = 0; i < al.size(); i++) { Edge e = al.get(i); if (e.v == v) { idx = i; break; } } return idx; } public static void removeEdge(ArrayList<Edge>[] graph, int u, int v) { int idx1 = findVtx(graph, u, v); int idx2 = findVtx(graph, v, u); graph[u].remove(idx1); graph[v].remove(idx2); } public static void removeVtx(ArrayList<Edge>[] graph, int u) { ArrayList<Edge> al = graph[u]; while (al.size() != 0) { int v = al.get(al.size() - 1).v; removeEdge(graph, u, v); } } public static boolean hasPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis) { if (src == dest) return true; vis[src] = true; boolean res = false; for (Edge e : graph[src]) { if (!vis[e.v]) res = res || hasPath(graph, e.v, dest, vis); } return res; } public static int printAllPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis, String ans) { if (src == dest) { System.out.println(ans + dest); return 1; } int count = 0; vis[src] = true; for (Edge e : graph[src]) { if (!vis[e.v]) { count += printAllPath(graph, e.v, dest, vis, ans + src); } } vis[src] = false; return count; } public static void printpreOrder(ArrayList<Edge>[] graph, int src, int wsf, boolean[] vis, String ans) { System.out.println(src + " -> " + ans + src + "@" + wsf); vis[src] = true; for (Edge e : graph[src]) { if (!vis[e.v]) printpreOrder(graph, e.v, wsf + e.w, vis, ans + src); } vis[src] = false; } public static class pair { String psf = ""; int wsf = 0; pair(String psf, int wsf) { this.wsf = wsf; this.psf = psf; } pair() { } } public static pair heavyWeightPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis) { if (src == dest) { return new pair(src + "", 0); } vis[src] = true; pair myAns = new pair("", -(int) 1e9); for (Edge e : graph[src]) { if (!vis[e.v]) { pair recAns = heavyWeightPath(graph, e.v, dest, vis); if (recAns.wsf != -(int) 1e9 && recAns.wsf + e.w > myAns.wsf) { myAns.wsf = recAns.wsf + e.w; myAns.psf = src + recAns.psf; } } } vis[src] = false; return myAns; } public static pair lightWeightPath(ArrayList<Edge>[] graph, int src, int dest, boolean[] vis) { if (src == dest) { return new pair(src + "", 0); } vis[src] = true; pair myAns = new pair("", (int) 1e9); for (Edge e : graph[src]) { if (!vis[e.v]) { pair recAns = lightWeightPath(graph, e.v, dest, vis); if (recAns.wsf != -(int) 1e9 && recAns.wsf + e.w < myAns.wsf) { myAns.wsf = recAns.wsf + e.w; myAns.psf = src + recAns.psf; } } } vis[src] = false; return myAns; } // static class Pair implements Comparable<Pair> { // int wsf; // String psf; // Pair(int wsf, String psf) { // this.wsf = wsf; // this.psf = psf; // } // public int compareTo(Pair o) { // return this.wsf - o.wsf; // } // } // static String spath; // static Integer spathwt = Integer.MAX_VALUE; // static String lpath; // static Integer lpathwt = Integer.MIN_VALUE; // static String cpath; // static Integer cpathwt = Integer.MAX_VALUE; // static String fpath; // static Integer fpathwt = Integer.MIN_VALUE; // static PriorityQueue<Pair> pq = new PriorityQueue<>(); // public static void multisolver(ArrayList<Edge>[] graph, int src, int dest, // boolean[] vis, int criteria, int k, // String psf, int wsf) { // if (src == dest) { // if (wsf < spathwt) { // spathwt = wsf; // spath = psf; // } // if (lpathwt < wsf) { // lpathwt = wsf; // lpath = psf; // } // if (wsf < criteria && wsf > fpathwt) { // fpathwt = wsf; // fpath = psf; // } // if (wsf > criteria && wsf < cpathwt) { // cpathwt = wsf; // cpath = psf; // } // pq.add(new Pair(wsf, psf)); // if (pq.size() > k) // pq.remove(); // return; // } // vis[src] = true; // for (Edge e : graph[src]) { // if (!vis[e.v]) // multisolver(graph, e.v, dest, vis, criteria, k, psf + e.v, wsf + e.w); // } // vis[src] = false; // } // Get Connected Components public static void dfs(ArrayList<Edge>[] graph, int src, boolean[] vis) { vis[src] = true; for (Edge e : graph[src]) { if (!vis[e.v]) dfs(graph, e.v, vis); } } public static int GCC(ArrayList<Edge>[] graph) { int N = graph.length; boolean[] vis = new boolean[N]; int components = 0; for (int i = 0; i < N; i++) { if (!vis[i]) { components++; dfs(graph, i, vis); } } return components; } public static int dfs_hamintonianPath(ArrayList<Edge>[] graph, boolean[] vis, int src, int osrc, int count, String psf) { if (count == graph.length - 1) { int idx = findVtx(graph, src, osrc); if (idx != -1) System.out.println(psf + "*"); else System.out.println(psf + "."); return 1; } int totalPaths = 0; vis[src] = true; for (Edge e : graph[src]) { if (!vis[e.v]) { totalPaths += dfs_hamintonianPath(graph, vis, e.v, osrc, count + 1, psf + e.v); } } vis[src] = false; return totalPaths; } // Hamintonian Path public static void hamintonianPath(int src, ArrayList<Edge>[] graph, int N) { boolean[] vis = new boolean[N]; dfs_hamintonianPath(graph, vis, src, src, 0, src + ""); } // BFS.=========================================================== public static void BFS(ArrayList<Edge>[] graph, int src, boolean[] vis) { LinkedList<Integer> que = new LinkedList<>(); // que -> addLast, removeFirst que.addLast(src); int level = 0; boolean isCycle = false; while (que.size() != 0) { int size = que.size(); System.out.print(level + " No Of Edges Required for: "); while (size-- > 0) { Integer rvtx = que.removeFirst(); if (vis[rvtx]) { isCycle = true; continue; } System.out.print(rvtx + " "); vis[rvtx] = true; for (Edge e : graph[rvtx]) { if (!vis[e.v]) que.addLast(e.v); } } level++; System.out.println(); } } public static void BFS_forNoCycle(ArrayList<Edge>[] graph, int src, boolean[] vis) { LinkedList<Integer> que = new LinkedList<>(); // que -> addLast, removeFirst que.addLast(src); vis[src] = true; int level = 0; while (que.size() != 0) { int size = que.size(); System.out.print(level + " No Of Edges Required for: "); while (size-- > 0) { Integer rvtx = que.removeFirst(); System.out.print(rvtx + " "); for (Edge e : graph[rvtx]) { if (!vis[e.v]) { vis[e.v] = true; que.addLast(e.v); } } } level++; System.out.println(); } } public static boolean isBipartite(ArrayList<Edge>[] graph, int src, int[] vis) { LinkedList<Integer> que = new LinkedList<>(); // que -> addLast, removeFirst que.addLast(src); int color = 0; // 0 -><SUF> boolean isBipartite = true; while (que.size() != 0) { int size = que.size(); while (size != 0) { int rvtx = que.removeFirst(); if (vis[rvtx] != -1) { if (vis[rvtx] != color) isBipartite = false; continue; } vis[rvtx] = color; for (Edge e : graph[rvtx]) { if (vis[e.v] == -1) que.addLast(e.v); } } color = (color + 1) % 2; } return isBipartite; } public static boolean isBipartit(ArrayList<Edge>[] graph) { int[] vis = new int[graph.length]; Arrays.fill(vis, -1); for (int i = 0; i < graph.length; i++) { if (vis[i] == -1) { if (!isBipartite(graph, i, vis)) return false; } } return true; } public static class diji_pair implements Comparable<diji_pair> { int vtx, par, wt, wsf; String psf; diji_pair(int vtx, int par, int wt, int wsf, String psf) { this.vtx = vtx; this.par = par; this.wt = wt; this.wsf = wsf; this.psf = psf; } @Override public int compareTo(diji_pair o) { return this.wsf - o.wsf; } } public static void dijikstrAlgo_01(ArrayList<Edge>[] graph, int src) { int N = 7; ArrayList<Edge>[] myGraph = new ArrayList[N]; for (int i = 0; i < N; i++) myGraph[i] = new ArrayList<>(); boolean[] vis = new boolean[N]; PriorityQueue<diji_pair> pq = new PriorityQueue<>(); pq.add(new diji_pair(src, -1, 0, 0, src + "")); int[] dis = new int[N]; while (pq.size() != 0) { diji_pair rp = pq.remove(); if (vis[rp.vtx]) continue; if (rp.par != -1) addEdge(myGraph, rp.vtx, rp.par, rp.wt); System.out.println(rp.vtx + " via " + rp.psf + " @ " + rp.wsf); dis[rp.vtx] = rp.wsf; vis[rp.vtx] = true; for (Edge e : graph[rp.vtx]) { if (!vis[e.v]) pq.add(new diji_pair(e.v, rp.vtx, e.w, rp.wsf + e.w, rp.psf + e.v)); } } display(myGraph); for (int ele : dis) System.out.print(ele + " "); } public static int[] dijikstrAlgo_forQuestionSolving(ArrayList<Edge>[] graph, int src) { int N = graph.length; boolean[] vis = new boolean[N]; PriorityQueue<diji_pair> pq = new PriorityQueue<>(); pq.add(new diji_pair(src, -1, 0, 0, src + "")); int[] dis = new int[N]; while (pq.size() != 0) { diji_pair rp = pq.remove(); if (vis[rp.vtx]) continue; dis[rp.vtx] = rp.wsf; vis[rp.vtx] = true; for (Edge e : graph[rp.vtx]) { if (!vis[e.v]) pq.add(new diji_pair(e.v, rp.vtx, e.w, rp.wsf + e.w, rp.psf + e.v)); } } return dis; } public static class diji_pair2 implements Comparable<diji_pair2> { int vtx, wsf; diji_pair2(int vtx, int wsf) { this.vtx = vtx; this.wsf = wsf; } @Override public int compareTo(diji_pair2 o) { return this.wsf - o.wsf; } } public static int[] dijikstrAlgo_bestMethod(ArrayList<Edge>[] graph, int src) { int N = graph.length; PriorityQueue<diji_pair2> pq = new PriorityQueue<>(); int[] dis = new int[N]; int[] par = new int[N]; boolean[] vis = new boolean[N]; Arrays.fill(dis, (int) 1e9); Arrays.fill(par, -1); pq.add(new diji_pair2(src, 0)); dis[src] = 0; while (pq.size() != 0) { diji_pair2 rp = pq.remove(); if (vis[rp.vtx]) continue; vis[rp.vtx] = true; for (Edge e : graph[rp.vtx]) { if (!vis[e.v] && e.w + rp.wsf < dis[e.v]) { dis[e.v] = e.w + rp.wsf; par[e.v] = rp.vtx; pq.add(new diji_pair2(e.v, rp.wsf + e.w)); } } } return dis; } private static class primsPair { int vtx, wt; primsPair(int vtx, int wt) { this.vtx = vtx; this.wt = wt; } } private static void prims(ArrayList<Edge>[] graph, int src, ArrayList<Edge>[] primsGraph, boolean[] vis) { int N = graph.length; PriorityQueue<primsPair> pq = new PriorityQueue<>((a, b) -> { return a.wt - b.wt; }); int[] dis = new int[N]; int[] par = new int[N]; Arrays.fill(dis, (int) 1e9); Arrays.fill(par, -1); pq.add(new primsPair(src, 0)); dis[src] = 0; while (pq.size() != 0) { primsPair p = pq.remove(); if (vis[p.vtx]) continue; vis[p.vtx] = true; for (Edge e : graph[p.vtx]) { if (!vis[e.v] && e.w < dis[e.v]) { dis[e.v] = e.w; par[e.v] = p.vtx; pq.add(new primsPair(e.v, e.w)); } } } } public static void prims(ArrayList<Edge>[] graph) { int N = 7; ArrayList<Edge>[] primsg = new ArrayList[N]; for (int i = 0; i < N; i++) primsg[i] = new ArrayList<>(); boolean[] vis = new boolean[N]; for (int i = 0; i < N; i++) { if (!vis[i]) { prims(graph, i, primsg, vis); } } display(primsg); } public static void graphConstruct() { int N = 7; ArrayList<Edge>[] graph = new ArrayList[N]; for (int i = 0; i < N; i++) graph[i] = new ArrayList<>(); addEdge(graph, 0, 1, 10); addEdge(graph, 0, 3, 40); addEdge(graph, 1, 2, 10); addEdge(graph, 2, 3, 10); addEdge(graph, 3, 4, 2); addEdge(graph, 4, 5, 3); addEdge(graph, 5, 6, 3); addEdge(graph, 4, 6, 8); addEdge(graph, 2, 5, 5); display(graph); // boolean[] vis = new boolean[N]; // System.out.println(printAllPath(graph, 0, 6, vis, "")); // printpreOrder(graph, 0, 0, vis, ""); // pair ans = heavyWeightPath(graph, 0, 6, vis); // pair ans = lightWeightPath(graph, 0, 6, vis); // if (ans.wsf != -(int) 1e9) // System.out.println(ans.psf + "@" + ans.wsf); // hamintonianPath(0, graph, N); // BFS(graph, 0, vis); System.out.println(); dijikstrAlgo_01(graph, 0); } public static void main(String[] args) { graphConstruct(); } }
52688_2
package infoborden; import javafx.application.Application; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.stage.Stage; import tijdtools.InfobordTijdFuncties; public class Infobord extends Application{ private String titel = "Bushalte XX in richting YY"; private Text tijdRegel = new Text("00:00:00"); private Text infoRegel1 = new Text("De eestevolgende bus"); private Text infoRegel2 = new Text("De tweede bus"); private Text infoRegel3 = new Text("De derde bus"); private Text infoRegel4 = new Text("De vierde bus"); private String halte; private String richting; private Berichten berichten; public Infobord(String halte, String richting) { this.titel = "Bushalte " + halte + " in richting " + richting; this.halte=halte; this.richting=richting; this.berichten=new Berichten(); } public void verwerkBericht() { if (berichten.hetBordMoetVerverst()) { String[] infoTekstRegels = berichten.repaintInfoBordValues(); // Deze code hoort bij opdracht 3 // InfobordTijdFuncties tijdfuncties = new InfobordTijdFuncties(); // String tijd = tijdfuncties.getCentralTime().toString(); // tijdRegel.setText(tijd); infoRegel1.setText(infoTekstRegels[0]); infoRegel2.setText(infoTekstRegels[1]); infoRegel3.setText(infoTekstRegels[2]); infoRegel4.setText(infoTekstRegels[3]); }; } public void updateBord() { Runnable updater = new Runnable() { @Override public void run() { verwerkBericht(); } }; Platform.runLater(updater); } @Override public void start(Stage primaryStage) { String selector = ""; if (halte.length() == 1) selector += "(HALTE='"+halte+"')"; if (halte.length() == 1 && richting.length() <= 2) selector += " AND "; if (richting.length() <= 2) selector += "(RICHTING='"+richting+"')"; thread(new ListenerStarter(selector, this, berichten),false); GridPane pane = new GridPane(); pane.setAlignment(Pos.CENTER_LEFT); pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5)); pane.setHgap(5.5); pane.setVgap(5.5); // Place nodes in the pane pane.add(new Label("Voor het laatst bijgewerkt op :"), 0, 0); pane.add(tijdRegel, 1, 0); pane.add(new Label("1:"), 0, 1); pane.add(infoRegel1, 1, 1); pane.add(new Label("2:"), 0, 2); pane.add(infoRegel2, 1, 2); pane.add(new Label("3:"), 0, 3); pane.add(infoRegel3, 1, 3); pane.add(new Label("4:"), 0, 4); pane.add(infoRegel4, 1, 4); // Create a scene and place it in the stage Scene scene = new Scene(pane,500,150); primaryStage.setTitle(titel); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } public void thread(Runnable runnable, boolean daemon) { Thread brokerThread = new Thread(runnable); brokerThread.setDaemon(daemon); brokerThread.start(); } }
pannekoekmetijsappelmoesenslagroom/EAI
eai_bussimulatorStudenten/InfobordSysteem/infoborden/Infobord.java
1,195
// String tijd = tijdfuncties.getCentralTime().toString();
line_comment
nl
package infoborden; import javafx.application.Application; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.stage.Stage; import tijdtools.InfobordTijdFuncties; public class Infobord extends Application{ private String titel = "Bushalte XX in richting YY"; private Text tijdRegel = new Text("00:00:00"); private Text infoRegel1 = new Text("De eestevolgende bus"); private Text infoRegel2 = new Text("De tweede bus"); private Text infoRegel3 = new Text("De derde bus"); private Text infoRegel4 = new Text("De vierde bus"); private String halte; private String richting; private Berichten berichten; public Infobord(String halte, String richting) { this.titel = "Bushalte " + halte + " in richting " + richting; this.halte=halte; this.richting=richting; this.berichten=new Berichten(); } public void verwerkBericht() { if (berichten.hetBordMoetVerverst()) { String[] infoTekstRegels = berichten.repaintInfoBordValues(); // Deze code hoort bij opdracht 3 // InfobordTijdFuncties tijdfuncties = new InfobordTijdFuncties(); // String tijd<SUF> // tijdRegel.setText(tijd); infoRegel1.setText(infoTekstRegels[0]); infoRegel2.setText(infoTekstRegels[1]); infoRegel3.setText(infoTekstRegels[2]); infoRegel4.setText(infoTekstRegels[3]); }; } public void updateBord() { Runnable updater = new Runnable() { @Override public void run() { verwerkBericht(); } }; Platform.runLater(updater); } @Override public void start(Stage primaryStage) { String selector = ""; if (halte.length() == 1) selector += "(HALTE='"+halte+"')"; if (halte.length() == 1 && richting.length() <= 2) selector += " AND "; if (richting.length() <= 2) selector += "(RICHTING='"+richting+"')"; thread(new ListenerStarter(selector, this, berichten),false); GridPane pane = new GridPane(); pane.setAlignment(Pos.CENTER_LEFT); pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5)); pane.setHgap(5.5); pane.setVgap(5.5); // Place nodes in the pane pane.add(new Label("Voor het laatst bijgewerkt op :"), 0, 0); pane.add(tijdRegel, 1, 0); pane.add(new Label("1:"), 0, 1); pane.add(infoRegel1, 1, 1); pane.add(new Label("2:"), 0, 2); pane.add(infoRegel2, 1, 2); pane.add(new Label("3:"), 0, 3); pane.add(infoRegel3, 1, 3); pane.add(new Label("4:"), 0, 4); pane.add(infoRegel4, 1, 4); // Create a scene and place it in the stage Scene scene = new Scene(pane,500,150); primaryStage.setTitle(titel); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage } public void thread(Runnable runnable, boolean daemon) { Thread brokerThread = new Thread(runnable); brokerThread.setDaemon(daemon); brokerThread.start(); } }
118582_0
package model.AI; import model.game.Game; import java.awt.*; public class AITester implements Runnable{ final long t = System.currentTimeMillis(); long time; private AI ai1; private AI ai2; private byte[][] board; private byte turn; private Game game; public AITester(AI ai1, AI ai2, byte[][] board, byte turn, Game game, long time) { this.ai1 = ai1; this.ai2 = ai2; this.board = board; this.turn = turn; this.game = game; this.time = time + t; } public void run(){ while(System.currentTimeMillis() < time){ ai1.possibleMoves = game.getAllPossibleMoves(game.getBoard(), turn); if(!ai1.possibleMoves.isEmpty()){ if(turn == 1) try{ Point p = ai1.findMove(turn); game.playMovez(board, p, turn); } catch(NullPointerException n){ // System.out.println("null"); } else if(turn == 2) try{ Point p = ai2.findMove(turn); game.playMovez(board, p, turn); } catch(NullPointerException n){ //System.out.println("null"); } } // else { // int aantal = 0, zwart = 0, wit = 0, gelijk = 0; // aantal++; // if(aantal%10==0) // System.out.println(aantal); // if(Game.score(board, Game.BLACK)>Game.score(board, Game.WHITE)) // zwart++; // else if(Game.score(board, Game.BLACK)<Game.score(board, Game.WHITE)) // wit++; // else // gelijk++; // if(aantal%10==0) // System.out.println("Zwart: " + zwart + "Wit: " + wit + "Gelijk: " + gelijk); // turn = 1; // } } // System.out.println(aantal); // System.out.println("Zwart: " + zwart + "Wit: " + wit + "Gelijk: " + gelijk); } }
pannekoekmetijsappelmoesenslagroom/Reversi_Project
model/AI/AITester.java
651
// int aantal = 0, zwart = 0, wit = 0, gelijk = 0;
line_comment
nl
package model.AI; import model.game.Game; import java.awt.*; public class AITester implements Runnable{ final long t = System.currentTimeMillis(); long time; private AI ai1; private AI ai2; private byte[][] board; private byte turn; private Game game; public AITester(AI ai1, AI ai2, byte[][] board, byte turn, Game game, long time) { this.ai1 = ai1; this.ai2 = ai2; this.board = board; this.turn = turn; this.game = game; this.time = time + t; } public void run(){ while(System.currentTimeMillis() < time){ ai1.possibleMoves = game.getAllPossibleMoves(game.getBoard(), turn); if(!ai1.possibleMoves.isEmpty()){ if(turn == 1) try{ Point p = ai1.findMove(turn); game.playMovez(board, p, turn); } catch(NullPointerException n){ // System.out.println("null"); } else if(turn == 2) try{ Point p = ai2.findMove(turn); game.playMovez(board, p, turn); } catch(NullPointerException n){ //System.out.println("null"); } } // else { // int aantal<SUF> // aantal++; // if(aantal%10==0) // System.out.println(aantal); // if(Game.score(board, Game.BLACK)>Game.score(board, Game.WHITE)) // zwart++; // else if(Game.score(board, Game.BLACK)<Game.score(board, Game.WHITE)) // wit++; // else // gelijk++; // if(aantal%10==0) // System.out.println("Zwart: " + zwart + "Wit: " + wit + "Gelijk: " + gelijk); // turn = 1; // } } // System.out.println(aantal); // System.out.println("Zwart: " + zwart + "Wit: " + wit + "Gelijk: " + gelijk); } }
200855_4
// Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package com.twitter.intellij.pants.service.project.model; import com.intellij.openapi.util.Condition; import com.intellij.util.containers.ContainerUtil; import com.twitter.intellij.pants.model.PantsSourceType; import com.twitter.intellij.pants.model.TargetAddressInfo; import com.twitter.intellij.pants.util.PantsScalaUtil; import com.twitter.intellij.pants.util.PantsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; public class TargetInfo { protected Set<TargetAddressInfo> addressInfos = Collections.emptySet(); /** * List of libraries. Just names. */ protected Set<String> libraries = Collections.emptySet(); /** * List of libraries. Just names. */ protected Set<String> excludes = Collections.emptySet(); /** * List of dependencies. */ protected Set<String> targets = Collections.emptySet(); /** * List of source roots. */ protected Set<ContentRoot> roots = Collections.emptySet(); public TargetInfo(TargetAddressInfo... addressInfos) { setAddressInfos(ContainerUtil.newHashSet(addressInfos)); } public TargetInfo( Set<TargetAddressInfo> addressInfos, Set<String> targets, Set<String> libraries, Set<String> excludes, Set<ContentRoot> roots ) { setAddressInfos(addressInfos); setLibraries(libraries); setExcludes(excludes); setTargets(targets); setRoots(roots); } public Set<TargetAddressInfo> getAddressInfos() { return addressInfos; } public void setAddressInfos(Set<TargetAddressInfo> addressInfos) { this.addressInfos = addressInfos; } @NotNull public Set<String> getLibraries() { return libraries; } public void setLibraries(Set<String> libraries) { this.libraries = new TreeSet<>(libraries); } @NotNull public Set<String> getExcludes() { return excludes; } public void setExcludes(Set<String> excludes) { this.excludes = new TreeSet<>(excludes); } @NotNull public Set<String> getTargets() { return targets; } public void setTargets(Set<String> targets) { this.targets = new TreeSet<>(targets); } @NotNull public Set<ContentRoot> getRoots() { return roots; } public void setRoots(Set<ContentRoot> roots) { this.roots = new TreeSet<>(roots); } public boolean isEmpty() { return libraries.isEmpty() && targets.isEmpty() && roots.isEmpty() && addressInfos.isEmpty(); } @Nullable public String findScalaLibId() { return ContainerUtil.find( libraries, new Condition<String>() { @Override public boolean value(String libraryId) { return PantsScalaUtil.isScalaLibraryLib(libraryId); } } ); } public boolean isTest() { return ContainerUtil.exists( getAddressInfos(), new Condition<TargetAddressInfo>() { @Override public boolean value(TargetAddressInfo info) { return PantsUtil.getSourceTypeForTargetType(info.getTargetType(), info.isSynthetic()).toExternalSystemSourceType().isTest(); } } ); } @NotNull public PantsSourceType getSourcesType() { // In the case where multiple targets get combined into one module, // the type of common module should be in the order of // source -> test source -> resource -> test resources. (like Ranked Value in Pants options) // e.g. if source and resources get combined, the common module should be source type. Set<PantsSourceType> allTypes = getAddressInfos().stream() .map(s -> PantsUtil.getSourceTypeForTargetType(s.getTargetType(), s.isSynthetic())) .collect(Collectors.toSet()); Optional<PantsSourceType> topRankedType = Arrays.stream(PantsSourceType.values()) .filter(allTypes::contains) .findFirst(); if (topRankedType.isPresent()) { return topRankedType.get(); } return PantsSourceType.SOURCE; } public boolean isJarLibrary() { return getAddressInfos().stream().allMatch(TargetAddressInfo::isJarLibrary); } public boolean isScalaTarget() { return getAddressInfos().stream().anyMatch(TargetAddressInfo::isScala) || // TODO(yic): have Pants export `pants_target_type` correctly // because `thrift-scala` also has the type `java_thrift_library` getAddressInfos().stream().anyMatch(s -> s.getTargetAddress().endsWith("-scala")); } public boolean isPythonTarget() { return getAddressInfos().stream().anyMatch(TargetAddressInfo::isPython); } public boolean dependOn(@NotNull String targetName) { return targets.contains(targetName); } public void addDependency(@NotNull String targetName) { if (targets.isEmpty()) { targets = new HashSet<>(Collections.singletonList(targetName)); } else { targets.add(targetName); } } public boolean removeDependency(@NotNull String targetName) { return getTargets().remove(targetName); } public void replaceDependency(@NotNull String targetName, @NotNull String newTargetName) { if (removeDependency(targetName)) { addDependency(newTargetName); } } public TargetInfo union(@NotNull TargetInfo other) { return new TargetInfo( ContainerUtil.union(getAddressInfos(), other.getAddressInfos()), ContainerUtil.union(getTargets(), other.getTargets()), ContainerUtil.union(getLibraries(), other.getLibraries()), ContainerUtil.union(getExcludes(), other.getExcludes()), ContainerUtil.union(getRoots(), other.getRoots()) ); } @Override public String toString() { return "TargetInfo{" + "libraries=" + libraries + ", excludes=" + excludes + ", targets=" + targets + ", roots=" + roots + ", addressInfos='" + addressInfos + '\'' + '}'; } }
pantsbuild/intellij-pants-plugin
src/main/scala/com/twitter/intellij/pants/service/project/model/TargetInfo.java
1,868
/** * List of dependencies. */
block_comment
nl
// Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package com.twitter.intellij.pants.service.project.model; import com.intellij.openapi.util.Condition; import com.intellij.util.containers.ContainerUtil; import com.twitter.intellij.pants.model.PantsSourceType; import com.twitter.intellij.pants.model.TargetAddressInfo; import com.twitter.intellij.pants.util.PantsScalaUtil; import com.twitter.intellij.pants.util.PantsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; public class TargetInfo { protected Set<TargetAddressInfo> addressInfos = Collections.emptySet(); /** * List of libraries. Just names. */ protected Set<String> libraries = Collections.emptySet(); /** * List of libraries. Just names. */ protected Set<String> excludes = Collections.emptySet(); /** * List of dependencies.<SUF>*/ protected Set<String> targets = Collections.emptySet(); /** * List of source roots. */ protected Set<ContentRoot> roots = Collections.emptySet(); public TargetInfo(TargetAddressInfo... addressInfos) { setAddressInfos(ContainerUtil.newHashSet(addressInfos)); } public TargetInfo( Set<TargetAddressInfo> addressInfos, Set<String> targets, Set<String> libraries, Set<String> excludes, Set<ContentRoot> roots ) { setAddressInfos(addressInfos); setLibraries(libraries); setExcludes(excludes); setTargets(targets); setRoots(roots); } public Set<TargetAddressInfo> getAddressInfos() { return addressInfos; } public void setAddressInfos(Set<TargetAddressInfo> addressInfos) { this.addressInfos = addressInfos; } @NotNull public Set<String> getLibraries() { return libraries; } public void setLibraries(Set<String> libraries) { this.libraries = new TreeSet<>(libraries); } @NotNull public Set<String> getExcludes() { return excludes; } public void setExcludes(Set<String> excludes) { this.excludes = new TreeSet<>(excludes); } @NotNull public Set<String> getTargets() { return targets; } public void setTargets(Set<String> targets) { this.targets = new TreeSet<>(targets); } @NotNull public Set<ContentRoot> getRoots() { return roots; } public void setRoots(Set<ContentRoot> roots) { this.roots = new TreeSet<>(roots); } public boolean isEmpty() { return libraries.isEmpty() && targets.isEmpty() && roots.isEmpty() && addressInfos.isEmpty(); } @Nullable public String findScalaLibId() { return ContainerUtil.find( libraries, new Condition<String>() { @Override public boolean value(String libraryId) { return PantsScalaUtil.isScalaLibraryLib(libraryId); } } ); } public boolean isTest() { return ContainerUtil.exists( getAddressInfos(), new Condition<TargetAddressInfo>() { @Override public boolean value(TargetAddressInfo info) { return PantsUtil.getSourceTypeForTargetType(info.getTargetType(), info.isSynthetic()).toExternalSystemSourceType().isTest(); } } ); } @NotNull public PantsSourceType getSourcesType() { // In the case where multiple targets get combined into one module, // the type of common module should be in the order of // source -> test source -> resource -> test resources. (like Ranked Value in Pants options) // e.g. if source and resources get combined, the common module should be source type. Set<PantsSourceType> allTypes = getAddressInfos().stream() .map(s -> PantsUtil.getSourceTypeForTargetType(s.getTargetType(), s.isSynthetic())) .collect(Collectors.toSet()); Optional<PantsSourceType> topRankedType = Arrays.stream(PantsSourceType.values()) .filter(allTypes::contains) .findFirst(); if (topRankedType.isPresent()) { return topRankedType.get(); } return PantsSourceType.SOURCE; } public boolean isJarLibrary() { return getAddressInfos().stream().allMatch(TargetAddressInfo::isJarLibrary); } public boolean isScalaTarget() { return getAddressInfos().stream().anyMatch(TargetAddressInfo::isScala) || // TODO(yic): have Pants export `pants_target_type` correctly // because `thrift-scala` also has the type `java_thrift_library` getAddressInfos().stream().anyMatch(s -> s.getTargetAddress().endsWith("-scala")); } public boolean isPythonTarget() { return getAddressInfos().stream().anyMatch(TargetAddressInfo::isPython); } public boolean dependOn(@NotNull String targetName) { return targets.contains(targetName); } public void addDependency(@NotNull String targetName) { if (targets.isEmpty()) { targets = new HashSet<>(Collections.singletonList(targetName)); } else { targets.add(targetName); } } public boolean removeDependency(@NotNull String targetName) { return getTargets().remove(targetName); } public void replaceDependency(@NotNull String targetName, @NotNull String newTargetName) { if (removeDependency(targetName)) { addDependency(newTargetName); } } public TargetInfo union(@NotNull TargetInfo other) { return new TargetInfo( ContainerUtil.union(getAddressInfos(), other.getAddressInfos()), ContainerUtil.union(getTargets(), other.getTargets()), ContainerUtil.union(getLibraries(), other.getLibraries()), ContainerUtil.union(getExcludes(), other.getExcludes()), ContainerUtil.union(getRoots(), other.getRoots()) ); } @Override public String toString() { return "TargetInfo{" + "libraries=" + libraries + ", excludes=" + excludes + ", targets=" + targets + ", roots=" + roots + ", addressInfos='" + addressInfos + '\'' + '}'; } }
11666_0
package nl.infi.aoc; import static java.util.stream.Collectors.summingLong; import java.util.stream.Stream; /** * <h1><a href="https://aoc.infi.nl/2020">Bepakt en bezakt in 2020</a></h1> <p> In het bijzondere jaar 2020 blijkt de magie van kerstman <br/> verbazingwekkend als altijd, want ondanks dat normale mensen <br/> het een raar jaar vinden, gaat het dit jaar op de Noordpool <br/> verbazingwekkend goed. </p> <p> De elven hebben van alle kinderen, die lijstje opgestuurd <br/> hebben, in record tempo hun voorkeuren uitgezocht en geteld.<br/> De cadeautjes zijn gekocht en ingepakt en alle pakjes liggen al klaar.<br/> Ze hoeven alleen nog maar in een zak gedaan te worden, zodat <br/> de kerstman deze op kerstavond mee kan nemen. <p> <p> En dat is dan wel het enige puntje, waar de elven dit jaar wat <br/> hulp bij nodig hebben, want ze weten niet hoe groot de zak <br/> moet gaan worden.<br/> De magie van de kerstman en de supersonische snelheid van de <br/> arreslee met de rendieren, zorgt er voor dat tijdens het <br/> vervoer de pakjes en de zak <i>tweedimensionaal</i> lijken.<br/> Ook zijn, op magische wijze, alle pakjes even groot <br/> op het moment dat ze in de zak komen. Tevens weten ze, dat voor <br/> een optimale verhouding tussen benodigd materiaal om de zak te <br/> maken en inhoud van de zak deze tijdens het vervoer de vorm <br/> moet krijgen van een <b>Regelmatige achthoek</b>. </p> <p> Echter omdat er alleen maar gehele pakjes in de zak kunnen, <br/> hebben de elven niets aan de bekende formules voor het <br/> berekenen van de oppervlakte en dus hebben ze om hulp gevraagd <br/> om te helpen met de berekeningen. </p> <h5>Vereisten:</h5> <p> De zak moet met een platte kant op de bodem van de slee <br/> komen te staan.<br/> Alle acht de zijden van de zak moeten precies even lang zijn<br/> De schuine zijden van de zak staan onder een hoek van 135°<br/> Ieder 1x1 vakje binnen de zak is een plek voor een pakje </p> <h5>Legenda</h5> <p> <ul> <li><b>‾</b>: De bodem</li> <li><b>/</b> of <b>\</b>: een schuine zijde</li> <li><b>|</b>: Een zijkant</li> <li><b>_</b>: De bovenkant</li> <li><b>.</b>: Ruimte voor één pakje</li> </ul> </p> <h5>Achthoek met zijden van lengte: <b>2</b></h5> <pre> _ /..\ /....\ |......| |......| \..../ \../ ¯¯ </pre> <p>Het aantal pakjes dat in deze zak passen is: <b>24</b> </p> <h5>Achthoek met zijden van lengte: <b>3</b></h5> <pre> ___ /...\ /.....\ /.......\ |.........| |.........| |.........| \......./ \...../ \.../ ¯¯¯ </pre> <p>Het aantal pakjes dat in deze zak passen is: <b>57</b> </p> <h5>Extra voorbeelden</h5> <p> In een zak met zijde van lengte <b>1</b> passen: <b>5</b> pakjes<br/> In een zak met zijde van lengte <b>4</b> passen: <b>104</b> pakjes<br/> In een zak met zijde van lengte <b>10</b> passen: <b>680</b> pakjes<br/> In een zak met zijde van lengte <b>25</b> passen: <b>4.325</b> pakjes<br/> </p><p> In Nederland wonen momenteel <b>17.486.751</b> inwoners.<br/> De elven willen graag alle pakjes voor Nederland in één zak stoppen. </p><p> <b>Wat is de minimale lengte van een zijde voor de zak die zak?</b> </p> <hr/> <p> Om een zak te kunnen maken hebben de elven natuurlijk wel <br/> voldoende stof nodig. De zak bestaat uit: <ul> <li>een bodem <b>‾</b>.</li> <li>de schuine zijdes <b>/</b> of <b>\</b>.</li> <li>De zijkanten <b>|</b>.</li> <li>De bovenkant <b>_</b>.</li> </ul> <h5>Conclusie</h5> <p> Voor een zak met zijde van lengte <b>1</b> zijn <b>8</b> stukken stof nodig<br/> Voor een zak met zijde van lengte <b>4</b> zijn <b>32</b> stukken stof nodig<br/> Voor een zak met zijde van lengte <b>25</b> zijn <b>200</b> stukken stof nodig<br/> </p><p> De kerstman kan op zijn tocht in 1 zak alle cadeautjes voor 1 <br/> continent meenemen.<br/> De elven zetten van tevoren alle zakken klaar op de noordpool.<br/> Na ieder continent komt hij even terug op de noordpool om de <br/> volgende zak op te halen.<br/> De elven weten per continent hoeveel cadeautjes er bezorgt (sic)<br/> moeten worden: <table> <tr><td>Asia</td><td style="text-align: right"><b>4.541.363.434</b></td></tr> <tr><td>Africa</td><td style="text-align: right"><b>1.340.832.532</b></td></tr> <tr><td>Europe</td><td style="text-align: right"><b>747.786.585</b></td></tr> <tr><td>South America</td><td style="text-align: right"><b>430.832.752</b></td></tr> <tr><td>North America</td><td style="text-align: right"><b>369.012.203</b></td></tr> <tr><td>Oceania</td><td style="text-align: right"><b>42.715.772</b></td></tr> </table> </p> <b>Hoeveel stukken stof moeten de elven mimimaal kopen om alle <br/> zakken te kunnen maken?</b> */ public class AoC2020 extends AocBase { final Long[] input; private AoC2020(final boolean debug, final Long[] input) { super(debug); this.input = input; } public static final AoC2020 create(final Long... input) { return new AoC2020(false, input); } public static final AoC2020 createDebug(final Long... input) { return new AoC2020(true, input); } private long berekenPakjesVoorZijde(final long zijde) { long pakjes = zijde; long summant = zijde; for (long i = 0; i < zijde - 1; i++) { summant += 2; pakjes += summant; } pakjes *= 2; summant += 2; pakjes += zijde * summant; return pakjes; } private long zoekZijdeVoorPakjes(final long pakjes) { long i = 1; while (berekenPakjesVoorZijde(i) < pakjes) { i++; } return i; } @Override public Long solvePart1() { assert this.input.length == 1; return zoekZijdeVoorPakjes(input[0]); } @Override public Long solvePart2() { return 8 * Stream.of(this.input) .collect(summingLong(i -> zoekZijdeVoorPakjes(i))); } public static void main(final String[] args) throws Exception { assert AoC2020.createDebug(5L).solvePart1() == 1; assert AoC2020.createDebug(24L).solvePart1() == 2; assert AoC2020.createDebug(57L).solvePart1() == 3; assert AoC2020.createDebug(104L).solvePart1() == 4; assert AoC2020.createDebug(680L).solvePart1() == 10; assert AoC2020.createDebug(4325L).solvePart1() == 25; lap("Part 1", () -> AoC2020.create(17_486_751L).solvePart1()); lap("Part 2", () -> AoC2020.create( 4_541_363_434L, 1_340_832_532L, 747_786_585L, 430_832_752L, 369_012_203L, 42_715_772L).solvePart2()); } }
pareronia/puzzles
src/main/java/nl/infi/aoc/AoC2020.java
2,410
/** * <h1><a href="https://aoc.infi.nl/2020">Bepakt en bezakt in 2020</a></h1> <p> In het bijzondere jaar 2020 blijkt de magie van kerstman <br/> verbazingwekkend als altijd, want ondanks dat normale mensen <br/> het een raar jaar vinden, gaat het dit jaar op de Noordpool <br/> verbazingwekkend goed. </p> <p> De elven hebben van alle kinderen, die lijstje opgestuurd <br/> hebben, in record tempo hun voorkeuren uitgezocht en geteld.<br/> De cadeautjes zijn gekocht en ingepakt en alle pakjes liggen al klaar.<br/> Ze hoeven alleen nog maar in een zak gedaan te worden, zodat <br/> de kerstman deze op kerstavond mee kan nemen. <p> <p> En dat is dan wel het enige puntje, waar de elven dit jaar wat <br/> hulp bij nodig hebben, want ze weten niet hoe groot de zak <br/> moet gaan worden.<br/> De magie van de kerstman en de supersonische snelheid van de <br/> arreslee met de rendieren, zorgt er voor dat tijdens het <br/> vervoer de pakjes en de zak <i>tweedimensionaal</i> lijken.<br/> Ook zijn, op magische wijze, alle pakjes even groot <br/> op het moment dat ze in de zak komen. Tevens weten ze, dat voor <br/> een optimale verhouding tussen benodigd materiaal om de zak te <br/> maken en inhoud van de zak deze tijdens het vervoer de vorm <br/> moet krijgen van een <b>Regelmatige achthoek</b>. </p> <p> Echter omdat er alleen maar gehele pakjes in de zak kunnen, <br/> hebben de elven niets aan de bekende formules voor het <br/> berekenen van de oppervlakte en dus hebben ze om hulp gevraagd <br/> om te helpen met de berekeningen. </p> <h5>Vereisten:</h5> <p> De zak moet met een platte kant op de bodem van de slee <br/> komen te staan.<br/> Alle acht de zijden van de zak moeten precies even lang zijn<br/> De schuine zijden van de zak staan onder een hoek van 135°<br/> Ieder 1x1 vakje binnen de zak is een plek voor een pakje </p> <h5>Legenda</h5> <p> <ul> <li><b>‾</b>: De bodem</li> <li><b>/</b> of <b>\</b>: een schuine zijde</li> <li><b>|</b>: Een zijkant</li> <li><b>_</b>: De bovenkant</li> <li><b>.</b>: Ruimte voor één pakje</li> </ul> </p> <h5>Achthoek met zijden van lengte: <b>2</b></h5> <pre> _ /..\ /....\ |......| |......| \..../ \../ ¯¯ </pre> <p>Het aantal pakjes dat in deze zak passen is: <b>24</b> </p> <h5>Achthoek met zijden van lengte: <b>3</b></h5> <pre> ___ /...\ /.....\ /.......\ |.........| |.........| |.........| \......./ \...../ \.../ ¯¯¯ </pre> <p>Het aantal pakjes dat in deze zak passen is: <b>57</b> </p> <h5>Extra voorbeelden</h5> <p> In een zak met zijde van lengte <b>1</b> passen: <b>5</b> pakjes<br/> In een zak met zijde van lengte <b>4</b> passen: <b>104</b> pakjes<br/> In een zak met zijde van lengte <b>10</b> passen: <b>680</b> pakjes<br/> In een zak met zijde van lengte <b>25</b> passen: <b>4.325</b> pakjes<br/> </p><p> In Nederland wonen momenteel <b>17.486.751</b> inwoners.<br/> De elven willen graag alle pakjes voor Nederland in één zak stoppen. </p><p> <b>Wat is de minimale lengte van een zijde voor de zak die zak?</b> </p> <hr/> <p> Om een zak te kunnen maken hebben de elven natuurlijk wel <br/> voldoende stof nodig. De zak bestaat uit: <ul> <li>een bodem <b>‾</b>.</li> <li>de schuine zijdes <b>/</b> of <b>\</b>.</li> <li>De zijkanten <b>|</b>.</li> <li>De bovenkant <b>_</b>.</li> </ul> <h5>Conclusie</h5> <p> Voor een zak met zijde van lengte <b>1</b> zijn <b>8</b> stukken stof nodig<br/> Voor een zak met zijde van lengte <b>4</b> zijn <b>32</b> stukken stof nodig<br/> Voor een zak met zijde van lengte <b>25</b> zijn <b>200</b> stukken stof nodig<br/> </p><p> De kerstman kan op zijn tocht in 1 zak alle cadeautjes voor 1 <br/> continent meenemen.<br/> De elven zetten van tevoren alle zakken klaar op de noordpool.<br/> Na ieder continent komt hij even terug op de noordpool om de <br/> volgende zak op te halen.<br/> De elven weten per continent hoeveel cadeautjes er bezorgt (sic)<br/> moeten worden: <table> <tr><td>Asia</td><td style="text-align: right"><b>4.541.363.434</b></td></tr> <tr><td>Africa</td><td style="text-align: right"><b>1.340.832.532</b></td></tr> <tr><td>Europe</td><td style="text-align: right"><b>747.786.585</b></td></tr> <tr><td>South America</td><td style="text-align: right"><b>430.832.752</b></td></tr> <tr><td>North America</td><td style="text-align: right"><b>369.012.203</b></td></tr> <tr><td>Oceania</td><td style="text-align: right"><b>42.715.772</b></td></tr> </table> </p> <b>Hoeveel stukken stof moeten de elven mimimaal kopen om alle <br/> zakken te kunnen maken?</b> */
block_comment
nl
package nl.infi.aoc; import static java.util.stream.Collectors.summingLong; import java.util.stream.Stream; /** * <h1><a href="https://aoc.infi.nl/2020">Bepakt en<SUF>*/ public class AoC2020 extends AocBase { final Long[] input; private AoC2020(final boolean debug, final Long[] input) { super(debug); this.input = input; } public static final AoC2020 create(final Long... input) { return new AoC2020(false, input); } public static final AoC2020 createDebug(final Long... input) { return new AoC2020(true, input); } private long berekenPakjesVoorZijde(final long zijde) { long pakjes = zijde; long summant = zijde; for (long i = 0; i < zijde - 1; i++) { summant += 2; pakjes += summant; } pakjes *= 2; summant += 2; pakjes += zijde * summant; return pakjes; } private long zoekZijdeVoorPakjes(final long pakjes) { long i = 1; while (berekenPakjesVoorZijde(i) < pakjes) { i++; } return i; } @Override public Long solvePart1() { assert this.input.length == 1; return zoekZijdeVoorPakjes(input[0]); } @Override public Long solvePart2() { return 8 * Stream.of(this.input) .collect(summingLong(i -> zoekZijdeVoorPakjes(i))); } public static void main(final String[] args) throws Exception { assert AoC2020.createDebug(5L).solvePart1() == 1; assert AoC2020.createDebug(24L).solvePart1() == 2; assert AoC2020.createDebug(57L).solvePart1() == 3; assert AoC2020.createDebug(104L).solvePart1() == 4; assert AoC2020.createDebug(680L).solvePart1() == 10; assert AoC2020.createDebug(4325L).solvePart1() == 25; lap("Part 1", () -> AoC2020.create(17_486_751L).solvePart1()); lap("Part 2", () -> AoC2020.create( 4_541_363_434L, 1_340_832_532L, 747_786_585L, 430_832_752L, 369_012_203L, 42_715_772L).solvePart2()); } }
57587_0
package org.nhl.spoder.hexapod.visionservice; import org.nhl.spoderpod.hexapod.components.C_RouterClient; import org.nhl.spoderpod.hexapod.components.C_VisionFormatter; import org.nhl.spoderpod.hexapod.components.C_VisionListener; import org.nhl.spoderpod.hexapod.core.Service; import org.nhl.spoderpod.hexapod.interfaces.I_Component; /*** * Vision Service verzorgt het versturen van data naar de AI service, zodat die een berekening kan maken. * * @author Driving Ghost * TODO Matthijs, waar komt de data in VisionFormatter, die naar de AI service en logger wordt gestuurd, vandaan? * TODO Kan VisionListner weg? * */ public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Started service"); Service s = new Service("Vision", new I_Component[] { new C_VisionFormatter("C_VisionFormatter"), new C_VisionListener("C_VisionListener"), new C_RouterClient("C_RouterClient", "127.0.0.1", 1234) }); s.start(); Thread.sleep(10 * 1000); s.stop(); } } /* */
pasibun/IDP_Spoder_Pod
hexapod/src/main/java/org/nhl/spoder/hexapod/visionservice/Main.java
360
/*** * Vision Service verzorgt het versturen van data naar de AI service, zodat die een berekening kan maken. * * @author Driving Ghost * TODO Matthijs, waar komt de data in VisionFormatter, die naar de AI service en logger wordt gestuurd, vandaan? * TODO Kan VisionListner weg? * */
block_comment
nl
package org.nhl.spoder.hexapod.visionservice; import org.nhl.spoderpod.hexapod.components.C_RouterClient; import org.nhl.spoderpod.hexapod.components.C_VisionFormatter; import org.nhl.spoderpod.hexapod.components.C_VisionListener; import org.nhl.spoderpod.hexapod.core.Service; import org.nhl.spoderpod.hexapod.interfaces.I_Component; /*** * Vision Service verzorgt<SUF>*/ public class Main { public static void main(String[] args) throws InterruptedException { System.out.println("Started service"); Service s = new Service("Vision", new I_Component[] { new C_VisionFormatter("C_VisionFormatter"), new C_VisionListener("C_VisionListener"), new C_RouterClient("C_RouterClient", "127.0.0.1", 1234) }); s.start(); Thread.sleep(10 * 1000); s.stop(); } } /* */
95733_2
package com.matchfixing.minor.matchfixing; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Invitation extends Activity { String MATCHID, MATCHDATE, MATCHTIME, MATCHTYPE, MATCHLANE, MATCHDESCRIPTION; int userID; String s; List<String> matches = null; List<String> matchDates = null; List<String> matchTimes = null; List<String> matchLanes = null; List<String> matchTypes = null; Map<String, Integer> matchIDs = null; List<String> matchDescriptionsList = null; GridView matchGrid; TextView txtView; private int previousSelectedPosition = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.matches_today); userID = Integer.parseInt(PersonaliaSingleton.getInstance().getUserID()); matches = new ArrayList<String>(); matchIDs = new HashMap<String, Integer>(); matchDescriptionsList = new ArrayList<>(); matchDates = new ArrayList<>(); matchTimes = new ArrayList<>(); matchLanes = new ArrayList<>(); matchTypes = new ArrayList<>(); s = Integer.toString(userID); txtView = (TextView) findViewById(R.id.textView2); txtView.setText("Hier vind je matches waar mensen jou persoonlijk voor uitgenodigd hebben. Klik een match aan om de details te kunnen zien."); matchGrid = (GridView) findViewById(R.id.gridView); SetupView(); String databaseInfo = "userID="+userID; String fileName = "GetInvitations.php"; Invitation.BackGround b = new Invitation.BackGround(); b.execute(s); } public void home_home(View view){ startActivity(new Intent(this, Home.class)); } public void SetupView() { final GridView gv = (GridView) findViewById(R.id.gridView); gv.setAdapter(new GridViewAdapter(Invitation.this, matches){ public View getView(int position, View convertView, ViewGroup parent){ View view = super.getView(position, convertView, parent); TextView tv = (TextView) view; tv.setTextColor(Color.WHITE); tv.setBackgroundColor(Color.parseColor("#23db4e")); tv.setTextSize(25); return tv; } }); gv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView tv = (TextView) view; tv.setTextColor(Color.RED); TextView previousSelectedView = (TextView) gv.getChildAt(previousSelectedPosition); int clickedMatchID = -1; //with thclickedMatchIDis method we retrieve the matchID. We need this to implement in the upcoming "MATCH ATTENDEES" table. if(matchIDs != null) { clickedMatchID = matchIDs.get(matches.get(position)); } String matchDescription = matches.get(position); String description = matchDescriptionsList.get(position); String matchDate = matchDates.get(position); String matchTime = matchTimes.get(position); String matchLane = matchLanes.get(position); String matchType = matchTypes.get(position); int matchID = clickedMatchID; Intent Popup = new Intent(Invitation.this, Popup.class); Popup.putExtra("matchDescription", matchDescription); Popup.putExtra("desc", description); Popup.putExtra("matchID", matchID); Popup.putExtra("matchDate", matchDate); Popup.putExtra("matchTime", matchTime); Popup.putExtra("matchLane", matchLane); Popup.putExtra("matchType", matchType); startActivity(Popup); // If there is a previous selected view exists if (previousSelectedPosition != -1) { previousSelectedView.setSelected(false); previousSelectedView.setTextColor(Color.WHITE); } previousSelectedPosition = position; } }); } // //onPostExecute samen ff nakijken. // // Waarom kan hier wel findViewById en in mijn classe niet. class BackGround extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String userID = params[0]; String data = ""; int tmp; try { URL url = new URL("http://141.252.218.158:80/GetInvitations.php"); String urlParams = "userID=" + userID; HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput(true); OutputStream os = httpURLConnection.getOutputStream(); os.write(urlParams.getBytes()); os.flush(); os.close(); InputStream is = httpURLConnection.getInputStream(); while ((tmp = is.read()) != -1) { data += (char) tmp; } is.close(); httpURLConnection.disconnect(); return data; } catch (MalformedURLException e) { e.printStackTrace(); return "Exception: " + e.getMessage(); } catch (IOException e) { e.printStackTrace(); return "Exception: " + e.getMessage(); } } @Override protected void onPostExecute(String s) { String err = null; String[] matchStrings = s.split("&"); int fieldID = -1; for(int i = 0; i < matchStrings.length; ++i) { try { JSONObject root = new JSONObject(matchStrings[i]); JSONObject user_data = root.getJSONObject("user_data"); MATCHID = user_data.getString("MatchID"); MATCHDATE = user_data.getString("matchDate"); MATCHTIME = user_data.getString("matchTime"); MATCHTYPE = user_data.getString("MatchType"); MATCHLANE = user_data.getString("lane"); MATCHDESCRIPTION = user_data.getString("description"); //dates times lanes types matchDates.add(MATCHDATE); matchTimes.add(MATCHTIME); matchTypes.add(MATCHTYPE); matchLanes.add(MATCHLANE); matches.add(MATCHDATE + " " + MATCHTIME + " " + MATCHTYPE + " " + MATCHLANE); matchIDs.put(MATCHDATE + " " + MATCHTIME + " " + MATCHTYPE + " " + MATCHLANE, Integer.parseInt(MATCHID)); matchDescriptionsList.add(MATCHDESCRIPTION); } catch (JSONException e) { e.printStackTrace(); err = "Exception: " + e.getMessage(); } } SetupView(); } } }
pasibun/MatchFixing
app/src/main/java/com/matchfixing/minor/matchfixing/Invitation.java
2,144
// //onPostExecute samen ff nakijken.
line_comment
nl
package com.matchfixing.minor.matchfixing; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Invitation extends Activity { String MATCHID, MATCHDATE, MATCHTIME, MATCHTYPE, MATCHLANE, MATCHDESCRIPTION; int userID; String s; List<String> matches = null; List<String> matchDates = null; List<String> matchTimes = null; List<String> matchLanes = null; List<String> matchTypes = null; Map<String, Integer> matchIDs = null; List<String> matchDescriptionsList = null; GridView matchGrid; TextView txtView; private int previousSelectedPosition = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.matches_today); userID = Integer.parseInt(PersonaliaSingleton.getInstance().getUserID()); matches = new ArrayList<String>(); matchIDs = new HashMap<String, Integer>(); matchDescriptionsList = new ArrayList<>(); matchDates = new ArrayList<>(); matchTimes = new ArrayList<>(); matchLanes = new ArrayList<>(); matchTypes = new ArrayList<>(); s = Integer.toString(userID); txtView = (TextView) findViewById(R.id.textView2); txtView.setText("Hier vind je matches waar mensen jou persoonlijk voor uitgenodigd hebben. Klik een match aan om de details te kunnen zien."); matchGrid = (GridView) findViewById(R.id.gridView); SetupView(); String databaseInfo = "userID="+userID; String fileName = "GetInvitations.php"; Invitation.BackGround b = new Invitation.BackGround(); b.execute(s); } public void home_home(View view){ startActivity(new Intent(this, Home.class)); } public void SetupView() { final GridView gv = (GridView) findViewById(R.id.gridView); gv.setAdapter(new GridViewAdapter(Invitation.this, matches){ public View getView(int position, View convertView, ViewGroup parent){ View view = super.getView(position, convertView, parent); TextView tv = (TextView) view; tv.setTextColor(Color.WHITE); tv.setBackgroundColor(Color.parseColor("#23db4e")); tv.setTextSize(25); return tv; } }); gv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView tv = (TextView) view; tv.setTextColor(Color.RED); TextView previousSelectedView = (TextView) gv.getChildAt(previousSelectedPosition); int clickedMatchID = -1; //with thclickedMatchIDis method we retrieve the matchID. We need this to implement in the upcoming "MATCH ATTENDEES" table. if(matchIDs != null) { clickedMatchID = matchIDs.get(matches.get(position)); } String matchDescription = matches.get(position); String description = matchDescriptionsList.get(position); String matchDate = matchDates.get(position); String matchTime = matchTimes.get(position); String matchLane = matchLanes.get(position); String matchType = matchTypes.get(position); int matchID = clickedMatchID; Intent Popup = new Intent(Invitation.this, Popup.class); Popup.putExtra("matchDescription", matchDescription); Popup.putExtra("desc", description); Popup.putExtra("matchID", matchID); Popup.putExtra("matchDate", matchDate); Popup.putExtra("matchTime", matchTime); Popup.putExtra("matchLane", matchLane); Popup.putExtra("matchType", matchType); startActivity(Popup); // If there is a previous selected view exists if (previousSelectedPosition != -1) { previousSelectedView.setSelected(false); previousSelectedView.setTextColor(Color.WHITE); } previousSelectedPosition = position; } }); } // //onPostExecute samen<SUF> // // Waarom kan hier wel findViewById en in mijn classe niet. class BackGround extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String userID = params[0]; String data = ""; int tmp; try { URL url = new URL("http://141.252.218.158:80/GetInvitations.php"); String urlParams = "userID=" + userID; HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput(true); OutputStream os = httpURLConnection.getOutputStream(); os.write(urlParams.getBytes()); os.flush(); os.close(); InputStream is = httpURLConnection.getInputStream(); while ((tmp = is.read()) != -1) { data += (char) tmp; } is.close(); httpURLConnection.disconnect(); return data; } catch (MalformedURLException e) { e.printStackTrace(); return "Exception: " + e.getMessage(); } catch (IOException e) { e.printStackTrace(); return "Exception: " + e.getMessage(); } } @Override protected void onPostExecute(String s) { String err = null; String[] matchStrings = s.split("&"); int fieldID = -1; for(int i = 0; i < matchStrings.length; ++i) { try { JSONObject root = new JSONObject(matchStrings[i]); JSONObject user_data = root.getJSONObject("user_data"); MATCHID = user_data.getString("MatchID"); MATCHDATE = user_data.getString("matchDate"); MATCHTIME = user_data.getString("matchTime"); MATCHTYPE = user_data.getString("MatchType"); MATCHLANE = user_data.getString("lane"); MATCHDESCRIPTION = user_data.getString("description"); //dates times lanes types matchDates.add(MATCHDATE); matchTimes.add(MATCHTIME); matchTypes.add(MATCHTYPE); matchLanes.add(MATCHLANE); matches.add(MATCHDATE + " " + MATCHTIME + " " + MATCHTYPE + " " + MATCHLANE); matchIDs.put(MATCHDATE + " " + MATCHTIME + " " + MATCHTYPE + " " + MATCHLANE, Integer.parseInt(MATCHID)); matchDescriptionsList.add(MATCHDESCRIPTION); } catch (JSONException e) { e.printStackTrace(); err = "Exception: " + e.getMessage(); } } SetupView(); } } }
71152_2
/* * The MIT License * * Copyright 2018 The OpenNARS authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.opennars.inference; import org.opennars.entity.*; import org.opennars.language.Term; import org.opennars.storage.Memory; import static java.lang.Math.*; import org.opennars.main.Parameters; /** * Budget functions for resources allocation * * @author Pei Wang * @author Patrick Hammer */ public final class BudgetFunctions extends UtilityFunctions { /* ----------------------- Belief evaluation ----------------------- */ /** * Determine the quality of a judgment by its truth value alone * <p> * Mainly decided by confidence, though binary judgment is also preferred * * @param t The truth value of a judgment * @return The quality of the judgment, according to truth value only */ public final static float truthToQuality(final TruthValue t) { final float exp = t.getExpectation(); return (float) max(exp, (1 - exp)*0.75); } /** * Determine the rank of a judgment by its quality and originality (stamp baseLength), called from Concept * * @param judg The judgment to be ranked * @return The rank of the judgment, according to truth value only */ public final static float rankBelief(final Sentence judg, final boolean rankTruthExpectation) { if(rankTruthExpectation) { return judg.getTruth().getExpectation(); } final float confidence = judg.truth.getConfidence(); //final float originality = judg.stamp.getOriginality(); return confidence; //or(confidence, originality); } /** * Evaluate the quality of a revision, then de-prioritize the premises * * @param tTruth The truth value of the judgment in the task * @param bTruth The truth value of the belief * @param truth The truth value of the conclusion of revision * @return The budget for the new task */ static BudgetValue revise(final TruthValue tTruth, final TruthValue bTruth, final TruthValue truth, final org.opennars.control.DerivationContext nal) { final float difT = truth.getExpDifAbs(tTruth); final Task task = nal.getCurrentTask(); task.decPriority(1 - difT); task.decDurability(1 - difT); final float dif = truth.getConfidence() - max(tTruth.getConfidence(), bTruth.getConfidence()); final float priority = or(dif, task.getPriority()); final float durability = aveAri(dif, task.getDurability()); final float quality = truthToQuality(truth); return new BudgetValue(priority, durability, quality, nal.narParameters); } /** * Update a belief * * @param task The task containing new belief * @param bTruth Truth value of the previous belief * @return Budget value of the updating task */ public static BudgetValue update(final Task task, final TruthValue bTruth, Parameters narParameters) { final TruthValue tTruth = task.sentence.truth; final float dif = tTruth.getExpDifAbs(bTruth); final float priority = or(dif, task.getPriority()); final float durability = aveAri(dif, task.getDurability()); final float quality = truthToQuality(bTruth); return new BudgetValue(priority, durability, quality, narParameters); } public enum Activating { Max, TaskLink } /* ----------------------- Concept ----------------------- */ /** * Activate a concept by an incoming TaskLink * * @param receiver The budget receiving the activation * @param amount The budget for the new item */ public static void activate(final BudgetValue receiver, final BudgetValue amount) { final float oldPri = receiver.getPriority(); receiver.setPriority( or(oldPri, amount.getPriority()) ); } /* ---------------- Bag functions, on all Items ------------------- */ /** * Decrease Priority after an item is used, called in Bag. * After a constant time, p should become d*p. Since in this period, the * item is accessed c*p times, each time p-q should multiple d^(1/(c*p)). * The intuitive meaning of the parameter "forgetRate" is: after this number * of times of access, priority 1 will become d, it is a system parameter * adjustable in run time. * * @param budget The previous budget value * @param forgetCycles The budget for the new item * @param relativeThreshold The relative threshold of the bag */ public static float applyForgetting(final BudgetValue budget, final float forgetCycles, final float relativeThreshold) { float quality = budget.getQuality() * relativeThreshold; // re-scaled quality final float p = budget.getPriority() - quality; // priority above quality if (p > 0) { quality += p * pow(budget.getDurability(), 1.0 / (forgetCycles * p)); } // priority Durability budget.setPriority(quality); return quality; } /** * Merge an item into another one in a bag, when the two are identical * except in budget values * * @param b The budget baseValue to be modified * @param a The budget adjustValue doing the adjusting */ public static void merge(final BudgetValue b, final BudgetValue a) { b.setPriority(max(b.getPriority(), a.getPriority())); b.setDurability(max(b.getDurability(), a.getDurability())); b.setQuality(max(b.getQuality(), a.getQuality())); } /* ----- Task derivation in LocalRules and SyllogisticRules ----- */ /** * Forward inference result and adjustment * * @param truth The truth value of the conclusion * @return The budget value of the conclusion */ public static BudgetValue forward(final TruthValue truth, final org.opennars.control.DerivationContext nal) { return budgetInference(truthToQuality(truth), 1, nal); } /** * Backward inference result and adjustment, stronger case * * @param truth The truth value of the belief deriving the conclusion * @param nal Reference to the memory * @return The budget value of the conclusion */ public static BudgetValue backward(final TruthValue truth, final org.opennars.control.DerivationContext nal) { return budgetInference(truthToQuality(truth), 1, nal); } /** * Backward inference result and adjustment, weaker case * * @param truth The truth value of the belief deriving the conclusion * @param nal Reference to the memory * @return The budget value of the conclusion */ public static BudgetValue backwardWeak(final TruthValue truth, final org.opennars.control.DerivationContext nal) { return budgetInference(w2c(1, nal.narParameters) * truthToQuality(truth), 1, nal); } /* ----- Task derivation in CompositionalRules and StructuralRules ----- */ /** * Forward inference with CompoundTerm conclusion * * @param truth The truth value of the conclusion * @param content The content of the conclusion * @param nal Reference to the memory * @return The budget of the conclusion */ public static BudgetValue compoundForward(final TruthValue truth, final Term content, final org.opennars.control.DerivationContext nal) { final float complexity = (content == null) ? nal.narParameters.COMPLEXITY_UNIT : nal.narParameters.COMPLEXITY_UNIT*content.getComplexity(); return budgetInference(truthToQuality(truth), complexity, nal); } /** * Backward inference with CompoundTerm conclusion, stronger case * * @param content The content of the conclusion * @param nal Reference to the memory * @return The budget of the conclusion */ public static BudgetValue compoundBackward(final Term content, final org.opennars.control.DerivationContext nal) { return budgetInference(1, content.getComplexity()*nal.narParameters.COMPLEXITY_UNIT, nal); } /** * Backward inference with CompoundTerm conclusion, weaker case * * @param content The content of the conclusion * @param nal Reference to the memory * @return The budget of the conclusion */ public static BudgetValue compoundBackwardWeak(final Term content, final org.opennars.control.DerivationContext nal) { return budgetInference(w2c(1, nal.narParameters), content.getComplexity()*nal.narParameters.COMPLEXITY_UNIT, nal); } /** * Get the current activation level of a concept. * * @param t The Term naming a concept * @return the priority value of the concept */ public static float conceptActivation(final Memory mem, final Term t) { final Concept c = mem.concept(t); return (c == null) ? 0f : c.getPriority(); } /** * Common processing for all inference step * * @param qual Quality of the inference * @param complexity Syntactic complexity of the conclusion * @param nal Reference to the memory * @return Budget of the conclusion task */ private static BudgetValue budgetInference(final float qual, final float complexity, final org.opennars.control.DerivationContext nal) { Item t = nal.getCurrentTask(); if (t == null) { t = nal.getCurrentTask(); } Concept c = nal.getCurrentConcept(); TruthValue beliefTruth = nal.getCurrentBelief() == null ? new TruthValue(1.0f,0.9f, nal.narParameters) : nal.getCurrentBelief().truth; float priority = 0.01f+c.getPriority() * beliefTruth.getExpectation(); float durability = t.getDurability(); //float durability = t.getDurability() / complexity; final float quality = qual / complexity; //not used in ALANN though return new BudgetValue(priority, durability, quality, nal.narParameters); } @Deprecated static BudgetValue solutionEval(final Sentence problem, final Sentence solution, final Task task, final Memory memory) { throw new IllegalStateException("Moved to TemporalRules.java"); } public static BudgetValue budgetTermLinkConcept(final Concept c, final BudgetValue taskBudget, final TermLink termLink) { return taskBudget.clone(); } }
patham9/RetroALANN
src/main/java/org/opennars/inference/BudgetFunctions.java
3,112
/* ----------------------- Belief evaluation ----------------------- */
block_comment
nl
/* * The MIT License * * Copyright 2018 The OpenNARS authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.opennars.inference; import org.opennars.entity.*; import org.opennars.language.Term; import org.opennars.storage.Memory; import static java.lang.Math.*; import org.opennars.main.Parameters; /** * Budget functions for resources allocation * * @author Pei Wang * @author Patrick Hammer */ public final class BudgetFunctions extends UtilityFunctions { /* ----------------------- Belief evaluation<SUF>*/ /** * Determine the quality of a judgment by its truth value alone * <p> * Mainly decided by confidence, though binary judgment is also preferred * * @param t The truth value of a judgment * @return The quality of the judgment, according to truth value only */ public final static float truthToQuality(final TruthValue t) { final float exp = t.getExpectation(); return (float) max(exp, (1 - exp)*0.75); } /** * Determine the rank of a judgment by its quality and originality (stamp baseLength), called from Concept * * @param judg The judgment to be ranked * @return The rank of the judgment, according to truth value only */ public final static float rankBelief(final Sentence judg, final boolean rankTruthExpectation) { if(rankTruthExpectation) { return judg.getTruth().getExpectation(); } final float confidence = judg.truth.getConfidence(); //final float originality = judg.stamp.getOriginality(); return confidence; //or(confidence, originality); } /** * Evaluate the quality of a revision, then de-prioritize the premises * * @param tTruth The truth value of the judgment in the task * @param bTruth The truth value of the belief * @param truth The truth value of the conclusion of revision * @return The budget for the new task */ static BudgetValue revise(final TruthValue tTruth, final TruthValue bTruth, final TruthValue truth, final org.opennars.control.DerivationContext nal) { final float difT = truth.getExpDifAbs(tTruth); final Task task = nal.getCurrentTask(); task.decPriority(1 - difT); task.decDurability(1 - difT); final float dif = truth.getConfidence() - max(tTruth.getConfidence(), bTruth.getConfidence()); final float priority = or(dif, task.getPriority()); final float durability = aveAri(dif, task.getDurability()); final float quality = truthToQuality(truth); return new BudgetValue(priority, durability, quality, nal.narParameters); } /** * Update a belief * * @param task The task containing new belief * @param bTruth Truth value of the previous belief * @return Budget value of the updating task */ public static BudgetValue update(final Task task, final TruthValue bTruth, Parameters narParameters) { final TruthValue tTruth = task.sentence.truth; final float dif = tTruth.getExpDifAbs(bTruth); final float priority = or(dif, task.getPriority()); final float durability = aveAri(dif, task.getDurability()); final float quality = truthToQuality(bTruth); return new BudgetValue(priority, durability, quality, narParameters); } public enum Activating { Max, TaskLink } /* ----------------------- Concept ----------------------- */ /** * Activate a concept by an incoming TaskLink * * @param receiver The budget receiving the activation * @param amount The budget for the new item */ public static void activate(final BudgetValue receiver, final BudgetValue amount) { final float oldPri = receiver.getPriority(); receiver.setPriority( or(oldPri, amount.getPriority()) ); } /* ---------------- Bag functions, on all Items ------------------- */ /** * Decrease Priority after an item is used, called in Bag. * After a constant time, p should become d*p. Since in this period, the * item is accessed c*p times, each time p-q should multiple d^(1/(c*p)). * The intuitive meaning of the parameter "forgetRate" is: after this number * of times of access, priority 1 will become d, it is a system parameter * adjustable in run time. * * @param budget The previous budget value * @param forgetCycles The budget for the new item * @param relativeThreshold The relative threshold of the bag */ public static float applyForgetting(final BudgetValue budget, final float forgetCycles, final float relativeThreshold) { float quality = budget.getQuality() * relativeThreshold; // re-scaled quality final float p = budget.getPriority() - quality; // priority above quality if (p > 0) { quality += p * pow(budget.getDurability(), 1.0 / (forgetCycles * p)); } // priority Durability budget.setPriority(quality); return quality; } /** * Merge an item into another one in a bag, when the two are identical * except in budget values * * @param b The budget baseValue to be modified * @param a The budget adjustValue doing the adjusting */ public static void merge(final BudgetValue b, final BudgetValue a) { b.setPriority(max(b.getPriority(), a.getPriority())); b.setDurability(max(b.getDurability(), a.getDurability())); b.setQuality(max(b.getQuality(), a.getQuality())); } /* ----- Task derivation in LocalRules and SyllogisticRules ----- */ /** * Forward inference result and adjustment * * @param truth The truth value of the conclusion * @return The budget value of the conclusion */ public static BudgetValue forward(final TruthValue truth, final org.opennars.control.DerivationContext nal) { return budgetInference(truthToQuality(truth), 1, nal); } /** * Backward inference result and adjustment, stronger case * * @param truth The truth value of the belief deriving the conclusion * @param nal Reference to the memory * @return The budget value of the conclusion */ public static BudgetValue backward(final TruthValue truth, final org.opennars.control.DerivationContext nal) { return budgetInference(truthToQuality(truth), 1, nal); } /** * Backward inference result and adjustment, weaker case * * @param truth The truth value of the belief deriving the conclusion * @param nal Reference to the memory * @return The budget value of the conclusion */ public static BudgetValue backwardWeak(final TruthValue truth, final org.opennars.control.DerivationContext nal) { return budgetInference(w2c(1, nal.narParameters) * truthToQuality(truth), 1, nal); } /* ----- Task derivation in CompositionalRules and StructuralRules ----- */ /** * Forward inference with CompoundTerm conclusion * * @param truth The truth value of the conclusion * @param content The content of the conclusion * @param nal Reference to the memory * @return The budget of the conclusion */ public static BudgetValue compoundForward(final TruthValue truth, final Term content, final org.opennars.control.DerivationContext nal) { final float complexity = (content == null) ? nal.narParameters.COMPLEXITY_UNIT : nal.narParameters.COMPLEXITY_UNIT*content.getComplexity(); return budgetInference(truthToQuality(truth), complexity, nal); } /** * Backward inference with CompoundTerm conclusion, stronger case * * @param content The content of the conclusion * @param nal Reference to the memory * @return The budget of the conclusion */ public static BudgetValue compoundBackward(final Term content, final org.opennars.control.DerivationContext nal) { return budgetInference(1, content.getComplexity()*nal.narParameters.COMPLEXITY_UNIT, nal); } /** * Backward inference with CompoundTerm conclusion, weaker case * * @param content The content of the conclusion * @param nal Reference to the memory * @return The budget of the conclusion */ public static BudgetValue compoundBackwardWeak(final Term content, final org.opennars.control.DerivationContext nal) { return budgetInference(w2c(1, nal.narParameters), content.getComplexity()*nal.narParameters.COMPLEXITY_UNIT, nal); } /** * Get the current activation level of a concept. * * @param t The Term naming a concept * @return the priority value of the concept */ public static float conceptActivation(final Memory mem, final Term t) { final Concept c = mem.concept(t); return (c == null) ? 0f : c.getPriority(); } /** * Common processing for all inference step * * @param qual Quality of the inference * @param complexity Syntactic complexity of the conclusion * @param nal Reference to the memory * @return Budget of the conclusion task */ private static BudgetValue budgetInference(final float qual, final float complexity, final org.opennars.control.DerivationContext nal) { Item t = nal.getCurrentTask(); if (t == null) { t = nal.getCurrentTask(); } Concept c = nal.getCurrentConcept(); TruthValue beliefTruth = nal.getCurrentBelief() == null ? new TruthValue(1.0f,0.9f, nal.narParameters) : nal.getCurrentBelief().truth; float priority = 0.01f+c.getPriority() * beliefTruth.getExpectation(); float durability = t.getDurability(); //float durability = t.getDurability() / complexity; final float quality = qual / complexity; //not used in ALANN though return new BudgetValue(priority, durability, quality, nal.narParameters); } @Deprecated static BudgetValue solutionEval(final Sentence problem, final Sentence solution, final Task task, final Memory memory) { throw new IllegalStateException("Moved to TemporalRules.java"); } public static BudgetValue budgetTermLinkConcept(final Concept c, final BudgetValue taskBudget, final TermLink termLink) { return taskBudget.clone(); } }
11655_10
import java.util.List; /** * Deze app is interface voor administratie medewerker. * <ul> * <li>Een opsomming van alle studenten die een bepaald vak hebben gehaald.</li> * <li>Een opsomming van alle vakken die een specifieke student heeft gehaald.</li> * <li>Een opsomming van alle vakken die een student nog moet halen.</li> * <li>Het gemiddelde van alle cijfers die studenten voor een bepaald vak hebbengehaald.</li> * <li>De optelsom van alle cijfers die een (meegegeven) student voor alle vakkenheeft gehaald.</li> * <li>De standaarddeviatie van alle cijfers die een student heeft gehaald.</li> * <li>De variantie van alle cijfers die alle studenten voor een vak gehaald hebben.</li> * <li>De docent wil weten of mannen beter of slechter scoren voor een specifiekvak dan vrouwen.</li> * </ul> * @author Joseph Nzi * @version %I% %G% * @see Administratie * @since 1.0 */ public interface IAdministratieMedewerker { Double PASS = 5.5; /** * Methode om een list van student te krijgen * @return een student list * @see #setStudents(List Studenten) */ List<IStudent> getStudents(); /** * Methode om een list van student te maken * @param students list van studenten * @see #getStudents */ void setStudents(List<IStudent> students); /** * Methode om een opsomming van alle studenten die een bepaald vak hebben gehaald te zien. * @param vak is de de modulcode van het vak * @see #checkBest(String Vak) * @see #getGemiddelCijferPerVak(String Vak) */ void getOpsommingBehaald(String vak); /** * Methode om te weten of mannen beter of slechter scoren voor een specifiekvak dan vrouwen. * @param vak is de de modulcode van het vak * @see #getOpsommingBehaald(String Vak) * @see #getGemiddelCijferPerVak(String Vak) */ void checkBest(String vak); /** * Methode om een opsomming van alle vakken die een specifieke student moet nog behalen. * @param student is het student nummer van de student * @see #getNietBehaalStudent(String Student) * @see #getSumCijferPerStudent(String Student) * @see #getGemiddelCijferPerStudent(String Student) * @see #getStandaardeviatieEnVariatie(String Student) */ void getNietBehaalStudent(String student); /** * Methode om een de standaardeviatie en variatie van de student cijfers * @param student is het student nummer van de student * @see #getNietBehaalStudent(String Student) * @see #getSumCijferPerStudent(String Student) * @see #getGemiddelCijferPerStudent(String Student) * @see #getStandaardeviatieEnVariatie(String Student) */ void getStandaardeviatieEnVariatie(String student); /** * Methode om een opsomming van alle vakken die een student heeft behaald. * @param student is de de modulcode van het vak * @see #checkBest(String Vak) * @see #getGemiddelCijferPerVak(String Vak) */ void getBehaalStudent(String student); /** * Methode om het gemiddelde van alle cijfers die studenten hebbengehaald. * @param vak is de de modulcode van het vak * @see #getOpsommingBehaald(String Vak) * @see #checkBest(String Vak) */ void getGemiddelCijferPerVak(String vak); /** * Methode om het gemiddelde van alle cijfers die studenten voor een bepaald vak hebbengehaald. * @param student is het student nummer van de student * @see #getBehaalStudent(String Student) * @see #getNietBehaalStudent(String Student) * @see #getSumCijferPerStudent(String Student) * @see #getStandaardeviatieEnVariatie(String Student) */ void getGemiddelCijferPerStudent(String student); /** * Methode om de optelsom van alle cijfers die een (meegegeven) student voor alle vakkenheeft gehaald. * @param student is het student nummer van de student * @see #getBehaalStudent(String Student) * @see #getNietBehaalStudent(String Student) * @see #getGemiddelCijferPerStudent(String Student) * @see #getStandaardeviatieEnVariatie(String Student) */ void getSumCijferPerStudent(String student); }
patker77/Eindopdracht4
src/IAdministratieMedewerker.java
1,382
/** * Methode om de optelsom van alle cijfers die een (meegegeven) student voor alle vakkenheeft gehaald. * @param student is het student nummer van de student * @see #getBehaalStudent(String Student) * @see #getNietBehaalStudent(String Student) * @see #getGemiddelCijferPerStudent(String Student) * @see #getStandaardeviatieEnVariatie(String Student) */
block_comment
nl
import java.util.List; /** * Deze app is interface voor administratie medewerker. * <ul> * <li>Een opsomming van alle studenten die een bepaald vak hebben gehaald.</li> * <li>Een opsomming van alle vakken die een specifieke student heeft gehaald.</li> * <li>Een opsomming van alle vakken die een student nog moet halen.</li> * <li>Het gemiddelde van alle cijfers die studenten voor een bepaald vak hebbengehaald.</li> * <li>De optelsom van alle cijfers die een (meegegeven) student voor alle vakkenheeft gehaald.</li> * <li>De standaarddeviatie van alle cijfers die een student heeft gehaald.</li> * <li>De variantie van alle cijfers die alle studenten voor een vak gehaald hebben.</li> * <li>De docent wil weten of mannen beter of slechter scoren voor een specifiekvak dan vrouwen.</li> * </ul> * @author Joseph Nzi * @version %I% %G% * @see Administratie * @since 1.0 */ public interface IAdministratieMedewerker { Double PASS = 5.5; /** * Methode om een list van student te krijgen * @return een student list * @see #setStudents(List Studenten) */ List<IStudent> getStudents(); /** * Methode om een list van student te maken * @param students list van studenten * @see #getStudents */ void setStudents(List<IStudent> students); /** * Methode om een opsomming van alle studenten die een bepaald vak hebben gehaald te zien. * @param vak is de de modulcode van het vak * @see #checkBest(String Vak) * @see #getGemiddelCijferPerVak(String Vak) */ void getOpsommingBehaald(String vak); /** * Methode om te weten of mannen beter of slechter scoren voor een specifiekvak dan vrouwen. * @param vak is de de modulcode van het vak * @see #getOpsommingBehaald(String Vak) * @see #getGemiddelCijferPerVak(String Vak) */ void checkBest(String vak); /** * Methode om een opsomming van alle vakken die een specifieke student moet nog behalen. * @param student is het student nummer van de student * @see #getNietBehaalStudent(String Student) * @see #getSumCijferPerStudent(String Student) * @see #getGemiddelCijferPerStudent(String Student) * @see #getStandaardeviatieEnVariatie(String Student) */ void getNietBehaalStudent(String student); /** * Methode om een de standaardeviatie en variatie van de student cijfers * @param student is het student nummer van de student * @see #getNietBehaalStudent(String Student) * @see #getSumCijferPerStudent(String Student) * @see #getGemiddelCijferPerStudent(String Student) * @see #getStandaardeviatieEnVariatie(String Student) */ void getStandaardeviatieEnVariatie(String student); /** * Methode om een opsomming van alle vakken die een student heeft behaald. * @param student is de de modulcode van het vak * @see #checkBest(String Vak) * @see #getGemiddelCijferPerVak(String Vak) */ void getBehaalStudent(String student); /** * Methode om het gemiddelde van alle cijfers die studenten hebbengehaald. * @param vak is de de modulcode van het vak * @see #getOpsommingBehaald(String Vak) * @see #checkBest(String Vak) */ void getGemiddelCijferPerVak(String vak); /** * Methode om het gemiddelde van alle cijfers die studenten voor een bepaald vak hebbengehaald. * @param student is het student nummer van de student * @see #getBehaalStudent(String Student) * @see #getNietBehaalStudent(String Student) * @see #getSumCijferPerStudent(String Student) * @see #getStandaardeviatieEnVariatie(String Student) */ void getGemiddelCijferPerStudent(String student); /** * Methode om de<SUF>*/ void getSumCijferPerStudent(String student); }
201092_24
package at.favre.lib.armadillo; import android.content.SharedPreferences; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.security.SecureRandom; import java.util.HashSet; import java.util.Random; import java.util.Set; import at.favre.lib.bytes.Bytes; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assume.assumeFalse; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @SuppressWarnings("deprecation") public abstract class ASecureSharedPreferencesTest { private static final String DEFAULT_PREF_NAME = "test-prefs"; SharedPreferences preferences; @Before public void setup() { try { preferences = create(DEFAULT_PREF_NAME, null).build(); } catch (Exception e) { e.printStackTrace(); throw e; } } @After public void tearDown() { preferences.edit().clear().commit(); } protected abstract Armadillo.Builder create(String name, char[] pw); protected abstract boolean isKitKatOrBelow(); @Test public void simpleMultipleStringGet() { SharedPreferences preferences = create("manytest", null).build(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 100; j++) { String content = "testäI/_²~" + Bytes.random(64 + j).encodeHex(); preferences.edit().putString("k" + j, content).commit(); assertEquals(content, preferences.getString("k" + j, null)); } } } @Test public void simpleGetString() { putAndTestString(preferences, "string1", 1); putAndTestString(preferences, "string2", 16); putAndTestString(preferences, "string3", 200); } @Test public void simpleGetStringApply() { String content = Bytes.random(16).encodeBase64(); preferences.edit().putString("d", content).apply(); assertEquals(content, preferences.getString("d", null)); } private String putAndTestString(SharedPreferences preferences, String key, int length) { String content = Bytes.random(length).encodeBase64(); preferences.edit().putString(key, content).commit(); assertTrue(preferences.contains(key)); assertEquals(content, preferences.getString(key, null)); return content; } @Test public void simpleGetInt() { int content = 3782633; preferences.edit().putInt("int", content).commit(); assertTrue(preferences.contains("int")); assertEquals(content, preferences.getInt("int", 0)); } @Test public void simpleGetLong() { long content = 3782633654323456L; preferences.edit().putLong("long", content).commit(); assertTrue(preferences.contains("long")); assertEquals(content, preferences.getLong("long", 0)); } @Test public void simpleGetFloat() { float content = 728.1891f; preferences.edit().putFloat("float", content).commit(); assertTrue(preferences.contains("float")); assertEquals(content, preferences.getFloat("float", 0), 0.001); } @Test public void simpleGetBoolean() { preferences.edit().putBoolean("boolean", true).commit(); assertTrue(preferences.contains("boolean")); assertTrue(preferences.getBoolean("boolean", false)); preferences.edit().putBoolean("boolean2", false).commit(); assertFalse(preferences.getBoolean("boolean2", true)); } @Test public void simpleGetStringSet() { addStringSet(preferences, 1); addStringSet(preferences, 7); addStringSet(preferences, 128); } private void addStringSet(SharedPreferences preferences, int count) { Set<String> set = new HashSet<>(count); for (int i = 0; i < count; i++) { set.add(Bytes.random(32).encodeBase36() + "input" + i); } preferences.edit().putStringSet("stringSet" + count, set).commit(); assertTrue(preferences.contains("stringSet" + count)); assertEquals(set, preferences.getStringSet("stringSet" + count, null)); } @Test public void testGetDefaults() { assertNull(preferences.getString("s", null)); assertNull(preferences.getStringSet("s", null)); assertFalse(preferences.getBoolean("s", false)); assertEquals(2, preferences.getInt("s", 2)); assertEquals(2, preferences.getLong("s", 2)); assertEquals(2f, preferences.getFloat("s", 2f), 0.0001); } @Test public void testRemove() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertTrue(preferences.getAll().size() >= count); for (int i = 0; i < count; i++) { preferences.edit().remove("string" + i).commit(); assertNull(preferences.getString("string" + i, null)); } } @Test public void testPutNullString() { String id = "testPutNullString"; putAndTestString(preferences, id, new Random().nextInt(32) + 1); preferences.edit().putString(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testPutNullStringSet() { String id = "testPutNullStringSet"; addStringSet(preferences, 8); preferences.edit().putStringSet(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testClear() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertFalse(preferences.getAll().isEmpty()); preferences.edit().clear().commit(); assertTrue(preferences.getAll().isEmpty()); String newContent = putAndTestString(preferences, "new", new Random().nextInt(32) + 1); assertFalse(preferences.getAll().isEmpty()); preferences = create(DEFAULT_PREF_NAME, null).build(); assertEquals(newContent, preferences.getString("new", null)); } @Test public void testInitializeTwice() { SharedPreferences sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s2", 24); } @Test public void testContainsAfterReinitialization() { SharedPreferences sharedPreferences = create("twice", null).build(); String t = putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("twice", null).build(); assertEquals(t, sharedPreferences.getString("s", null)); putAndTestString(sharedPreferences, "s2", 24); } @Test public void simpleStringGetWithPkdf2Password() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new PBKDF2KeyStretcher(1000, null)).build()); } @Test public void simpleStringGetWithBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(7)).build()); } @Test public void simpleStringGetWithBrokenBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(6)).build()); } @Test public void simpleStringGetWithUnicodePw() { preferenceSmokeTest(create("withPw", "ö案äü_ß²áèµÿA2ijʥ".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void simpleStringGetWithFastKDF() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void testWithCompression() { preferenceSmokeTest(create("compressed", null).compress().build()); } @Test public void testWithDifferentFingerprint() { preferenceSmokeTest(create("fingerprint", null) .encryptionFingerprint(Bytes.random(16).array()).build()); preferenceSmokeTest(create("fingerprint2", null) .encryptionFingerprint(new TestEncryptionFingerprint(new byte[16])).build()); } @Test public void testWithDifferentContentDigest() { preferenceSmokeTest(create("contentDigest1", null) .contentKeyDigest(8).build()); preferenceSmokeTest(create("contentDigest2", null) .contentKeyDigest(Bytes.random(16).array()).build()); preferenceSmokeTest(create("contentDigest3", null) .contentKeyDigest((providedMessage, usageName) -> Bytes.from(providedMessage).append(usageName).encodeUtf8()).build()); } @Test public void testWithSecureRandom() { preferenceSmokeTest(create("secureRandom", null) .secureRandom(new SecureRandom()).build()); } @Test public void testEncryptionStrength() { preferenceSmokeTest(create("secureRandom", null) .encryptionKeyStrength(AuthenticatedEncryption.STRENGTH_HIGH).build()); } @Test public void testProvider() { preferenceSmokeTest(create("provider", null) .securityProvider(null).build()); } @Test public void testWithNoObfuscation() { preferenceSmokeTest(create("obfuscate", null) .dataObfuscatorFactory(new NoObfuscator.Factory()).build()); } @Test public void testSetEncryption() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); preferenceSmokeTest(create("enc", null) .symmetricEncryption(new AesGcmEncryption()).build()); } @Test public void testRecoveryPolicy() { preferenceSmokeTest(create("recovery", null) .recoveryPolicy(true, true).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy(new SimpleRecoveryPolicy.Default(true, true)).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy((e, keyHash, base64Encrypted, pwUsed, sharedPreferences) -> System.out.println(e + " " + keyHash + " " + base64Encrypted + " " + pwUsed)).build()); } @Test public void testCustomProtocolVersion() { preferenceSmokeTest(create("protocol", null) .cryptoProtocolVersion(14221).build()); } void preferenceSmokeTest(SharedPreferences preferences) { putAndTestString(preferences, "string", new Random().nextInt(500) + 1); assertNull(preferences.getString("string2", null)); long contentLong = new Random().nextLong(); preferences.edit().putLong("long", contentLong).commit(); assertEquals(contentLong, preferences.getLong("long", 0)); float contentFloat = new Random().nextFloat(); preferences.edit().putFloat("float", contentFloat).commit(); assertEquals(contentFloat, preferences.getFloat("float", 0), 0.001); boolean contentBoolean = new Random().nextBoolean(); preferences.edit().putBoolean("boolean", contentBoolean).commit(); assertEquals(contentBoolean, preferences.getBoolean("boolean", !contentBoolean)); addStringSet(preferences, new Random().nextInt(31) + 1); preferences.edit().remove("string").commit(); assertNull(preferences.getString("string", null)); preferences.edit().remove("float").commit(); assertEquals(-1, preferences.getFloat("float", -1), 0.00001); } @Test public void testChangePassword() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordWithEnabledDerivedPwCache() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), true); } @Test public void testChangePasswordFromNullPassword() { testChangePassword("testChangePasswordFromNullPassword", null, "pw2".toCharArray(), false); } @Test public void testChangePasswordToNullPassword() { testChangePassword("testChangePasswordToNullPassword", "pw1".toCharArray(), null, false); } @Test public void testChangePasswordFromEmptyPassword() { testChangePassword("testChangePasswordFromEmptyPassword", "".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordToEmptyPassword() { testChangePassword("testChangePasswordToEmptyPassword", "pw1".toCharArray(), "".toCharArray(), false); } private void testChangePassword(String name, char[] currentPassword, char[] newPassword, boolean enableCache) { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and change to new one, all the values should be accessible pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.changePassword(clonePassword(newPassword)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw, should be accessible pref = create(name, clonePassword(newPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw, should throw exception, since cannot decrypt pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } private char[] clonePassword(char[] password) { return password == null ? null : password.clone(); } @Test public void testChangePasswordAndKeyStretchingFunction() { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and old ksFn; change to new one, all the values should be accessible pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.changePassword("pw2".toCharArray(), new ArmadilloBcryptKeyStretcher(8)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and new ksFn, should be accessible pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } // open with old pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testInvalidPasswordShouldNotBeAccessible() { // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with invalid pw, should throw exception, since cannot decrypt pref = create("testInvalidPassword", "pw2".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getInt("k2", 0); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getBoolean("k3", false); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testUpgradeToNewerProtocolVersion() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); // open new preference with old encryption config ArmadilloSharedPreferences pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // add some data pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again with encryption config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); // overwrite old data pref.edit().putInt("k2", 2).commit(); // add some data pref.edit().putString("j1", "string2").putInt("j2", 3).putBoolean("j3", false).commit(); pref.close(); // open again with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals("string2", pref.getString("j1", null)); assertEquals(3, pref.getInt("j2", 0)); assertFalse(pref.getBoolean("j3", true)); pref.close(); // open again with new config WITHOUT old config as support config (removing in the builder) pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .clearAdditionalDecryptionProtocolConfigs() // test remove support protocols in builder .build(); // check overwritten data assertEquals(2, pref.getInt("k2", 0)); try { pref.getString("k1", null); fail("should throw exception, since should not be able to decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testSameKeyDifferentTypeShouldOverwrite() { //this is a similar behavior to normal shared preferences SharedPreferences pref = create("testSameKeyDifferentTypeShouldOverwrite", null).build(); pref.edit().putInt("id", 1).commit(); pref.edit().putString("id", "testNotInt").commit(); TestCase.assertEquals("testNotInt", pref.getString("id", null)); try { pref.getInt("id", -1); TestCase.fail("string should be overwritten with int"); } catch (Exception ignored) { } } }
patrickfav/armadillo
armadillo/src/sharedTest/java/at/favre/lib/armadillo/ASecureSharedPreferencesTest.java
6,870
// check overwritten data
line_comment
nl
package at.favre.lib.armadillo; import android.content.SharedPreferences; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.security.SecureRandom; import java.util.HashSet; import java.util.Random; import java.util.Set; import at.favre.lib.bytes.Bytes; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assume.assumeFalse; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @SuppressWarnings("deprecation") public abstract class ASecureSharedPreferencesTest { private static final String DEFAULT_PREF_NAME = "test-prefs"; SharedPreferences preferences; @Before public void setup() { try { preferences = create(DEFAULT_PREF_NAME, null).build(); } catch (Exception e) { e.printStackTrace(); throw e; } } @After public void tearDown() { preferences.edit().clear().commit(); } protected abstract Armadillo.Builder create(String name, char[] pw); protected abstract boolean isKitKatOrBelow(); @Test public void simpleMultipleStringGet() { SharedPreferences preferences = create("manytest", null).build(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 100; j++) { String content = "testäI/_²~" + Bytes.random(64 + j).encodeHex(); preferences.edit().putString("k" + j, content).commit(); assertEquals(content, preferences.getString("k" + j, null)); } } } @Test public void simpleGetString() { putAndTestString(preferences, "string1", 1); putAndTestString(preferences, "string2", 16); putAndTestString(preferences, "string3", 200); } @Test public void simpleGetStringApply() { String content = Bytes.random(16).encodeBase64(); preferences.edit().putString("d", content).apply(); assertEquals(content, preferences.getString("d", null)); } private String putAndTestString(SharedPreferences preferences, String key, int length) { String content = Bytes.random(length).encodeBase64(); preferences.edit().putString(key, content).commit(); assertTrue(preferences.contains(key)); assertEquals(content, preferences.getString(key, null)); return content; } @Test public void simpleGetInt() { int content = 3782633; preferences.edit().putInt("int", content).commit(); assertTrue(preferences.contains("int")); assertEquals(content, preferences.getInt("int", 0)); } @Test public void simpleGetLong() { long content = 3782633654323456L; preferences.edit().putLong("long", content).commit(); assertTrue(preferences.contains("long")); assertEquals(content, preferences.getLong("long", 0)); } @Test public void simpleGetFloat() { float content = 728.1891f; preferences.edit().putFloat("float", content).commit(); assertTrue(preferences.contains("float")); assertEquals(content, preferences.getFloat("float", 0), 0.001); } @Test public void simpleGetBoolean() { preferences.edit().putBoolean("boolean", true).commit(); assertTrue(preferences.contains("boolean")); assertTrue(preferences.getBoolean("boolean", false)); preferences.edit().putBoolean("boolean2", false).commit(); assertFalse(preferences.getBoolean("boolean2", true)); } @Test public void simpleGetStringSet() { addStringSet(preferences, 1); addStringSet(preferences, 7); addStringSet(preferences, 128); } private void addStringSet(SharedPreferences preferences, int count) { Set<String> set = new HashSet<>(count); for (int i = 0; i < count; i++) { set.add(Bytes.random(32).encodeBase36() + "input" + i); } preferences.edit().putStringSet("stringSet" + count, set).commit(); assertTrue(preferences.contains("stringSet" + count)); assertEquals(set, preferences.getStringSet("stringSet" + count, null)); } @Test public void testGetDefaults() { assertNull(preferences.getString("s", null)); assertNull(preferences.getStringSet("s", null)); assertFalse(preferences.getBoolean("s", false)); assertEquals(2, preferences.getInt("s", 2)); assertEquals(2, preferences.getLong("s", 2)); assertEquals(2f, preferences.getFloat("s", 2f), 0.0001); } @Test public void testRemove() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertTrue(preferences.getAll().size() >= count); for (int i = 0; i < count; i++) { preferences.edit().remove("string" + i).commit(); assertNull(preferences.getString("string" + i, null)); } } @Test public void testPutNullString() { String id = "testPutNullString"; putAndTestString(preferences, id, new Random().nextInt(32) + 1); preferences.edit().putString(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testPutNullStringSet() { String id = "testPutNullStringSet"; addStringSet(preferences, 8); preferences.edit().putStringSet(id, null).apply(); assertFalse(preferences.contains(id)); } @Test public void testClear() { int count = 10; for (int i = 0; i < count; i++) { putAndTestString(preferences, "string" + i, new Random().nextInt(32) + 1); } assertFalse(preferences.getAll().isEmpty()); preferences.edit().clear().commit(); assertTrue(preferences.getAll().isEmpty()); String newContent = putAndTestString(preferences, "new", new Random().nextInt(32) + 1); assertFalse(preferences.getAll().isEmpty()); preferences = create(DEFAULT_PREF_NAME, null).build(); assertEquals(newContent, preferences.getString("new", null)); } @Test public void testInitializeTwice() { SharedPreferences sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("init", null).build(); putAndTestString(sharedPreferences, "s2", 24); } @Test public void testContainsAfterReinitialization() { SharedPreferences sharedPreferences = create("twice", null).build(); String t = putAndTestString(sharedPreferences, "s", 12); sharedPreferences = create("twice", null).build(); assertEquals(t, sharedPreferences.getString("s", null)); putAndTestString(sharedPreferences, "s2", 24); } @Test public void simpleStringGetWithPkdf2Password() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new PBKDF2KeyStretcher(1000, null)).build()); } @Test public void simpleStringGetWithBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(7)).build()); } @Test public void simpleStringGetWithBrokenBcryptPassword() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(6)).build()); } @Test public void simpleStringGetWithUnicodePw() { preferenceSmokeTest(create("withPw", "ö案äü_ß²áèµÿA2ijʥ".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void simpleStringGetWithFastKDF() { preferenceSmokeTest(create("withPw", "superSecret".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build()); } @Test public void testWithCompression() { preferenceSmokeTest(create("compressed", null).compress().build()); } @Test public void testWithDifferentFingerprint() { preferenceSmokeTest(create("fingerprint", null) .encryptionFingerprint(Bytes.random(16).array()).build()); preferenceSmokeTest(create("fingerprint2", null) .encryptionFingerprint(new TestEncryptionFingerprint(new byte[16])).build()); } @Test public void testWithDifferentContentDigest() { preferenceSmokeTest(create("contentDigest1", null) .contentKeyDigest(8).build()); preferenceSmokeTest(create("contentDigest2", null) .contentKeyDigest(Bytes.random(16).array()).build()); preferenceSmokeTest(create("contentDigest3", null) .contentKeyDigest((providedMessage, usageName) -> Bytes.from(providedMessage).append(usageName).encodeUtf8()).build()); } @Test public void testWithSecureRandom() { preferenceSmokeTest(create("secureRandom", null) .secureRandom(new SecureRandom()).build()); } @Test public void testEncryptionStrength() { preferenceSmokeTest(create("secureRandom", null) .encryptionKeyStrength(AuthenticatedEncryption.STRENGTH_HIGH).build()); } @Test public void testProvider() { preferenceSmokeTest(create("provider", null) .securityProvider(null).build()); } @Test public void testWithNoObfuscation() { preferenceSmokeTest(create("obfuscate", null) .dataObfuscatorFactory(new NoObfuscator.Factory()).build()); } @Test public void testSetEncryption() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); preferenceSmokeTest(create("enc", null) .symmetricEncryption(new AesGcmEncryption()).build()); } @Test public void testRecoveryPolicy() { preferenceSmokeTest(create("recovery", null) .recoveryPolicy(true, true).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy(new SimpleRecoveryPolicy.Default(true, true)).build()); preferenceSmokeTest(create("recovery", null) .recoveryPolicy((e, keyHash, base64Encrypted, pwUsed, sharedPreferences) -> System.out.println(e + " " + keyHash + " " + base64Encrypted + " " + pwUsed)).build()); } @Test public void testCustomProtocolVersion() { preferenceSmokeTest(create("protocol", null) .cryptoProtocolVersion(14221).build()); } void preferenceSmokeTest(SharedPreferences preferences) { putAndTestString(preferences, "string", new Random().nextInt(500) + 1); assertNull(preferences.getString("string2", null)); long contentLong = new Random().nextLong(); preferences.edit().putLong("long", contentLong).commit(); assertEquals(contentLong, preferences.getLong("long", 0)); float contentFloat = new Random().nextFloat(); preferences.edit().putFloat("float", contentFloat).commit(); assertEquals(contentFloat, preferences.getFloat("float", 0), 0.001); boolean contentBoolean = new Random().nextBoolean(); preferences.edit().putBoolean("boolean", contentBoolean).commit(); assertEquals(contentBoolean, preferences.getBoolean("boolean", !contentBoolean)); addStringSet(preferences, new Random().nextInt(31) + 1); preferences.edit().remove("string").commit(); assertNull(preferences.getString("string", null)); preferences.edit().remove("float").commit(); assertEquals(-1, preferences.getFloat("float", -1), 0.00001); } @Test public void testChangePassword() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordWithEnabledDerivedPwCache() { testChangePassword("testChangePassword", "pw1".toCharArray(), "pw2".toCharArray(), true); } @Test public void testChangePasswordFromNullPassword() { testChangePassword("testChangePasswordFromNullPassword", null, "pw2".toCharArray(), false); } @Test public void testChangePasswordToNullPassword() { testChangePassword("testChangePasswordToNullPassword", "pw1".toCharArray(), null, false); } @Test public void testChangePasswordFromEmptyPassword() { testChangePassword("testChangePasswordFromEmptyPassword", "".toCharArray(), "pw2".toCharArray(), false); } @Test public void testChangePasswordToEmptyPassword() { testChangePassword("testChangePasswordToEmptyPassword", "pw1".toCharArray(), "".toCharArray(), false); } private void testChangePassword(String name, char[] currentPassword, char[] newPassword, boolean enableCache) { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and change to new one, all the values should be accessible pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.changePassword(clonePassword(newPassword)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw, should be accessible pref = create(name, clonePassword(newPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw, should throw exception, since cannot decrypt pref = create(name, clonePassword(currentPassword)) .enableDerivedPasswordCache(enableCache) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } private char[] clonePassword(char[] password) { return password == null ? null : password.clone(); } @Test public void testChangePasswordAndKeyStretchingFunction() { Set<String> testSet = new HashSet<>(); testSet.add("t1"); testSet.add("t2"); testSet.add("t3"); // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putStringSet("set", testSet) .putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with old pw and old ksFn; change to new one, all the values should be accessible pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); pref.changePassword("pw2".toCharArray(), new ArmadilloBcryptKeyStretcher(8)); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and new ksFn, should be accessible pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new ArmadilloBcryptKeyStretcher(8)).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals(testSet, pref.getStringSet("set", null)); pref.close(); // open with new pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw2".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } // open with old pw and old ksFn, should throw exception, since cannot decrypt pref = create("testChangePassword", "pw1".toCharArray()) .keyStretchingFunction(new BrokenBcryptKeyStretcher(8)).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testInvalidPasswordShouldNotBeAccessible() { // open new shared pref and add some data ArmadilloSharedPreferences pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again and check if can be used pref = create("testInvalidPassword", "pw1".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with invalid pw, should throw exception, since cannot decrypt pref = create("testInvalidPassword", "pw2".toCharArray()) .keyStretchingFunction(new FastKeyStretcher()).build(); try { pref.getString("k1", null); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getInt("k2", 0); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } try { pref.getBoolean("k3", false); fail("should throw exception, since cannot decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testUpgradeToNewerProtocolVersion() { assumeFalse("test not supported on kitkat devices", isKitKatOrBelow()); // open new preference with old encryption config ArmadilloSharedPreferences pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // add some data pref.edit().putString("k1", "string1").putInt("k2", 2).putBoolean("k3", true).commit(); pref.close(); // open again with encryption config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesCbcEncryption()) .cryptoProtocolVersion(-19).build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); pref.close(); // open with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); // overwrite old data pref.edit().putInt("k2", 2).commit(); // add some data pref.edit().putString("j1", "string2").putInt("j2", 3).putBoolean("j3", false).commit(); pref.close(); // open again with new config and add old config as support config pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .build(); // check data assertEquals("string1", pref.getString("k1", null)); assertEquals(2, pref.getInt("k2", 0)); assertTrue(pref.getBoolean("k3", false)); assertEquals("string2", pref.getString("j1", null)); assertEquals(3, pref.getInt("j2", 0)); assertFalse(pref.getBoolean("j3", true)); pref.close(); // open again with new config WITHOUT old config as support config (removing in the builder) pref = create("testUpgradeToNewerProtocolVersion", null) .symmetricEncryption(new AesGcmEncryption()) .cryptoProtocolVersion(0) .addAdditionalDecryptionProtocolConfig(EncryptionProtocolConfig .newDefaultConfig() .authenticatedEncryption(new AesCbcEncryption()) .protocolVersion(-19) .build()) .clearAdditionalDecryptionProtocolConfigs() // test remove support protocols in builder .build(); // check overwritten<SUF> assertEquals(2, pref.getInt("k2", 0)); try { pref.getString("k1", null); fail("should throw exception, since should not be able to decrypt"); } catch (SecureSharedPreferenceCryptoException ignored) { } } @Test public void testSameKeyDifferentTypeShouldOverwrite() { //this is a similar behavior to normal shared preferences SharedPreferences pref = create("testSameKeyDifferentTypeShouldOverwrite", null).build(); pref.edit().putInt("id", 1).commit(); pref.edit().putString("id", "testNotInt").commit(); TestCase.assertEquals("testNotInt", pref.getString("id", null)); try { pref.getInt("id", -1); TestCase.fail("string should be overwritten with int"); } catch (Exception ignored) { } } }
5102_1
package library.wavelets.lift; /** <p> Haar (flat line) wavelet. </p> <p> As with all Lifting scheme wavelet transform functions, the first stage of a transform step is the split stage. The split step moves the even element to the first half of an N element region and the odd elements to the second half of the N element region. </p> <p> The Lifting Scheme version of the Haar transform uses a wavelet function (predict stage) that "predicts" that an odd element will have the same value as it preceeding even element. Stated another way, the odd element is "predicted" to be on a flat (zero slope line) shared with the even point. The difference between this "prediction" and the actual odd value replaces the odd element. </p> <p> The wavelet scaling function (a.k.a. smoothing function) used in the update stage calculates the average between an even and an odd element. </p> <p> The merge stage at the end of the inverse transform interleaves odd and even elements from the two halves of the array (e.g., ordering them even<sub>0</sub>, odd<sub>0</sub>, even<sub>1</sub>, odd<sub>1</sub>, ...) </p> <h4> Copyright and Use </h4> <p> You may use this source code without limitation and without fee as long as you include: </p> <blockquote> This software was written and is copyrighted by Ian Kaplan, Bear Products International, www.bearcave.com, 2001. </blockquote> <p> This software is provided "as is", without any warrenty or claim as to its usefulness. Anyone who uses this source code uses it at their own risk. Nor is any support provided by Ian Kaplan and Bear Products International. <p> Please send any bug fixes or suggested source changes to: <pre> [email protected] </pre> @author Ian Kaplan */ public class Haar extends Liftbase { /** Haar predict step */ protected void predict(double[] vec, int N, int direction) { int half = N >> 1; for (int i = 0; i < half; i++) { double predictVal = vec[i]; int j = i + half; if (direction == forward) { vec[j] = vec[j] - predictVal; } else if (direction == inverse) { vec[j] = vec[j] + predictVal; } else { System.out.println("haar::predict: bad direction value"); } } } /** <p> Update step of the Haar wavelet transform. </p> <p> The wavelet transform calculates a set of detail or difference coefficients in the predict step. These are stored in the upper half of the array. The update step calculates an average from the even-odd element pairs. The averages will replace the even elements in the lower half of the array. </p> <p> The Haar wavelet calculation used in the Lifting Scheme is </p> <pre> d<sub>j+1, i</sub> = odd<sub>j+1, i</sub> = odd<sub>j, i</sub> - even<sub>j, i</sub> a<sub>j+1, i</sub> = even<sub>j, i</sub> = (even<sub>j, i</sub> + odd<sub>j, i</sub>)/2 </pre> <p> Note that the Lifting Scheme uses an in-place algorithm. The odd elements have been replaced by the detail coefficients in the predict step. With a little algebra we can substitute the coefficient calculation into the average calculation, which gives us </p> <pre> a<sub>j+1, i</sub> = even<sub>j, i</sub> = even<sub>j, i</sub> + (odd<sub>j, i</sub>/2) </pre> */ protected void update(double[] vec, int N, int direction) { int half = N >> 1; for (int i = 0; i < half; i++) { int j = i + half; double updateVal = vec[j] / 2.0; if (direction == forward) { vec[i] = vec[i] + updateVal; } else if (direction == inverse) { vec[i] = vec[i] - updateVal; } else { System.out.println("update: bad direction value"); } } } } // haar
patrickzib/SFA
src/main/java/library/wavelets/lift/Haar.java
1,282
/** Haar predict step */
block_comment
nl
package library.wavelets.lift; /** <p> Haar (flat line) wavelet. </p> <p> As with all Lifting scheme wavelet transform functions, the first stage of a transform step is the split stage. The split step moves the even element to the first half of an N element region and the odd elements to the second half of the N element region. </p> <p> The Lifting Scheme version of the Haar transform uses a wavelet function (predict stage) that "predicts" that an odd element will have the same value as it preceeding even element. Stated another way, the odd element is "predicted" to be on a flat (zero slope line) shared with the even point. The difference between this "prediction" and the actual odd value replaces the odd element. </p> <p> The wavelet scaling function (a.k.a. smoothing function) used in the update stage calculates the average between an even and an odd element. </p> <p> The merge stage at the end of the inverse transform interleaves odd and even elements from the two halves of the array (e.g., ordering them even<sub>0</sub>, odd<sub>0</sub>, even<sub>1</sub>, odd<sub>1</sub>, ...) </p> <h4> Copyright and Use </h4> <p> You may use this source code without limitation and without fee as long as you include: </p> <blockquote> This software was written and is copyrighted by Ian Kaplan, Bear Products International, www.bearcave.com, 2001. </blockquote> <p> This software is provided "as is", without any warrenty or claim as to its usefulness. Anyone who uses this source code uses it at their own risk. Nor is any support provided by Ian Kaplan and Bear Products International. <p> Please send any bug fixes or suggested source changes to: <pre> [email protected] </pre> @author Ian Kaplan */ public class Haar extends Liftbase { /** Haar predict step <SUF>*/ protected void predict(double[] vec, int N, int direction) { int half = N >> 1; for (int i = 0; i < half; i++) { double predictVal = vec[i]; int j = i + half; if (direction == forward) { vec[j] = vec[j] - predictVal; } else if (direction == inverse) { vec[j] = vec[j] + predictVal; } else { System.out.println("haar::predict: bad direction value"); } } } /** <p> Update step of the Haar wavelet transform. </p> <p> The wavelet transform calculates a set of detail or difference coefficients in the predict step. These are stored in the upper half of the array. The update step calculates an average from the even-odd element pairs. The averages will replace the even elements in the lower half of the array. </p> <p> The Haar wavelet calculation used in the Lifting Scheme is </p> <pre> d<sub>j+1, i</sub> = odd<sub>j+1, i</sub> = odd<sub>j, i</sub> - even<sub>j, i</sub> a<sub>j+1, i</sub> = even<sub>j, i</sub> = (even<sub>j, i</sub> + odd<sub>j, i</sub>)/2 </pre> <p> Note that the Lifting Scheme uses an in-place algorithm. The odd elements have been replaced by the detail coefficients in the predict step. With a little algebra we can substitute the coefficient calculation into the average calculation, which gives us </p> <pre> a<sub>j+1, i</sub> = even<sub>j, i</sub> = even<sub>j, i</sub> + (odd<sub>j, i</sub>/2) </pre> */ protected void update(double[] vec, int N, int direction) { int half = N >> 1; for (int i = 0; i < half; i++) { int j = i + half; double updateVal = vec[j] / 2.0; if (direction == forward) { vec[i] = vec[i] + updateVal; } else if (direction == inverse) { vec[i] = vec[i] - updateVal; } else { System.out.println("update: bad direction value"); } } } } // haar
106406_2
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.datasketches.cpc; import static java.lang.Math.pow; import static java.lang.Math.round; import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals; /** * @author Lee Rhodes */ public class TestUtil { static final double pwrLaw10NextDouble(final int ppb, final double curPoint) { final double cur = (curPoint < 1.0) ? 1.0 : curPoint; double gi = round(Math.log10(cur) * ppb); //current generating index double next; do { next = round(pow(10.0, ++gi / ppb)); } while (next <= curPoint); return next; } static boolean specialEquals(final CpcSketch sk1, final CpcSketch sk2, final boolean sk1wasMerged, final boolean sk2wasMerged) { rtAssertEquals(sk1.seed, sk2.seed); rtAssertEquals(sk1.lgK, sk2.lgK); rtAssertEquals(sk1.numCoupons, sk2.numCoupons); rtAssertEquals(sk1.windowOffset, sk2.windowOffset); rtAssertEquals(sk1.slidingWindow, sk2.slidingWindow); PairTable.equals(sk1.pairTable, sk2.pairTable); // fiCol is only updated occasionally while stream processing, // therefore, the stream sketch could be behind the merged sketch. // So we have to recalculate the FiCol on the stream sketch. final int ficolA = sk1.fiCol; final int ficolB = sk2.fiCol; if (!sk1wasMerged && sk2wasMerged) { rtAssert(!sk1.mergeFlag && sk2.mergeFlag); final int fiCol1 = calculateFirstInterestingColumn(sk1); rtAssertEquals(fiCol1, sk2.fiCol); } else if (sk1wasMerged && !sk2wasMerged) { rtAssert(sk1.mergeFlag && !sk2.mergeFlag); final int fiCol2 = calculateFirstInterestingColumn(sk2); rtAssertEquals(fiCol2,sk1.fiCol); } else { rtAssertEquals(sk1.mergeFlag, sk2.mergeFlag); rtAssertEquals(ficolA, ficolB); rtAssertEquals(sk1.kxp, sk2.kxp, .01 * sk1.kxp); //1% tolerance rtAssertEquals(sk1.hipEstAccum, sk2.hipEstAccum, 01 * sk1.hipEstAccum); //1% tolerance } return true; } static int calculateFirstInterestingColumn(final CpcSketch sketch) { final int offset = sketch.windowOffset; if (offset == 0) { return 0; } final PairTable table = sketch.pairTable; assert (table != null); final int[] slots = table.getSlotsArr(); final int numSlots = 1 << table.getLgSizeInts(); int i; int result = offset; for (i = 0; i < numSlots; i++) { final int rowCol = slots[i]; if (rowCol != -1) { final int col = rowCol & 63; if (col < result) { result = col; } } } return result; } }
paulk-asert/incubator-datasketches-java
src/main/java/org/apache/datasketches/cpc/TestUtil.java
1,115
//current generating index
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.datasketches.cpc; import static java.lang.Math.pow; import static java.lang.Math.round; import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssert; import static org.apache.datasketches.cpc.RuntimeAsserts.rtAssertEquals; /** * @author Lee Rhodes */ public class TestUtil { static final double pwrLaw10NextDouble(final int ppb, final double curPoint) { final double cur = (curPoint < 1.0) ? 1.0 : curPoint; double gi = round(Math.log10(cur) * ppb); //current generating<SUF> double next; do { next = round(pow(10.0, ++gi / ppb)); } while (next <= curPoint); return next; } static boolean specialEquals(final CpcSketch sk1, final CpcSketch sk2, final boolean sk1wasMerged, final boolean sk2wasMerged) { rtAssertEquals(sk1.seed, sk2.seed); rtAssertEquals(sk1.lgK, sk2.lgK); rtAssertEquals(sk1.numCoupons, sk2.numCoupons); rtAssertEquals(sk1.windowOffset, sk2.windowOffset); rtAssertEquals(sk1.slidingWindow, sk2.slidingWindow); PairTable.equals(sk1.pairTable, sk2.pairTable); // fiCol is only updated occasionally while stream processing, // therefore, the stream sketch could be behind the merged sketch. // So we have to recalculate the FiCol on the stream sketch. final int ficolA = sk1.fiCol; final int ficolB = sk2.fiCol; if (!sk1wasMerged && sk2wasMerged) { rtAssert(!sk1.mergeFlag && sk2.mergeFlag); final int fiCol1 = calculateFirstInterestingColumn(sk1); rtAssertEquals(fiCol1, sk2.fiCol); } else if (sk1wasMerged && !sk2wasMerged) { rtAssert(sk1.mergeFlag && !sk2.mergeFlag); final int fiCol2 = calculateFirstInterestingColumn(sk2); rtAssertEquals(fiCol2,sk1.fiCol); } else { rtAssertEquals(sk1.mergeFlag, sk2.mergeFlag); rtAssertEquals(ficolA, ficolB); rtAssertEquals(sk1.kxp, sk2.kxp, .01 * sk1.kxp); //1% tolerance rtAssertEquals(sk1.hipEstAccum, sk2.hipEstAccum, 01 * sk1.hipEstAccum); //1% tolerance } return true; } static int calculateFirstInterestingColumn(final CpcSketch sketch) { final int offset = sketch.windowOffset; if (offset == 0) { return 0; } final PairTable table = sketch.pairTable; assert (table != null); final int[] slots = table.getSlotsArr(); final int numSlots = 1 << table.getLgSizeInts(); int i; int result = offset; for (i = 0; i < numSlots; i++) { final int rowCol = slots[i]; if (rowCol != -1) { final int col = rowCol & 63; if (col < result) { result = col; } } } return result; } }
43042_1
package com.atakmap.comms; import android.os.Bundle; import com.atakmap.android.http.rest.ServerVersion; import com.atakmap.annotations.FortifyFinding; import com.atakmap.comms.app.CotPortListActivity; import com.atakmap.coremap.filesystem.FileSystemUtils; import com.atakmap.coremap.log.Log; /** * Metadata for a TAK server connection * Moved out of {@link CotPortListActivity.CotPort} */ public class TAKServer { private static final String TAG = "TAKServer"; public static final String CONNECT_STRING_KEY = "connectString"; public static final String DESCRIPTION_KEY = "description"; public static final String COMPRESSION_KEY = "compress"; public static final String ENABLED_KEY = "enabled"; public static final String CONNECTED_KEY = "connected"; public static final String ERROR_KEY = "error"; public static final String SERVER_VERSION_KEY = "serverVersion"; public static final String SERVER_API_KEY = "serverAPI"; public static final String USEAUTH_KEY = "useAuth"; public static final String USERNAME_KEY = "username"; public static final String ENROLL_FOR_CERT_KEY = "enrollForCertificateWithTrust"; public static final String EXPIRATION_KEY = "expiration"; @FortifyFinding(finding = "Password Management: Hardcoded Password", rational = "This is only a key and not a password") public static final String PASSWORD_KEY = "password"; public static final String CACHECREDS_KEY = "cacheCreds"; public static final String ISSTREAM_KEY = "isStream"; public static final String ISCHAT_KEY = "isChat"; private final Bundle data; public TAKServer(Bundle bundle) throws IllegalArgumentException { String connectString = bundle.getString(CONNECT_STRING_KEY); if (connectString == null || connectString.trim().length() == 0) { throw new IllegalArgumentException( "Cannot construct CotPort with empty/null connnectString"); } this.data = new Bundle(bundle); } public TAKServer(TAKServer other) { this(other.getData()); } @Override public boolean equals(Object other) { if (other instanceof TAKServer) return getConnectString().equalsIgnoreCase(((TAKServer) other) .getConnectString()); return false; } public String getConnectString() { return this.data.getString(CONNECT_STRING_KEY); } public String getURL(boolean includePort) { try { NetConnectString ncs = NetConnectString.fromString( getConnectString()); String proto = ncs.getProto(); if (proto.equalsIgnoreCase("ssl")) proto = "https"; else proto = "http"; String url = proto + "://" + ncs.getHost(); if (includePort) url += ":" + ncs.getPort(); return url; } catch (Exception e) { Log.e(TAG, "Failed to get server URL: " + this, e); } return null; } public void setServerVersion(ServerVersion version) { setServerVersion(version.getVersion()); this.data.putInt(SERVER_API_KEY, version.getApiVersion()); } public void setServerVersion(String version) { this.data.putString(SERVER_VERSION_KEY, version); } public String getServerVersion() { return this.data.getString(SERVER_VERSION_KEY); } public int getServerAPI() { return this.data.getInt(SERVER_API_KEY, -1); } public void setErrorString(String error) { appendString(this.data, ERROR_KEY, error); } public static void appendString(Bundle data, String key, String value) { String existing = data.getString(key); if (FileSystemUtils.isEmpty(existing)) data.putString(key, value); else if (!existing.contains(value)) { data.putString(key, existing + ", " + value); } } public String getErrorString() { return this.data.getString(ERROR_KEY); } public boolean isCompressed() { return this.data.getBoolean(COMPRESSION_KEY, false); } public boolean isUsingAuth() { return this.data.getBoolean(USEAUTH_KEY, false); } public boolean enrollForCert() { return this.data.getBoolean(ENROLL_FOR_CERT_KEY, false); } public boolean isStream() { return this.data.getBoolean(ISSTREAM_KEY, false); } public boolean isChat() { return this.data.getBoolean(ISCHAT_KEY, false); } public String getCacheCredentials() { String cacheCreds = this.data.getString(CACHECREDS_KEY); if (cacheCreds == null) { cacheCreds = ""; } return cacheCreds; } public String getDescription() { String description = this.data.getString(DESCRIPTION_KEY); if (description == null) { description = ""; } return description; } public String getUsername() { String s = this.data.getString(USERNAME_KEY); if (s == null) { s = ""; } return s; } public String getPassword() { String s = this.data.getString(PASSWORD_KEY); if (s == null) { s = ""; } return s; } @Override public int hashCode() { return this.getConnectString().hashCode(); } public boolean isEnabled() { return this.data.getBoolean(ENABLED_KEY, true); } public void setEnabled(boolean newValue) { this.data.putBoolean(ENABLED_KEY, newValue); } public boolean isConnected() { return this.data.getBoolean(CONNECTED_KEY, false); } public void setConnected(boolean newValue) { this.data.putBoolean(CONNECTED_KEY, newValue); if (newValue) this.data.remove(ERROR_KEY); } @Override public String toString() { if (data != null) { return "connect_string=" + data.getString(CONNECT_STRING_KEY) + " " + "description=" + data.getString(DESCRIPTION_KEY) + " " + "compression=" + data.getBoolean(COMPRESSION_KEY) + " " + "enabled=" + data.getBoolean(ENABLED_KEY) + " " + "connected=" + data.getBoolean(CONNECTED_KEY); } return super.toString(); } public Bundle getData() { return this.data; } }
paulmandal/AndroidTacticalAssaultKit-CIV
atak/ATAK/app/src/main/java/com/atakmap/comms/TAKServer.java
1,852
//" + ncs.getHost();
line_comment
nl
package com.atakmap.comms; import android.os.Bundle; import com.atakmap.android.http.rest.ServerVersion; import com.atakmap.annotations.FortifyFinding; import com.atakmap.comms.app.CotPortListActivity; import com.atakmap.coremap.filesystem.FileSystemUtils; import com.atakmap.coremap.log.Log; /** * Metadata for a TAK server connection * Moved out of {@link CotPortListActivity.CotPort} */ public class TAKServer { private static final String TAG = "TAKServer"; public static final String CONNECT_STRING_KEY = "connectString"; public static final String DESCRIPTION_KEY = "description"; public static final String COMPRESSION_KEY = "compress"; public static final String ENABLED_KEY = "enabled"; public static final String CONNECTED_KEY = "connected"; public static final String ERROR_KEY = "error"; public static final String SERVER_VERSION_KEY = "serverVersion"; public static final String SERVER_API_KEY = "serverAPI"; public static final String USEAUTH_KEY = "useAuth"; public static final String USERNAME_KEY = "username"; public static final String ENROLL_FOR_CERT_KEY = "enrollForCertificateWithTrust"; public static final String EXPIRATION_KEY = "expiration"; @FortifyFinding(finding = "Password Management: Hardcoded Password", rational = "This is only a key and not a password") public static final String PASSWORD_KEY = "password"; public static final String CACHECREDS_KEY = "cacheCreds"; public static final String ISSTREAM_KEY = "isStream"; public static final String ISCHAT_KEY = "isChat"; private final Bundle data; public TAKServer(Bundle bundle) throws IllegalArgumentException { String connectString = bundle.getString(CONNECT_STRING_KEY); if (connectString == null || connectString.trim().length() == 0) { throw new IllegalArgumentException( "Cannot construct CotPort with empty/null connnectString"); } this.data = new Bundle(bundle); } public TAKServer(TAKServer other) { this(other.getData()); } @Override public boolean equals(Object other) { if (other instanceof TAKServer) return getConnectString().equalsIgnoreCase(((TAKServer) other) .getConnectString()); return false; } public String getConnectString() { return this.data.getString(CONNECT_STRING_KEY); } public String getURL(boolean includePort) { try { NetConnectString ncs = NetConnectString.fromString( getConnectString()); String proto = ncs.getProto(); if (proto.equalsIgnoreCase("ssl")) proto = "https"; else proto = "http"; String url = proto + "://" +<SUF> if (includePort) url += ":" + ncs.getPort(); return url; } catch (Exception e) { Log.e(TAG, "Failed to get server URL: " + this, e); } return null; } public void setServerVersion(ServerVersion version) { setServerVersion(version.getVersion()); this.data.putInt(SERVER_API_KEY, version.getApiVersion()); } public void setServerVersion(String version) { this.data.putString(SERVER_VERSION_KEY, version); } public String getServerVersion() { return this.data.getString(SERVER_VERSION_KEY); } public int getServerAPI() { return this.data.getInt(SERVER_API_KEY, -1); } public void setErrorString(String error) { appendString(this.data, ERROR_KEY, error); } public static void appendString(Bundle data, String key, String value) { String existing = data.getString(key); if (FileSystemUtils.isEmpty(existing)) data.putString(key, value); else if (!existing.contains(value)) { data.putString(key, existing + ", " + value); } } public String getErrorString() { return this.data.getString(ERROR_KEY); } public boolean isCompressed() { return this.data.getBoolean(COMPRESSION_KEY, false); } public boolean isUsingAuth() { return this.data.getBoolean(USEAUTH_KEY, false); } public boolean enrollForCert() { return this.data.getBoolean(ENROLL_FOR_CERT_KEY, false); } public boolean isStream() { return this.data.getBoolean(ISSTREAM_KEY, false); } public boolean isChat() { return this.data.getBoolean(ISCHAT_KEY, false); } public String getCacheCredentials() { String cacheCreds = this.data.getString(CACHECREDS_KEY); if (cacheCreds == null) { cacheCreds = ""; } return cacheCreds; } public String getDescription() { String description = this.data.getString(DESCRIPTION_KEY); if (description == null) { description = ""; } return description; } public String getUsername() { String s = this.data.getString(USERNAME_KEY); if (s == null) { s = ""; } return s; } public String getPassword() { String s = this.data.getString(PASSWORD_KEY); if (s == null) { s = ""; } return s; } @Override public int hashCode() { return this.getConnectString().hashCode(); } public boolean isEnabled() { return this.data.getBoolean(ENABLED_KEY, true); } public void setEnabled(boolean newValue) { this.data.putBoolean(ENABLED_KEY, newValue); } public boolean isConnected() { return this.data.getBoolean(CONNECTED_KEY, false); } public void setConnected(boolean newValue) { this.data.putBoolean(CONNECTED_KEY, newValue); if (newValue) this.data.remove(ERROR_KEY); } @Override public String toString() { if (data != null) { return "connect_string=" + data.getString(CONNECT_STRING_KEY) + " " + "description=" + data.getString(DESCRIPTION_KEY) + " " + "compression=" + data.getBoolean(COMPRESSION_KEY) + " " + "enabled=" + data.getBoolean(ENABLED_KEY) + " " + "connected=" + data.getBoolean(CONNECTED_KEY); } return super.toString(); } public Bundle getData() { return this.data; } }
27779_9
/* LanguageTool, a natural language style checker * Copyright (C) 2023 Mark Baas * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.nl; import com.google.common.collect.ImmutableSet; import org.languagetool.*; import org.languagetool.rules.RuleMatch; import org.languagetool.tagging.Tagger; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.regex.Pattern; /** * Accept Dutch compounds that are not accepted by the speller. This code * is supposed to accept more words in order to extend the speller, but it's not meant * to accept all valid compounds. * It works on 2-part compounds only for now. */ public class CompoundAcceptor { private static final Pattern acronymPattern = Pattern.compile("[A-Z][A-Z][A-Z]-"); private static final Pattern normalCasePattern = Pattern.compile("[A-Za-z][a-zé]*"); private static final int MAX_WORD_SIZE = 35; // if part 1 ends with this, it always needs an 's' appended private final Set<String> alwaysNeedsS = ImmutableSet.of( "heids", "ings", "teits", "schaps" ); // compound parts that need an 's' appended to be used as first part of the compound: private final Set<String> needsS = ImmutableSet.of( "bedrijfs", "passagiers", "dorps", "gezichts", "lijdens", "gevechts", "oorlogs", "arbeiders", "overlijdens", "vrijwilligers", "personeels", "onderhouds", "levens", "jongens", "meisjes", "eindejaars", "etens", "allemans", "afgods", "varkens" ); // compound parts that must not have an 's' appended to be used as first part of the compound: private final Set<String> noS = ImmutableSet.of( "woning", "kinder", "fractie", "schade", "energie", "gemeente", "dienst", "wereld", "telefoon", "aandeel", "zwanger", "papier", "televisie", "bezoek", "achtergrond", "mensenrechten", "organisatie", "literatuur", "onderwijs", "informatie", "studenten", "productie", "vrouwen", "mannen", "karakter", "theater", "competitie", "politie", "luchtvaart", "belangen", "vreugde", "pyjama", "ruimtevaart", "contract", "hoofd", "woord", "probleem", "school", "feest", "familie", "boeren", "vogel", "lucht", "straat", "voorbeeld", "privé", "café", "auto", "periode", "einde", "ruimte", "hoogte", "keuze", "waarde", "ronde", "finale", "gemiddelde", "orde", "gedeelte", "lengte", "type", "liefde", "route", "bijdrage", "ziekte", "behoefte", "fase", "methode", "aangifte", "zijde", "rente", "grootte", "geboorte", "bijlage", "boete", "analyse", "warmte", "gedachte", "opname", "breedte", "overname", "offerte", "diepte", "etappe", "pauze", "hectare", "ellende", "sterkte", "seconde", "volume", "diagnose", "weduwe", "stilte", "hybride", "expertise", "belofte", "ambulance", "gewoonte", "vitamine", "weergave", "bende", "module", "uiteinde", "zonde", "ritme", "blessure", "groente", "droogte", "afname", "dikte", "legende", "oplage", "halte", "akte", "prototype", "binnenste", "inzage", "verte", "hypothese", "kazerne", "rotonde", "menigte", "inname", "mechanisme", "kudde", "brigade", "douane", "kade", "mythe", "bediende", "verloofde", "algoritme", "gestalte", "schaarste", "genade", "piste", "voorronde", "antenne", "controverse", "gehalte", "ruïne", "synagoge", "aanname", "voorliefde", "vlakte", "oorkonde", "gilde", "piramide", "zwakte", "krapte", "secretaresse", "organisme", "fanfare", "episode", "sterfte", "gesteente", "pedicure", "uitgifte", "gebergte", "tube", "gedaante", "terzijde", "genocide", "gezegde", "beroerte", "detective", "synthese", "estafette", "oase", "holte", "nuance", "tombe", "leegte", "voorbode", "weide", "novelle", "curve", "metamorfose", "sekte", "accessoire", "attitude", "horde", "voorhoede", "anekdote", "tenue", "façade", "lade", "afgifte", "synode", "catastrofe", "impasse", "gravure", "bolide", "orgasme", "meute", "satire", "vete", "toelage", "trede", "prothese", "cassette", "made", "gevaarte", "zwaarte", "psychose", "balustrade", "allure", "cantate", "collecte", "mascotte", "fluoride" ); // Make sure we don't allow compound words where part 1 ends with a specific vowel and part2 starts with one, for words like "politieeenheid". private final Set<String> collidingVowels = ImmutableSet.of( "aa", "ae", "ai", "au", "ee", "ée", "ei", "éi", "eu", "éu", "ie", "ii", "ij", "oe", "oi", "oo", "ou", "ui", "uu" ); private static final MorfologikDutchSpellerRule speller; static { try { speller = new MorfologikDutchSpellerRule(JLanguageTool.getMessageBundle(), Languages.getLanguageForShortCode("nl"), null); } catch (IOException e) { throw new RuntimeException(e); } } private final Tagger tagger; CompoundAcceptor() { tagger = Languages.getLanguageForShortCode("nl").getTagger(); } public CompoundAcceptor(Tagger tagger) { this.tagger = tagger; } boolean acceptCompound(String word) throws IOException { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return false; } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (acceptCompound(part1, part2)) { System.out.println(part1+part2 + " -> accepted"); return true; } } return false; } public List<String> getParts(String word) { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return Collections.emptyList(); } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (acceptCompound(part1, part2)) { return Arrays.asList(part1, part2); } } return Collections.emptyList(); } boolean acceptCompound(String part1, String part2) { try { String part1lc = part1.toLowerCase(); if (part1.endsWith("s")) { for (String suffix : alwaysNeedsS) { if (part1lc.endsWith(suffix)) { return isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2); } } return needsS.contains(part1lc) && isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2); } else if (part1.endsWith("-")) { // abbreviations return abbrevOk(part1) && spellingOk(part2); } else if (part2.startsWith("-")) { // vowel collision part2 = part2.substring(1); return noS.contains(part1lc) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && hasCollidingVowels(part1, part2); } else { return noS.contains(part1lc) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && !hasCollidingVowels(part1, part2); } } catch (IOException e) { throw new RuntimeException(e); } } boolean isNoun(String word) throws IOException { List<AnalyzedTokenReadings> part2Readings = tagger.tag(Arrays.asList(word)); return part2Readings.stream().anyMatch(k -> k.hasPosTagStartingWith("ZNW")); } private boolean hasCollidingVowels(String part1, String part2) { char char1 = part1.charAt(part1.length() - 1); char char2 = part2.charAt(0); String vowels = String.valueOf(char1) + char2; return collidingVowels.contains(vowels.toLowerCase()); } private boolean abbrevOk(String nonCompound) { // for compound words like IRA-akkoord, JPG-bestand return acronymPattern.matcher(nonCompound).matches(); } private boolean spellingOk(String nonCompound) throws IOException { if (!normalCasePattern.matcher(nonCompound).matches()) { return false; // e.g. kinderenHet -> split as kinder,enHet } AnalyzedSentence as = new AnalyzedSentence(new AnalyzedTokenReadings[] { new AnalyzedTokenReadings(new AnalyzedToken(nonCompound.toLowerCase(), "FAKE_POS", "fakeLemma")) }); RuleMatch[] matches = speller.match(as); return matches.length == 0; } public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: " + CompoundAcceptor.class.getName() + " <file>"); System.exit(1); } CompoundAcceptor acceptor = new CompoundAcceptor(); List<String> words = Files.readAllLines(Paths.get(args[0])); for (String word : words) { boolean accepted = acceptor.acceptCompound(word); System.out.println(accepted + " " + word); } } }
pawsitive-pc/languagetool
languagetool-language-modules/nl/src/main/java/org/languagetool/rules/nl/CompoundAcceptor.java
3,628
// e.g. kinderenHet -> split as kinder,enHet
line_comment
nl
/* LanguageTool, a natural language style checker * Copyright (C) 2023 Mark Baas * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.nl; import com.google.common.collect.ImmutableSet; import org.languagetool.*; import org.languagetool.rules.RuleMatch; import org.languagetool.tagging.Tagger; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.regex.Pattern; /** * Accept Dutch compounds that are not accepted by the speller. This code * is supposed to accept more words in order to extend the speller, but it's not meant * to accept all valid compounds. * It works on 2-part compounds only for now. */ public class CompoundAcceptor { private static final Pattern acronymPattern = Pattern.compile("[A-Z][A-Z][A-Z]-"); private static final Pattern normalCasePattern = Pattern.compile("[A-Za-z][a-zé]*"); private static final int MAX_WORD_SIZE = 35; // if part 1 ends with this, it always needs an 's' appended private final Set<String> alwaysNeedsS = ImmutableSet.of( "heids", "ings", "teits", "schaps" ); // compound parts that need an 's' appended to be used as first part of the compound: private final Set<String> needsS = ImmutableSet.of( "bedrijfs", "passagiers", "dorps", "gezichts", "lijdens", "gevechts", "oorlogs", "arbeiders", "overlijdens", "vrijwilligers", "personeels", "onderhouds", "levens", "jongens", "meisjes", "eindejaars", "etens", "allemans", "afgods", "varkens" ); // compound parts that must not have an 's' appended to be used as first part of the compound: private final Set<String> noS = ImmutableSet.of( "woning", "kinder", "fractie", "schade", "energie", "gemeente", "dienst", "wereld", "telefoon", "aandeel", "zwanger", "papier", "televisie", "bezoek", "achtergrond", "mensenrechten", "organisatie", "literatuur", "onderwijs", "informatie", "studenten", "productie", "vrouwen", "mannen", "karakter", "theater", "competitie", "politie", "luchtvaart", "belangen", "vreugde", "pyjama", "ruimtevaart", "contract", "hoofd", "woord", "probleem", "school", "feest", "familie", "boeren", "vogel", "lucht", "straat", "voorbeeld", "privé", "café", "auto", "periode", "einde", "ruimte", "hoogte", "keuze", "waarde", "ronde", "finale", "gemiddelde", "orde", "gedeelte", "lengte", "type", "liefde", "route", "bijdrage", "ziekte", "behoefte", "fase", "methode", "aangifte", "zijde", "rente", "grootte", "geboorte", "bijlage", "boete", "analyse", "warmte", "gedachte", "opname", "breedte", "overname", "offerte", "diepte", "etappe", "pauze", "hectare", "ellende", "sterkte", "seconde", "volume", "diagnose", "weduwe", "stilte", "hybride", "expertise", "belofte", "ambulance", "gewoonte", "vitamine", "weergave", "bende", "module", "uiteinde", "zonde", "ritme", "blessure", "groente", "droogte", "afname", "dikte", "legende", "oplage", "halte", "akte", "prototype", "binnenste", "inzage", "verte", "hypothese", "kazerne", "rotonde", "menigte", "inname", "mechanisme", "kudde", "brigade", "douane", "kade", "mythe", "bediende", "verloofde", "algoritme", "gestalte", "schaarste", "genade", "piste", "voorronde", "antenne", "controverse", "gehalte", "ruïne", "synagoge", "aanname", "voorliefde", "vlakte", "oorkonde", "gilde", "piramide", "zwakte", "krapte", "secretaresse", "organisme", "fanfare", "episode", "sterfte", "gesteente", "pedicure", "uitgifte", "gebergte", "tube", "gedaante", "terzijde", "genocide", "gezegde", "beroerte", "detective", "synthese", "estafette", "oase", "holte", "nuance", "tombe", "leegte", "voorbode", "weide", "novelle", "curve", "metamorfose", "sekte", "accessoire", "attitude", "horde", "voorhoede", "anekdote", "tenue", "façade", "lade", "afgifte", "synode", "catastrofe", "impasse", "gravure", "bolide", "orgasme", "meute", "satire", "vete", "toelage", "trede", "prothese", "cassette", "made", "gevaarte", "zwaarte", "psychose", "balustrade", "allure", "cantate", "collecte", "mascotte", "fluoride" ); // Make sure we don't allow compound words where part 1 ends with a specific vowel and part2 starts with one, for words like "politieeenheid". private final Set<String> collidingVowels = ImmutableSet.of( "aa", "ae", "ai", "au", "ee", "ée", "ei", "éi", "eu", "éu", "ie", "ii", "ij", "oe", "oi", "oo", "ou", "ui", "uu" ); private static final MorfologikDutchSpellerRule speller; static { try { speller = new MorfologikDutchSpellerRule(JLanguageTool.getMessageBundle(), Languages.getLanguageForShortCode("nl"), null); } catch (IOException e) { throw new RuntimeException(e); } } private final Tagger tagger; CompoundAcceptor() { tagger = Languages.getLanguageForShortCode("nl").getTagger(); } public CompoundAcceptor(Tagger tagger) { this.tagger = tagger; } boolean acceptCompound(String word) throws IOException { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return false; } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (acceptCompound(part1, part2)) { System.out.println(part1+part2 + " -> accepted"); return true; } } return false; } public List<String> getParts(String word) { if (word.length() > MAX_WORD_SIZE) { // prevent long runtime return Collections.emptyList(); } for (int i = 3; i < word.length() - 3; i++) { String part1 = word.substring(0, i); String part2 = word.substring(i); if (acceptCompound(part1, part2)) { return Arrays.asList(part1, part2); } } return Collections.emptyList(); } boolean acceptCompound(String part1, String part2) { try { String part1lc = part1.toLowerCase(); if (part1.endsWith("s")) { for (String suffix : alwaysNeedsS) { if (part1lc.endsWith(suffix)) { return isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2); } } return needsS.contains(part1lc) && isNoun(part2) && spellingOk(part1.substring(0, part1.length() - 1)) && spellingOk(part2); } else if (part1.endsWith("-")) { // abbreviations return abbrevOk(part1) && spellingOk(part2); } else if (part2.startsWith("-")) { // vowel collision part2 = part2.substring(1); return noS.contains(part1lc) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && hasCollidingVowels(part1, part2); } else { return noS.contains(part1lc) && isNoun(part2) && spellingOk(part1) && spellingOk(part2) && !hasCollidingVowels(part1, part2); } } catch (IOException e) { throw new RuntimeException(e); } } boolean isNoun(String word) throws IOException { List<AnalyzedTokenReadings> part2Readings = tagger.tag(Arrays.asList(word)); return part2Readings.stream().anyMatch(k -> k.hasPosTagStartingWith("ZNW")); } private boolean hasCollidingVowels(String part1, String part2) { char char1 = part1.charAt(part1.length() - 1); char char2 = part2.charAt(0); String vowels = String.valueOf(char1) + char2; return collidingVowels.contains(vowels.toLowerCase()); } private boolean abbrevOk(String nonCompound) { // for compound words like IRA-akkoord, JPG-bestand return acronymPattern.matcher(nonCompound).matches(); } private boolean spellingOk(String nonCompound) throws IOException { if (!normalCasePattern.matcher(nonCompound).matches()) { return false; // e.g. kinderenHet<SUF> } AnalyzedSentence as = new AnalyzedSentence(new AnalyzedTokenReadings[] { new AnalyzedTokenReadings(new AnalyzedToken(nonCompound.toLowerCase(), "FAKE_POS", "fakeLemma")) }); RuleMatch[] matches = speller.match(as); return matches.length == 0; } public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: " + CompoundAcceptor.class.getName() + " <file>"); System.exit(1); } CompoundAcceptor acceptor = new CompoundAcceptor(); List<String> words = Files.readAllLines(Paths.get(args[0])); for (String word : words) { boolean accepted = acceptor.acceptCompound(word); System.out.println(accepted + " " + word); } } }
72327_2
package org.snpeff.interval; import java.io.Serializable; /** * A genomic interval. * <p> * Note: Intervals are assumed to be zero-based and "closed" * i.e. an interval includes the first and the last base. * e.g.: an interval including the first base, up to base (and including) X would be [0,X] * * @author pcingola */ public class Interval implements Comparable<Interval>, Serializable, Cloneable { private static final long serialVersionUID = -3547434510230920403L; protected int start, end; // This is a closed interval, protected boolean strandMinus; protected String id = ""; // Interval's ID (e.g. gene name, transcript ID) protected String chromosomeNameOri; // Original chromosome name (e.g. literal form a file) protected Interval parent; protected Interval() { start = -1; end = -1; id = null; strandMinus = false; parent = null; } public Interval(Interval parent, int start, int end, boolean strandMinus, String id) { this.start = start; this.end = end; this.id = id; this.strandMinus = strandMinus; this.parent = parent; } @Override public Interval clone() { try { return (Interval) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } /** * Compare by start and end */ @Override public int compareTo(Interval i2) { // Start if (start > i2.start) return 1; if (start < i2.start) return -1; // End if (end > i2.end) return 1; if (end < i2.end) return -1; return 0; } public boolean equals(Interval interval) { return compareTo(interval) == 0; } /** * Go up (parent) until we find an instance of 'clazz' */ @SuppressWarnings("rawtypes") public Interval findParent(Class clazz) { if (this.getClass().equals(clazz)) return this; if ((parent != null) && (parent instanceof Marker)) return parent.findParent(clazz); return null; } public Chromosome getChromosome() { return (Chromosome) findParent(Chromosome.class); } /** * Find chromosome name */ public String getChromosomeName() { Chromosome chromo = getChromosome(); if (chromo != null) return chromo.getId(); return ""; } public String getChromosomeNameOri() { return chromosomeNameOri; } public void setChromosomeNameOri(String chromosomeNameOri) { this.chromosomeNameOri = chromosomeNameOri; } /** * Find chromosome and return it's number * * @return Chromosome number if found, -1 otherwise */ public double getChromosomeNum() { Chromosome chromo = (Chromosome) findParent(Chromosome.class); if (chromo != null) return chromo.chromosomeNum; return -1; } public int getEnd() { return end; } public void setEnd(int end) { if (end < start) throw new RuntimeException("Trying to set end before start:\n\tstart: " + start + "\n\tend : " + end + "\n\t" + this); this.end = end; } /** * Find genome */ public Genome getGenome() { return (Genome) findParent(Genome.class); } /** * Find genome name */ public String getGenomeName() { Genome genome = (Genome) findParent(Genome.class); if (genome != null) return genome.getId(); return ""; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Interval getParent() { return parent; } public void setParent(Interval parent) { this.parent = parent; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public String getStrand() { return strandMinus ? "-" : "+"; } @Override public int hashCode() { int hashCode = getChromosomeName().hashCode(); hashCode = hashCode * 31 + start; hashCode = hashCode * 31 + end; hashCode = hashCode * 31 + (strandMinus ? -1 : 1); if (id != null) hashCode = hashCode * 31 + id.hashCode(); return hashCode; } /** * Return true if this intersects '[iStart, iEnd]' */ public boolean intersects(int iStart, int iEnd) { return (iEnd >= start) && (iStart <= end); } /** * Return true if this intersects 'interval' */ public boolean intersects(Interval interval) { return (interval.getEnd() >= start) && (interval.getStart() <= end); } /** * @return true if this interval contains point (inclusive) */ public boolean intersects(long point) { return (start <= point) && (point <= end); } /** * Do the intervals intersect? * * @return return true if this intersects 'interval' */ public boolean intersects(Marker interval) { if (!interval.getChromosomeName().equals(getChromosomeName())) return false; return (interval.getEnd() >= start) && (interval.getStart() <= end); } /** * How much do intervals intersect? * * @return number of bases these intervals intersect */ public int intersectSize(Marker interval) { if (!interval.getChromosomeName().equals(getChromosomeName())) return 0; int start = Math.max(this.start, interval.getStart()); int end = Math.min(this.end, interval.getEnd()); if (end < start) return 0; return (end - start) + 1; } /** * Is this interval part of a circular chromosome and it spans * the 'chromosome zero / chromosome end' line? */ public boolean isCircular() { Chromosome chr = getChromosome(); return start < 0 // Negative coordinates? || (start > end) // Start before end? || (end > chr.getEnd()) // Ends after chromosome end? ; } public boolean isSameChromo(Marker interval) { return interval.getChromosomeName().equals(getChromosomeName()); } public boolean isStrandMinus() { return strandMinus; } public void setStrandMinus(boolean strand) { strandMinus = strand; } public boolean isStrandPlus() { return !strandMinus; } public boolean isValid() { return start <= end; } public void shiftCoordinates(int shift) { start += shift; end += shift; } public int size() { return end - start + 1; } /** * To string as a simple "chr:start-end" format */ public String toStr() { return getClass().getSimpleName() // + "_" + getChromosomeName() // + ":" + (start + 1) // + "-" + (end + 1) // ; } @Override public String toString() { return start + "-" + end // + ((id != null) && (id.length() > 0) ? " '" + id + "'" : ""); } /** * Show it as an ASCII art */ public String toStringAsciiArt(int maxLen) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < maxLen; i++) { if ((i >= start) && (i <= end)) sb.append('-'); else sb.append(' '); } return sb.toString(); } /** * To string as a simple "chr:start-end" format */ public String toStrPos() { return getChromosomeName() + ":" + (start + 1) + "-" + (end + 1); } }
pcingola/SnpEff
src/main/java/org/snpeff/interval/Interval.java
2,317
// Interval's ID (e.g. gene name, transcript ID)
line_comment
nl
package org.snpeff.interval; import java.io.Serializable; /** * A genomic interval. * <p> * Note: Intervals are assumed to be zero-based and "closed" * i.e. an interval includes the first and the last base. * e.g.: an interval including the first base, up to base (and including) X would be [0,X] * * @author pcingola */ public class Interval implements Comparable<Interval>, Serializable, Cloneable { private static final long serialVersionUID = -3547434510230920403L; protected int start, end; // This is a closed interval, protected boolean strandMinus; protected String id = ""; // Interval's ID<SUF> protected String chromosomeNameOri; // Original chromosome name (e.g. literal form a file) protected Interval parent; protected Interval() { start = -1; end = -1; id = null; strandMinus = false; parent = null; } public Interval(Interval parent, int start, int end, boolean strandMinus, String id) { this.start = start; this.end = end; this.id = id; this.strandMinus = strandMinus; this.parent = parent; } @Override public Interval clone() { try { return (Interval) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } /** * Compare by start and end */ @Override public int compareTo(Interval i2) { // Start if (start > i2.start) return 1; if (start < i2.start) return -1; // End if (end > i2.end) return 1; if (end < i2.end) return -1; return 0; } public boolean equals(Interval interval) { return compareTo(interval) == 0; } /** * Go up (parent) until we find an instance of 'clazz' */ @SuppressWarnings("rawtypes") public Interval findParent(Class clazz) { if (this.getClass().equals(clazz)) return this; if ((parent != null) && (parent instanceof Marker)) return parent.findParent(clazz); return null; } public Chromosome getChromosome() { return (Chromosome) findParent(Chromosome.class); } /** * Find chromosome name */ public String getChromosomeName() { Chromosome chromo = getChromosome(); if (chromo != null) return chromo.getId(); return ""; } public String getChromosomeNameOri() { return chromosomeNameOri; } public void setChromosomeNameOri(String chromosomeNameOri) { this.chromosomeNameOri = chromosomeNameOri; } /** * Find chromosome and return it's number * * @return Chromosome number if found, -1 otherwise */ public double getChromosomeNum() { Chromosome chromo = (Chromosome) findParent(Chromosome.class); if (chromo != null) return chromo.chromosomeNum; return -1; } public int getEnd() { return end; } public void setEnd(int end) { if (end < start) throw new RuntimeException("Trying to set end before start:\n\tstart: " + start + "\n\tend : " + end + "\n\t" + this); this.end = end; } /** * Find genome */ public Genome getGenome() { return (Genome) findParent(Genome.class); } /** * Find genome name */ public String getGenomeName() { Genome genome = (Genome) findParent(Genome.class); if (genome != null) return genome.getId(); return ""; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Interval getParent() { return parent; } public void setParent(Interval parent) { this.parent = parent; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public String getStrand() { return strandMinus ? "-" : "+"; } @Override public int hashCode() { int hashCode = getChromosomeName().hashCode(); hashCode = hashCode * 31 + start; hashCode = hashCode * 31 + end; hashCode = hashCode * 31 + (strandMinus ? -1 : 1); if (id != null) hashCode = hashCode * 31 + id.hashCode(); return hashCode; } /** * Return true if this intersects '[iStart, iEnd]' */ public boolean intersects(int iStart, int iEnd) { return (iEnd >= start) && (iStart <= end); } /** * Return true if this intersects 'interval' */ public boolean intersects(Interval interval) { return (interval.getEnd() >= start) && (interval.getStart() <= end); } /** * @return true if this interval contains point (inclusive) */ public boolean intersects(long point) { return (start <= point) && (point <= end); } /** * Do the intervals intersect? * * @return return true if this intersects 'interval' */ public boolean intersects(Marker interval) { if (!interval.getChromosomeName().equals(getChromosomeName())) return false; return (interval.getEnd() >= start) && (interval.getStart() <= end); } /** * How much do intervals intersect? * * @return number of bases these intervals intersect */ public int intersectSize(Marker interval) { if (!interval.getChromosomeName().equals(getChromosomeName())) return 0; int start = Math.max(this.start, interval.getStart()); int end = Math.min(this.end, interval.getEnd()); if (end < start) return 0; return (end - start) + 1; } /** * Is this interval part of a circular chromosome and it spans * the 'chromosome zero / chromosome end' line? */ public boolean isCircular() { Chromosome chr = getChromosome(); return start < 0 // Negative coordinates? || (start > end) // Start before end? || (end > chr.getEnd()) // Ends after chromosome end? ; } public boolean isSameChromo(Marker interval) { return interval.getChromosomeName().equals(getChromosomeName()); } public boolean isStrandMinus() { return strandMinus; } public void setStrandMinus(boolean strand) { strandMinus = strand; } public boolean isStrandPlus() { return !strandMinus; } public boolean isValid() { return start <= end; } public void shiftCoordinates(int shift) { start += shift; end += shift; } public int size() { return end - start + 1; } /** * To string as a simple "chr:start-end" format */ public String toStr() { return getClass().getSimpleName() // + "_" + getChromosomeName() // + ":" + (start + 1) // + "-" + (end + 1) // ; } @Override public String toString() { return start + "-" + end // + ((id != null) && (id.length() > 0) ? " '" + id + "'" : ""); } /** * Show it as an ASCII art */ public String toStringAsciiArt(int maxLen) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < maxLen; i++) { if ((i >= start) && (i <= end)) sb.append('-'); else sb.append(' '); } return sb.toString(); } /** * To string as a simple "chr:start-end" format */ public String toStrPos() { return getChromosomeName() + ":" + (start + 1) + "-" + (end + 1); } }
154506_2
// Screen.java // Represents the screen of the ATM public class Screen { // displays a message without a carriage return public void displayMessage(String message) { System.out.print(message); } // end method displayMessage // display a message with a carriage return public void displayMessageLine(String message) { System.out.println(message); } // end method displayMessageLine // display a dollar amount public void displayDollarAmount(double amount) { System.out.printf("$%,.2f", amount); } // end method displayDollarAmount } // end class Screen /************************************************************************** * (C) Copyright 1992-2014 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
pdeitel/JavaHowToProgram10eEarlyObjectsVersion
examples/ch34/Screen.java
419
// end method displayMessage
line_comment
nl
// Screen.java // Represents the screen of the ATM public class Screen { // displays a message without a carriage return public void displayMessage(String message) { System.out.print(message); } // end method<SUF> // display a message with a carriage return public void displayMessageLine(String message) { System.out.println(message); } // end method displayMessageLine // display a dollar amount public void displayDollarAmount(double amount) { System.out.printf("$%,.2f", amount); } // end method displayDollarAmount } // end class Screen /************************************************************************** * (C) Copyright 1992-2014 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
190870_5
/* Copyright 2018 Nationale-Nederlanden 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 nl.nn.ibistesttool; import nl.nn.adapterframework.util.AppConstants; import nl.nn.testtool.TestTool; import nl.nn.testtool.filter.View; import nl.nn.testtool.filter.Views; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.helpers.OptionConverter; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.BeanPostProcessor; /** * @author Jaco de Groot */ public class DeploymentSpecificsBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof TestTool) { TestTool testTool = (TestTool)bean; boolean testToolEnabled=true; AppConstants appConstants = AppConstants.getInstance(); String testToolEnabledProperty=appConstants.getProperty("testtool.enabled"); if (StringUtils.isNotEmpty(testToolEnabledProperty)) { testToolEnabled="true".equalsIgnoreCase(testToolEnabledProperty); } else { String stage = System.getProperty("otap.stage"); if ("ACC".equals(stage) || "PRD".equals(stage)) { testToolEnabled=false; } appConstants.setProperty("testtool.enabled", testToolEnabled); } // enable/disable testtool via two switches, until one of the switches has become deprecated testTool.setReportGeneratorEnabled(testToolEnabled); IbisDebuggerAdvice.setEnabled(testToolEnabled); } if (bean instanceof nl.nn.testtool.storage.file.Storage) { // TODO appConstants via set methode door spring i.p.v. AppConstants.getInstance()? AppConstants appConstants = AppConstants.getInstance(); String maxFileSize = appConstants.getResolvedProperty("ibistesttool.maxFileSize"); if (maxFileSize != null) { nl.nn.testtool.storage.file.Storage loggingStorage = (nl.nn.testtool.storage.file.Storage)bean; long maximumFileSize = OptionConverter.toFileSize(maxFileSize, nl.nn.testtool.storage.file.Storage.DEFAULT_MAXIMUM_FILE_SIZE); loggingStorage.setMaximumFileSize(maximumFileSize); } String maxBackupIndex = appConstants.getResolvedProperty("ibistesttool.maxBackupIndex"); if (maxBackupIndex != null) { nl.nn.testtool.storage.file.Storage loggingStorage = (nl.nn.testtool.storage.file.Storage)bean; int maximumBackupIndex = Integer.parseInt(maxBackupIndex); loggingStorage.setMaximumBackupIndex(maximumBackupIndex); } } // if (bean instanceof nl.nn.testtool.storage.diff.Storage) { // // TODO niet otap.stage maar een specifieke prop. gebruiken? op andere plekken in deze class ook? // String stage = System.getResolvedProperty("otap.stage"); // if ("LOC".equals(stage)) { // AppConstants appConstants = AppConstants.getInstance(); // nl.nn.testtool.storage.diff.Storage runStorage = (nl.nn.testtool.storage.diff.Storage)bean; // runStorage.setReportsFilename(appConstants.getResolvedProperty("rootRealPath") + "../TestTool/reports.xml"); //werkt hier ook niet, deze ?singleton? bean wordt ook al aangemaakt voor tt servlet // System.out.println("xxxxxxxxxx" + appConstants.getResolvedProperty("rootRealPath") + "../TestTool/reports.xml");//TODO remove // } // } if (bean instanceof Views) { AppConstants appConstants = AppConstants.getInstance(); String defaultView = appConstants.getResolvedProperty("ibistesttool.defaultView"); if (defaultView != null) { Views views = (Views)bean; View view = views.setDefaultView(defaultView); if (view == null) { throw new BeanCreationException("Default view '" + defaultView + "' not found"); } } } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }
pedro-tavares/iaf
ladybug/src/main/java/nl/nn/ibistesttool/DeploymentSpecificsBeanPostProcessor.java
1,305
// // TODO niet otap.stage maar een specifieke prop. gebruiken? op andere plekken in deze class ook?
line_comment
nl
/* Copyright 2018 Nationale-Nederlanden 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 nl.nn.ibistesttool; import nl.nn.adapterframework.util.AppConstants; import nl.nn.testtool.TestTool; import nl.nn.testtool.filter.View; import nl.nn.testtool.filter.Views; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.helpers.OptionConverter; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.BeanPostProcessor; /** * @author Jaco de Groot */ public class DeploymentSpecificsBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof TestTool) { TestTool testTool = (TestTool)bean; boolean testToolEnabled=true; AppConstants appConstants = AppConstants.getInstance(); String testToolEnabledProperty=appConstants.getProperty("testtool.enabled"); if (StringUtils.isNotEmpty(testToolEnabledProperty)) { testToolEnabled="true".equalsIgnoreCase(testToolEnabledProperty); } else { String stage = System.getProperty("otap.stage"); if ("ACC".equals(stage) || "PRD".equals(stage)) { testToolEnabled=false; } appConstants.setProperty("testtool.enabled", testToolEnabled); } // enable/disable testtool via two switches, until one of the switches has become deprecated testTool.setReportGeneratorEnabled(testToolEnabled); IbisDebuggerAdvice.setEnabled(testToolEnabled); } if (bean instanceof nl.nn.testtool.storage.file.Storage) { // TODO appConstants via set methode door spring i.p.v. AppConstants.getInstance()? AppConstants appConstants = AppConstants.getInstance(); String maxFileSize = appConstants.getResolvedProperty("ibistesttool.maxFileSize"); if (maxFileSize != null) { nl.nn.testtool.storage.file.Storage loggingStorage = (nl.nn.testtool.storage.file.Storage)bean; long maximumFileSize = OptionConverter.toFileSize(maxFileSize, nl.nn.testtool.storage.file.Storage.DEFAULT_MAXIMUM_FILE_SIZE); loggingStorage.setMaximumFileSize(maximumFileSize); } String maxBackupIndex = appConstants.getResolvedProperty("ibistesttool.maxBackupIndex"); if (maxBackupIndex != null) { nl.nn.testtool.storage.file.Storage loggingStorage = (nl.nn.testtool.storage.file.Storage)bean; int maximumBackupIndex = Integer.parseInt(maxBackupIndex); loggingStorage.setMaximumBackupIndex(maximumBackupIndex); } } // if (bean instanceof nl.nn.testtool.storage.diff.Storage) { // // TODO niet<SUF> // String stage = System.getResolvedProperty("otap.stage"); // if ("LOC".equals(stage)) { // AppConstants appConstants = AppConstants.getInstance(); // nl.nn.testtool.storage.diff.Storage runStorage = (nl.nn.testtool.storage.diff.Storage)bean; // runStorage.setReportsFilename(appConstants.getResolvedProperty("rootRealPath") + "../TestTool/reports.xml"); //werkt hier ook niet, deze ?singleton? bean wordt ook al aangemaakt voor tt servlet // System.out.println("xxxxxxxxxx" + appConstants.getResolvedProperty("rootRealPath") + "../TestTool/reports.xml");//TODO remove // } // } if (bean instanceof Views) { AppConstants appConstants = AppConstants.getInstance(); String defaultView = appConstants.getResolvedProperty("ibistesttool.defaultView"); if (defaultView != null) { Views views = (Views)bean; View view = views.setDefaultView(defaultView); if (view == null) { throw new BeanCreationException("Default view '" + defaultView + "' not found"); } } } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } }
187199_65
package com.itwillbs.mvc_board.controller; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.itwillbs.mvc_board.service.BankService; import com.itwillbs.mvc_board.service.MemberService; import com.itwillbs.mvc_board.service.SendMailService; import com.itwillbs.mvc_board.vo.MailAuthInfoVO; import com.itwillbs.mvc_board.vo.MemberVO; import com.itwillbs.mvc_board.vo.ResponseTokenVO; @Controller public class MemberController { // MemberService 객체 자동 주입 @Autowired private MemberService memberService; // SendMailService 객체 자동 주입 @Autowired private SendMailService mailService; @Autowired private BankService bankService; // [ 회원 가입 ] // "MemberJoinForm" 요청 joinForm() 메서드 정의(GET) // => "member/member_join_form.jsp" 페이지 포워딩 @GetMapping("MemberJoinForm") public String joinForm() { return "member/member_join_form"; } // "MemberJoinPro" 요청에 대한 비즈니스 로직 처리 수행할 joinPro() 메서드 정의(POST) // => 폼 파라미터를 통해 전달받은 회원정보를 MemberVO 타입으로 전달받기 // => 데이터 공유 객체 Model 타입 파라미터 추가 @PostMapping("MemberJoinPro") public String joinPro(MemberVO member, Model model) { // System.out.println(member); // ------------------------------------------------------------------------ // BCryptPasswordEncoder 를 활용한 패스워드 암호화 // 입력받은 패스워드는 암호화 필요 => 복호화가 불가능하도록 단방향 암호화(해싱) 수행 // => 평문(Clear Text, Plain Text) 을 해싱 후 MemberVO 객체의 passwd 에 덮어쓰기 // => org.springframework.security.crypto.bcrypt 패키지의 BCryptPasswordEncoder 클래스 활용 // (spring-security-crypto 또는 spring-security-web 라이브러리 추가) // 주의! JDK 11 일 때 5.x.x 버전 필요 // => BCryptPasswordEncoder 활용한 해싱은 솔팅(Salting) 기법을 통해 // 동일한 평문(원본 암호)이더라도 매번 다른 결과(암호문)를 얻을 수 있다! // 1. BCryptPasswordEncoder 클래스 인스턴스 생성 BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // 2. BCryptPasswordEncoder 객체의 encode() 메서드를 호출하여 // 원문(평문) 패스워드에 대한 해싱(= 암호화) 수행 후 결과값 저장 // => 파라미터 : MemberVO 객체의 패스워드(평문 암호) 리턴타입 : String(암호문) String securePasswd = passwordEncoder.encode(member.getPasswd()); // System.out.println("평문 패스워드 : " + member.getPasswd()); // 1234 // System.out.println("암호화 된 패스워드 : " + securePasswd); // $2a$10$wvO.wV.ZHbRFVr9q4ayFbeGGCRs7XKxsN8wmll/.5YFlA/N7hFYl2(매번 다름) // 3. 암호화 된 패스워드를 MemberVO 객체에 저장 member.setPasswd(securePasswd); // ------------------------------------------------------------------------------------- // MemberService - registMember() 메서드 호출하여 회원가입 작업 요청 // => 파라미터 : MemberVO 객체 리턴타입 : int(insertCount) int insertCount = memberService.registMember(member); // 회원가입 성공/실패에 따른 페이징 처리 // => 성공 시 "MemberJoinSuccess" 서블릿 주소 리다이렉트 // => 실패 시 "fail_back.jsp" 페이지 포워딩("msg" 속성값으로 "회원 가입 실패!" 저장) if(insertCount > 0) { // 12-29 추가내용 // -------- 인증메일 발송 작업 추가 -------- // SendMailService - sendAuthMail() 메서드 호출하여 인증 메일 발송 요청 // => 파라미터 : 아이디, 이메일(= 회원 가입 시 입력한 정보) // 리턴타입 : String(auth_code = 인증코드) member.setEmail(member.getEmail1() + "@" + member.getEmail2()); // 이메일 결합 String auth_code = mailService.sendAuthMail(member); // System.out.println("인증코드 : " + auth_code); // MemberService - registAuthInfo() 메서드 호출하여 인증 정보 등록 요청 // => 파라미터 : 아이디, 인증코드 memberService.registMailAuthInfo(member.getId(), auth_code); return "redirect:/MemberJoinSuccess"; } else { // 실패 시 메세지 출력 및 이전페이지로 돌아가는 기능을 모듈화 한 fail_back.jsp 페이지 model.addAttribute("msg", "회원 가입 실패!"); return "fail_back"; } } // "MemberCheckDupId" 요청에 대한 아이디 중복 검사 비즈니스 로직 처리 // 응답데이터를 디스패치 또는 리다이렉트 용도가 아닌 응답 데이터 body 로 그대로 활용하려면 // @ResponseBody 어노테이션을 적용해야한다! => 응답 데이터를 직접 전송하도록 지정한다. // => 이 어노테이션은 AJAX 와 상관없이 적용 가능하지만 AJAX 일 때는 대부분 사용한다. @ResponseBody @GetMapping("MemberCheckDupId") public String checkDupId(MemberVO member) { System.out.println(member.getId()); // MemberService - getMember() 메서드 호출하여 아이디 조회(기존 메서드 재사용) // (MemberService - getMemberId() 메서드 호출하여 아이디 조회 메서드 정의 가능) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 조회 결과 판별 // => MemberVO 객체가 존재할 경우 아이디 중복, 아니면 사용 가능한 아이디 if(dbMember == null) { // 사용 가능한 아이디 return "false"; // 중복이 아니라는 의미로 "false" 값 전달 } else { // 아이디 중복 return "true"; // 중복이라는 의미로 "true" 값 전달 } } // -------------------------------------- // 인증 메일 발송 테스트를 위한 서블릿 매핑 // => URL 을 통해 강제로 회원 아이디와 수신자 이메일 주소 전달받아 사용 @GetMapping("TestAuthMail") public String testAuthMail(MemberVO member) { String auth_code = mailService.sendAuthMail(member); // System.out.println("인증코드 : " + auth_code); // MemberService - registAuthInfo() 메서드 호출하여 인증 정보 등록 요청 // => 파라미터 : 아이디, 인증코드 memberService.registMailAuthInfo(member.getId(), auth_code); // return "member/member_join_success"; return "redirect:/MemberJoinSuccess"; } // ----------------- // "MemberEmailAuth" 서블릿 요청에 대한 메일 인증 작업 비즈니스 로직 처리 @GetMapping("MemberEmailAuth") public String emailAuth(MailAuthInfoVO authInfo, Model model) { System.out.println("인증정보 : " + authInfo); // MemberService - requestEmailAuth() 메서드 호출하여 인증 요청 // => 파라미터 : MailAuthInfoVO 객체 리턴타입 : boolean(isAuthSuccess) boolean isAuthSuccess = memberService.requestEmailAuth(authInfo); // 인증 요청 결과 판별 if(isAuthSuccess) { // 성공 model.addAttribute("msg", "인증 성공! 로그인 페이지로 이동합니다!"); model.addAttribute("targetURL", "MemberLoginForm"); return "forward"; } else { model.addAttribute("msg", "인증 실패!"); return "fail_back"; } } // ================================================================================ // [ 로그인 ] // "MemberJoinSuccess" 요청에 대해 "member/member_join_success" 페이지 포워딩(GET) @GetMapping("MemberJoinSuccess") public String joinSuccess() { // 아이디 : hong, 비번 : 1111 return "member/member_join_success"; } // "MemberLoginForm" 요청에 대해 "member/login_form" 페이지 포워딩(GET) @GetMapping("MemberLoginForm") public String loginForm() { return "member/member_login_form"; } // "MemberLoginPro" 요청에 대한 비즈니스 로직 처리 수행할 loginPro() 메서드 정의(POST) // => 폼 파라미터를 통해 전달받은 회원정보를 MemberVO 타입으로 전달받기 // => 세션 활용을 위해 HttpSession 타입 파라미터 추가 // => 데이터 공유 객체 Model 타입 파라미터 추가 @PostMapping("MemberLoginPro") public String loginPro(MemberVO member, HttpSession session, Model model) { System.out.println(member); // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청 // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // System.out.println(dbMember); // 만약, 회원 상태(member_status)값이 3일 경우 // "fail_back" 포워딩 처리("탈퇴한 회원입니다!") if(dbMember.getMember_status() == 3) { model.addAttribute("msg", "탈퇴한 회원입니다!"); return "fail_back"; } // BCryptPasswordEncoder 객체를 활용한 패스워드 비교 // => 입력받은 패스워드(평문)와 DB 에 저장된 패스워드(암호문)는 직접적인 문자열 비교 불가 // => 일반적인 경우 전달받은 평문과 DB 에 저장된 암호문을 복호화하여 비교하면 되지만 // 단방향 암호화가 된 패스워드의 경우 평문을 암호화(해싱)하여 결과값을 비교해야함 // (단, 솔팅값이 서로 다르므로 직접적인 비교(String 의 equals())가 불가능) // => BCryptPasswordEncoder 객체의 matches() 메서드를 통한 비교 필수! BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // => 단, 아이디가 일치하지 않을 경우(null 값 리턴됨) 또는 패스워드 불일치 시 // fail_back.jsp 페이지 포워딩("로그인 실패!") // null 값을 먼저 비교하지 않으면 NullPointException 발생 if(dbMember == null || !passwordEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { // 로그인 실패 처리 model.addAttribute("msg", "로그인 실패!"); return "fail_back"; } else { // 12-29 추가내용 // 이메일 인증 여부 확인 // => 회원정보조회를 통해 MemberVO 객체에 저장된 // 이메일 인증 정보(mail_auth_status) 값이 "N" 일 경우 이메일 미인증 회원이므로 // "이메일 인증 후 로그인이 가능합니다" 출력 후 이전페이지로 돌아가기 if(dbMember.getMail_auth_status().equals("N")) { model.addAttribute("msg","이메일 인증 후 로그인이 가능합니다"); return "fail_back"; } // 세션 객체에 로그인 성공한 아이디를 "sId" 속성으로 추가 session.setAttribute("sId", member.getId()); // 1-22 추가내용 // -------------------------------------------------------------------- // BankService - getBankUserInfo() 메서드 호출하여 엑세스 토큰 조회 요청 // => 파라미터 : 아이디 리턴타입 : Map<String, String> Map<String, String> token = bankService.getBankUserInfo(member.getId()); // System.out.println(token); // -------------------------------------------------------------------- // 조회된 엑세스 토큰을 "access_token", 사용자 번호를 "user_seq_no" 로 세션에 추가 // => 단, Map객체(token)이 null 이 아닐 경우에만 수행 if(token != null ) { session.setAttribute("access_token", token.get("access_token")); session.setAttribute("user_seq_no", token.get("user_seq_no")); } // 메인페이지로 리다이렉트 return "redirect:/"; } } // "MemberLogout" 요청에 대한 로그아웃 비즈니스 로직 처리 @GetMapping("MemberLogout") public String logout(HttpSession session) { session.invalidate(); return "redirect:/"; } // =============================================================== // [ 회원 상세정보 조회 ] // "MemberInfo" 서블릿 요청 시 회원 상세정보 조회 비즈니스 로직 처리 // 회원 정보 조회 @GetMapping("MemberInfo") public String info(MemberVO member, HttpSession session, Model model) { // 세션 아이디가 없을 경우 "fail_back" 페이지를 통해 "잘못된 접근입니다" 출력 처리 String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 12-19 추가내용 // 관리자 계정일 경우 회원 조회시 해당 회원의 정보가 출력되어야한다. // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) // 파라미터가 없을 경우는 null, 파라미터는 있지만 데이터가 없으면 "" // 두가지 경우를 고려해서 null과 "" 둘 다 판별한다. if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 상세정보 조회 요청 // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 조회 결과 Model 객체에 저장 model.addAttribute("member", dbMember); // 주민번호(MemberVO - jumin는 뒷자리 첫번째 숫자를 제외한 나머지 * 처리(마스킹) // => 처리된 주민번호를 jumin 멤버변수에 저장 // => 주민번호 앞자리 6자리와 뒷자리 1자리까지 추출하여 뒷부분에 * 기호 6개 결합 dbMember.setJumin(dbMember.getJumin().substring(0, 8) + "******"); // 0 ~ 8-1 인덱스까지 추출 // 회원 상세정보 조회 페이지 포워딩 return "member/member_info"; } // =============================================================== // [ 회원 정보 수정 ] // "MemberModifyForm" 서블릿 요청 시 회원 정보 수정 폼 표시 @GetMapping("MemberModifyForm") public String modifyForm(MemberVO member, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 상세정보 조회 요청 // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 주민번호(MemberVO - jumin는 뒷자리 첫번째 숫자를 제외한 나머지 * 처리(마스킹) // => 처리된 주민번호를 jumin 멤버변수에 저장 // => 주민번호 앞자리 6자리와 뒷자리 1자리까지 추출하여 뒷부분에 * 기호 6개 결합 dbMember.setJumin(dbMember.getJumin().substring(0, 8) + "******"); // 0 ~ 8-1 인덱스까지 추출 // 조회 결과 Model 객체에 저장 model.addAttribute("member", dbMember); return "member/member_modify_form"; } // "MemberModifyPro" 서블릿 요청에 대한 회원 정보 수정 비즈니스 로직 처리 // => 추가로 전달되는 새 패스워드(newPasswd) 값을 전달받을 파라미터 변수 1개 추가(Map 사용 가능) @PostMapping("MemberModifyPro") public String modifyPro(MemberVO member, String newPasswd, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청(패스워드 비교용) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // BCryptPasswordEncoder 클래스를 활용하여 입력받은 기존 패스워드와 DB 패스워드 비교 BCryptPasswordEncoder passwoedEncoder = new BCryptPasswordEncoder(); // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { // 이 때, 동일한 조건에서 패스워드 검증도 추가로 수행 // => 관리자가 다른 회원의 정보를 수정할 경우에는 패스워드 검증 수행 생략됨 if(!passwoedEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { model.addAttribute("msg", "수정 권한이 없습니다!"); return "fail_back"; } } // 새 패스워드를 입력받았을 경우 BCryptPasswordEncoder 클래스를 활요하여 암호화 처리 // 파라미터로는 newPasswd 자체는 있기에 입력값이 없을 경우 ""으로 넘어오지만 // 만일의 경우를 대비해서 null값도 비교한다. if(newPasswd != null && !newPasswd.equals("")) { newPasswd = passwoedEncoder.encode(newPasswd); } // MemberService - modifyMember() 메서드 호출하여 회원 정보 수정 요청 // => 파라미터 : MemberVO 객체, 새 패스워드(newPasswd) 리턴타입 : int(updateCount) int updateCount = memberService.modifyMember(member, newPasswd); // 회원 정보 수정 요청 결과 판별 // => 실패 시 "fail_back" 페이지 포워딩 처리("회원정보 수정 실패!") // => 성공 시 "MemberInfo" 서블릿 리다이렉트 if(updateCount > 0) { // 관리자가 다른 회원 정보 수정 시 MemberInfo 서블릿 주소에 아이디 파라미터 결합 if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { // 본인 정보를 조회할 경우 return "redirect:/MemberInfo"; } else { return "redirect:/MemberInfo?id=" + member.getId(); } } else { model.addAttribute("msg", "회원정보 수정 실패!"); return "fail_back"; } } // =============================================================== // [ 회원 탈퇴 ] // "MemberWithdrawForm" 서블릿 요청 시 회원 정보 탈퇴 폼 표시 @GetMapping("MemberWithdrawForm") public String withdrawForm(HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } return "member/member_withdraw_form"; } // "MemberWithdrawPro" 서블릿 요청 시 회원 탈퇴 비즈니스 로직 처리 @PostMapping("MemberWithdrawPro") public String withdrawPro(MemberVO member, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } member.setId(sId); // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청(패스워드 비교용) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // BCryptPasswordEncoder 클래스를 활용하여 입력받은 기존 패스워드와 DB 패스워드 비교 BCryptPasswordEncoder passwoedEncoder = new BCryptPasswordEncoder(); if(!passwoedEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { model.addAttribute("msg", "수정 권한이 없습니다!"); return "fail_back"; } // MemberService - withdrawMember() 메서드 호출하여 회원 탈퇴 처리 요청 // => 파라미터 : MemberVO 객체 리턴타입 : int(updateCount) int updateCount = memberService.withdrawMember(member); // 탈퇴 처리 결과 판별 // => 실패 시 "fail_back" 포워딩 처리("회원 탈퇴 실패!") // => 성공 시 세션 초기화 후 메인페이지 리다이렉트 if(updateCount > 0) { session.invalidate(); return "redirect:/"; } else { model.addAttribute("msg", "회원 탈퇴 실패!"); return "fail_back"; } } // ======================================================================= // [ 관리자 페이지 ] @GetMapping("MemberAdminMain") public String adminMain(HttpSession session, Model model) { // 세션 아이디가 null 이거나 "admin" 이 아닐 경우 String sId = (String)session.getAttribute("sId"); if(sId == null || !sId.equals("admin")) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } return "admin/admin_main"; } // [ 회원 목록 조회 ] @GetMapping("AdminMemberList") public String memberList(HttpSession session, Model model) { // 세션 아이디가 null 이거나 "admin" 이 아닐 경우 String sId = (String)session.getAttribute("sId"); if(sId == null || !sId.equals("admin")) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // MemberService - getMemberList() 메서드 호출하여 회원 목록 조회 요청 // => 파라미터 : 없음 리턴타입 : List<MemberVO>(memberList) List<MemberVO> memberList = memberService.getMemberList(); System.out.println(memberList); // Model 객체에 회원 목록 조회 결과 저장 model.addAttribute("memberList", memberList); // 회원 목록 조회 페이지(admin/member_list.jsp)로 포워딩 return "admin/member_list"; } }
penguKim/Spring_study
Spring_MVC_Board/src/main/java/com/itwillbs/mvc_board/controller/MemberController.java
7,303
// MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청
line_comment
nl
package com.itwillbs.mvc_board.controller; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.itwillbs.mvc_board.service.BankService; import com.itwillbs.mvc_board.service.MemberService; import com.itwillbs.mvc_board.service.SendMailService; import com.itwillbs.mvc_board.vo.MailAuthInfoVO; import com.itwillbs.mvc_board.vo.MemberVO; import com.itwillbs.mvc_board.vo.ResponseTokenVO; @Controller public class MemberController { // MemberService 객체 자동 주입 @Autowired private MemberService memberService; // SendMailService 객체 자동 주입 @Autowired private SendMailService mailService; @Autowired private BankService bankService; // [ 회원 가입 ] // "MemberJoinForm" 요청 joinForm() 메서드 정의(GET) // => "member/member_join_form.jsp" 페이지 포워딩 @GetMapping("MemberJoinForm") public String joinForm() { return "member/member_join_form"; } // "MemberJoinPro" 요청에 대한 비즈니스 로직 처리 수행할 joinPro() 메서드 정의(POST) // => 폼 파라미터를 통해 전달받은 회원정보를 MemberVO 타입으로 전달받기 // => 데이터 공유 객체 Model 타입 파라미터 추가 @PostMapping("MemberJoinPro") public String joinPro(MemberVO member, Model model) { // System.out.println(member); // ------------------------------------------------------------------------ // BCryptPasswordEncoder 를 활용한 패스워드 암호화 // 입력받은 패스워드는 암호화 필요 => 복호화가 불가능하도록 단방향 암호화(해싱) 수행 // => 평문(Clear Text, Plain Text) 을 해싱 후 MemberVO 객체의 passwd 에 덮어쓰기 // => org.springframework.security.crypto.bcrypt 패키지의 BCryptPasswordEncoder 클래스 활용 // (spring-security-crypto 또는 spring-security-web 라이브러리 추가) // 주의! JDK 11 일 때 5.x.x 버전 필요 // => BCryptPasswordEncoder 활용한 해싱은 솔팅(Salting) 기법을 통해 // 동일한 평문(원본 암호)이더라도 매번 다른 결과(암호문)를 얻을 수 있다! // 1. BCryptPasswordEncoder 클래스 인스턴스 생성 BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // 2. BCryptPasswordEncoder 객체의 encode() 메서드를 호출하여 // 원문(평문) 패스워드에 대한 해싱(= 암호화) 수행 후 결과값 저장 // => 파라미터 : MemberVO 객체의 패스워드(평문 암호) 리턴타입 : String(암호문) String securePasswd = passwordEncoder.encode(member.getPasswd()); // System.out.println("평문 패스워드 : " + member.getPasswd()); // 1234 // System.out.println("암호화 된 패스워드 : " + securePasswd); // $2a$10$wvO.wV.ZHbRFVr9q4ayFbeGGCRs7XKxsN8wmll/.5YFlA/N7hFYl2(매번 다름) // 3. 암호화 된 패스워드를 MemberVO 객체에 저장 member.setPasswd(securePasswd); // ------------------------------------------------------------------------------------- // MemberService - registMember() 메서드 호출하여 회원가입 작업 요청 // => 파라미터 : MemberVO 객체 리턴타입 : int(insertCount) int insertCount = memberService.registMember(member); // 회원가입 성공/실패에 따른 페이징 처리 // => 성공 시 "MemberJoinSuccess" 서블릿 주소 리다이렉트 // => 실패 시 "fail_back.jsp" 페이지 포워딩("msg" 속성값으로 "회원 가입 실패!" 저장) if(insertCount > 0) { // 12-29 추가내용 // -------- 인증메일 발송 작업 추가 -------- // SendMailService - sendAuthMail() 메서드 호출하여 인증 메일 발송 요청 // => 파라미터 : 아이디, 이메일(= 회원 가입 시 입력한 정보) // 리턴타입 : String(auth_code = 인증코드) member.setEmail(member.getEmail1() + "@" + member.getEmail2()); // 이메일 결합 String auth_code = mailService.sendAuthMail(member); // System.out.println("인증코드 : " + auth_code); // MemberService - registAuthInfo() 메서드 호출하여 인증 정보 등록 요청 // => 파라미터 : 아이디, 인증코드 memberService.registMailAuthInfo(member.getId(), auth_code); return "redirect:/MemberJoinSuccess"; } else { // 실패 시 메세지 출력 및 이전페이지로 돌아가는 기능을 모듈화 한 fail_back.jsp 페이지 model.addAttribute("msg", "회원 가입 실패!"); return "fail_back"; } } // "MemberCheckDupId" 요청에 대한 아이디 중복 검사 비즈니스 로직 처리 // 응답데이터를 디스패치 또는 리다이렉트 용도가 아닌 응답 데이터 body 로 그대로 활용하려면 // @ResponseBody 어노테이션을 적용해야한다! => 응답 데이터를 직접 전송하도록 지정한다. // => 이 어노테이션은 AJAX 와 상관없이 적용 가능하지만 AJAX 일 때는 대부분 사용한다. @ResponseBody @GetMapping("MemberCheckDupId") public String checkDupId(MemberVO member) { System.out.println(member.getId()); // MemberService - getMember() 메서드 호출하여 아이디 조회(기존 메서드 재사용) // (MemberService - getMemberId() 메서드 호출하여 아이디 조회 메서드 정의 가능) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 조회 결과 판별 // => MemberVO 객체가 존재할 경우 아이디 중복, 아니면 사용 가능한 아이디 if(dbMember == null) { // 사용 가능한 아이디 return "false"; // 중복이 아니라는 의미로 "false" 값 전달 } else { // 아이디 중복 return "true"; // 중복이라는 의미로 "true" 값 전달 } } // -------------------------------------- // 인증 메일 발송 테스트를 위한 서블릿 매핑 // => URL 을 통해 강제로 회원 아이디와 수신자 이메일 주소 전달받아 사용 @GetMapping("TestAuthMail") public String testAuthMail(MemberVO member) { String auth_code = mailService.sendAuthMail(member); // System.out.println("인증코드 : " + auth_code); // MemberService - registAuthInfo() 메서드 호출하여 인증 정보 등록 요청 // => 파라미터 : 아이디, 인증코드 memberService.registMailAuthInfo(member.getId(), auth_code); // return "member/member_join_success"; return "redirect:/MemberJoinSuccess"; } // ----------------- // "MemberEmailAuth" 서블릿 요청에 대한 메일 인증 작업 비즈니스 로직 처리 @GetMapping("MemberEmailAuth") public String emailAuth(MailAuthInfoVO authInfo, Model model) { System.out.println("인증정보 : " + authInfo); // MemberService - requestEmailAuth() 메서드 호출하여 인증 요청 // => 파라미터 : MailAuthInfoVO 객체 리턴타입 : boolean(isAuthSuccess) boolean isAuthSuccess = memberService.requestEmailAuth(authInfo); // 인증 요청 결과 판별 if(isAuthSuccess) { // 성공 model.addAttribute("msg", "인증 성공! 로그인 페이지로 이동합니다!"); model.addAttribute("targetURL", "MemberLoginForm"); return "forward"; } else { model.addAttribute("msg", "인증 실패!"); return "fail_back"; } } // ================================================================================ // [ 로그인 ] // "MemberJoinSuccess" 요청에 대해 "member/member_join_success" 페이지 포워딩(GET) @GetMapping("MemberJoinSuccess") public String joinSuccess() { // 아이디 : hong, 비번 : 1111 return "member/member_join_success"; } // "MemberLoginForm" 요청에 대해 "member/login_form" 페이지 포워딩(GET) @GetMapping("MemberLoginForm") public String loginForm() { return "member/member_login_form"; } // "MemberLoginPro" 요청에 대한 비즈니스 로직 처리 수행할 loginPro() 메서드 정의(POST) // => 폼 파라미터를 통해 전달받은 회원정보를 MemberVO 타입으로 전달받기 // => 세션 활용을 위해 HttpSession 타입 파라미터 추가 // => 데이터 공유 객체 Model 타입 파라미터 추가 @PostMapping("MemberLoginPro") public String loginPro(MemberVO member, HttpSession session, Model model) { System.out.println(member); // MemberService -<SUF> // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // System.out.println(dbMember); // 만약, 회원 상태(member_status)값이 3일 경우 // "fail_back" 포워딩 처리("탈퇴한 회원입니다!") if(dbMember.getMember_status() == 3) { model.addAttribute("msg", "탈퇴한 회원입니다!"); return "fail_back"; } // BCryptPasswordEncoder 객체를 활용한 패스워드 비교 // => 입력받은 패스워드(평문)와 DB 에 저장된 패스워드(암호문)는 직접적인 문자열 비교 불가 // => 일반적인 경우 전달받은 평문과 DB 에 저장된 암호문을 복호화하여 비교하면 되지만 // 단방향 암호화가 된 패스워드의 경우 평문을 암호화(해싱)하여 결과값을 비교해야함 // (단, 솔팅값이 서로 다르므로 직접적인 비교(String 의 equals())가 불가능) // => BCryptPasswordEncoder 객체의 matches() 메서드를 통한 비교 필수! BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // => 단, 아이디가 일치하지 않을 경우(null 값 리턴됨) 또는 패스워드 불일치 시 // fail_back.jsp 페이지 포워딩("로그인 실패!") // null 값을 먼저 비교하지 않으면 NullPointException 발생 if(dbMember == null || !passwordEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { // 로그인 실패 처리 model.addAttribute("msg", "로그인 실패!"); return "fail_back"; } else { // 12-29 추가내용 // 이메일 인증 여부 확인 // => 회원정보조회를 통해 MemberVO 객체에 저장된 // 이메일 인증 정보(mail_auth_status) 값이 "N" 일 경우 이메일 미인증 회원이므로 // "이메일 인증 후 로그인이 가능합니다" 출력 후 이전페이지로 돌아가기 if(dbMember.getMail_auth_status().equals("N")) { model.addAttribute("msg","이메일 인증 후 로그인이 가능합니다"); return "fail_back"; } // 세션 객체에 로그인 성공한 아이디를 "sId" 속성으로 추가 session.setAttribute("sId", member.getId()); // 1-22 추가내용 // -------------------------------------------------------------------- // BankService - getBankUserInfo() 메서드 호출하여 엑세스 토큰 조회 요청 // => 파라미터 : 아이디 리턴타입 : Map<String, String> Map<String, String> token = bankService.getBankUserInfo(member.getId()); // System.out.println(token); // -------------------------------------------------------------------- // 조회된 엑세스 토큰을 "access_token", 사용자 번호를 "user_seq_no" 로 세션에 추가 // => 단, Map객체(token)이 null 이 아닐 경우에만 수행 if(token != null ) { session.setAttribute("access_token", token.get("access_token")); session.setAttribute("user_seq_no", token.get("user_seq_no")); } // 메인페이지로 리다이렉트 return "redirect:/"; } } // "MemberLogout" 요청에 대한 로그아웃 비즈니스 로직 처리 @GetMapping("MemberLogout") public String logout(HttpSession session) { session.invalidate(); return "redirect:/"; } // =============================================================== // [ 회원 상세정보 조회 ] // "MemberInfo" 서블릿 요청 시 회원 상세정보 조회 비즈니스 로직 처리 // 회원 정보 조회 @GetMapping("MemberInfo") public String info(MemberVO member, HttpSession session, Model model) { // 세션 아이디가 없을 경우 "fail_back" 페이지를 통해 "잘못된 접근입니다" 출력 처리 String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 12-19 추가내용 // 관리자 계정일 경우 회원 조회시 해당 회원의 정보가 출력되어야한다. // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) // 파라미터가 없을 경우는 null, 파라미터는 있지만 데이터가 없으면 "" // 두가지 경우를 고려해서 null과 "" 둘 다 판별한다. if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 상세정보 조회 요청 // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 조회 결과 Model 객체에 저장 model.addAttribute("member", dbMember); // 주민번호(MemberVO - jumin는 뒷자리 첫번째 숫자를 제외한 나머지 * 처리(마스킹) // => 처리된 주민번호를 jumin 멤버변수에 저장 // => 주민번호 앞자리 6자리와 뒷자리 1자리까지 추출하여 뒷부분에 * 기호 6개 결합 dbMember.setJumin(dbMember.getJumin().substring(0, 8) + "******"); // 0 ~ 8-1 인덱스까지 추출 // 회원 상세정보 조회 페이지 포워딩 return "member/member_info"; } // =============================================================== // [ 회원 정보 수정 ] // "MemberModifyForm" 서블릿 요청 시 회원 정보 수정 폼 표시 @GetMapping("MemberModifyForm") public String modifyForm(MemberVO member, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 상세정보 조회 요청 // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // 주민번호(MemberVO - jumin는 뒷자리 첫번째 숫자를 제외한 나머지 * 처리(마스킹) // => 처리된 주민번호를 jumin 멤버변수에 저장 // => 주민번호 앞자리 6자리와 뒷자리 1자리까지 추출하여 뒷부분에 * 기호 6개 결합 dbMember.setJumin(dbMember.getJumin().substring(0, 8) + "******"); // 0 ~ 8-1 인덱스까지 추출 // 조회 결과 Model 객체에 저장 model.addAttribute("member", dbMember); return "member/member_modify_form"; } // "MemberModifyPro" 서블릿 요청에 대한 회원 정보 수정 비즈니스 로직 처리 // => 추가로 전달되는 새 패스워드(newPasswd) 값을 전달받을 파라미터 변수 1개 추가(Map 사용 가능) @PostMapping("MemberModifyPro") public String modifyPro(MemberVO member, String newPasswd, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { member.setId(sId); } // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청(패스워드 비교용) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // BCryptPasswordEncoder 클래스를 활용하여 입력받은 기존 패스워드와 DB 패스워드 비교 BCryptPasswordEncoder passwoedEncoder = new BCryptPasswordEncoder(); // 만약, 현재 세션이 관리자가 아니거나 // 관리자이면서 id 파라미터가 없을 경우(null 또는 널스트링) // MemberVO 객체의 id 값을 세션 아이디로 교체(덮어쓰기) if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { // 이 때, 동일한 조건에서 패스워드 검증도 추가로 수행 // => 관리자가 다른 회원의 정보를 수정할 경우에는 패스워드 검증 수행 생략됨 if(!passwoedEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { model.addAttribute("msg", "수정 권한이 없습니다!"); return "fail_back"; } } // 새 패스워드를 입력받았을 경우 BCryptPasswordEncoder 클래스를 활요하여 암호화 처리 // 파라미터로는 newPasswd 자체는 있기에 입력값이 없을 경우 ""으로 넘어오지만 // 만일의 경우를 대비해서 null값도 비교한다. if(newPasswd != null && !newPasswd.equals("")) { newPasswd = passwoedEncoder.encode(newPasswd); } // MemberService - modifyMember() 메서드 호출하여 회원 정보 수정 요청 // => 파라미터 : MemberVO 객체, 새 패스워드(newPasswd) 리턴타입 : int(updateCount) int updateCount = memberService.modifyMember(member, newPasswd); // 회원 정보 수정 요청 결과 판별 // => 실패 시 "fail_back" 페이지 포워딩 처리("회원정보 수정 실패!") // => 성공 시 "MemberInfo" 서블릿 리다이렉트 if(updateCount > 0) { // 관리자가 다른 회원 정보 수정 시 MemberInfo 서블릿 주소에 아이디 파라미터 결합 if(!sId.equals("admin") || sId.equals("admin") && (member.getId() == null || member.getId().equals(""))) { // 본인 정보를 조회할 경우 return "redirect:/MemberInfo"; } else { return "redirect:/MemberInfo?id=" + member.getId(); } } else { model.addAttribute("msg", "회원정보 수정 실패!"); return "fail_back"; } } // =============================================================== // [ 회원 탈퇴 ] // "MemberWithdrawForm" 서블릿 요청 시 회원 정보 탈퇴 폼 표시 @GetMapping("MemberWithdrawForm") public String withdrawForm(HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } return "member/member_withdraw_form"; } // "MemberWithdrawPro" 서블릿 요청 시 회원 탈퇴 비즈니스 로직 처리 @PostMapping("MemberWithdrawPro") public String withdrawPro(MemberVO member, HttpSession session, Model model) { String sId = (String)session.getAttribute("sId"); if(sId == null) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } member.setId(sId); // MemberService - getMember() 메서드 호출하여 회원 정보 조회 요청(패스워드 비교용) // => 파라미터 : MemberVO 객체 리턴타입 : MemberVO(dbMember) MemberVO dbMember = memberService.getMember(member); // BCryptPasswordEncoder 클래스를 활용하여 입력받은 기존 패스워드와 DB 패스워드 비교 BCryptPasswordEncoder passwoedEncoder = new BCryptPasswordEncoder(); if(!passwoedEncoder.matches(member.getPasswd(), dbMember.getPasswd())) { model.addAttribute("msg", "수정 권한이 없습니다!"); return "fail_back"; } // MemberService - withdrawMember() 메서드 호출하여 회원 탈퇴 처리 요청 // => 파라미터 : MemberVO 객체 리턴타입 : int(updateCount) int updateCount = memberService.withdrawMember(member); // 탈퇴 처리 결과 판별 // => 실패 시 "fail_back" 포워딩 처리("회원 탈퇴 실패!") // => 성공 시 세션 초기화 후 메인페이지 리다이렉트 if(updateCount > 0) { session.invalidate(); return "redirect:/"; } else { model.addAttribute("msg", "회원 탈퇴 실패!"); return "fail_back"; } } // ======================================================================= // [ 관리자 페이지 ] @GetMapping("MemberAdminMain") public String adminMain(HttpSession session, Model model) { // 세션 아이디가 null 이거나 "admin" 이 아닐 경우 String sId = (String)session.getAttribute("sId"); if(sId == null || !sId.equals("admin")) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } return "admin/admin_main"; } // [ 회원 목록 조회 ] @GetMapping("AdminMemberList") public String memberList(HttpSession session, Model model) { // 세션 아이디가 null 이거나 "admin" 이 아닐 경우 String sId = (String)session.getAttribute("sId"); if(sId == null || !sId.equals("admin")) { model.addAttribute("msg", "잘못된 접근입니다!"); return "fail_back"; } // MemberService - getMemberList() 메서드 호출하여 회원 목록 조회 요청 // => 파라미터 : 없음 리턴타입 : List<MemberVO>(memberList) List<MemberVO> memberList = memberService.getMemberList(); System.out.println(memberList); // Model 객체에 회원 목록 조회 결과 저장 model.addAttribute("memberList", memberList); // 회원 목록 조회 페이지(admin/member_list.jsp)로 포워딩 return "admin/member_list"; } }
123812_20
/** * Copyright (c) 2007, AurorisNET. * * Everyone is permitted to copy and distribute verbatim copies of this license * document, but changing it is not allowed. * * Preamble * * This license establishes the terms under which a given free software Package * may be copied, modified, distributed, and/or redistributed. The intent is * that the Copyright Holder maintains some artistic control over the * development of that Package while still keeping the Package available as open * source and free software. * * You are always permitted to make arrangements wholly outside of this license * directly with the Copyright Holder of a given Package. If the terms of this * license do not permit the full use that you propose to make of the Package, * you should contact the Copyright Holder and seek a different licensing * arrangement. * * Definitions * * "Copyright Holder" means the individual(s) or organization(s) named in the * copyright notice for the entire Package. * * "Contributor" means any party that has contributed code or other material to * the Package, in accordance with the Copyright Holder's procedures. * * "You" and "your" means any person who would like to copy, distribute, or * modify the Package. * * "Package" means the collection of files distributed by the Copyright Holder, * and derivatives of that collection and/or of those files. A given Package may * consist of either the Standard Version, or a Modified Version. * * "Distribute" means providing a copy of the Package or making it accessible to * anyone else, or in the case of a company or organization, to others outside * of your company or organization. * * "Distributor Fee" means any fee that you charge for Distributing this Package * or providing support for this Package to another party. It does not mean * licensing fees. * * "Standard Version" refers to the Package if it has not been modified, or has * been modified only in ways explicitly requested by the Copyright Holder. * * "Modified Version" means the Package, if it has been changed, and such * changes were not explicitly requested by the Copyright Holder. * * "Original License" means this Artistic License as Distributed with the * Standard Version of the Package, in its current version or as it may be * modified by The Perl Foundation in the future. * * "Source" form means the source code, documentation source, and configuration * files for the Package. * * "Compiled" form means the compiled bytecode, object code, binary, or any * other form resulting from mechanical transformation or translation of the * Source form. * * Permission for Use and Modification Without Distribution * * (1) You are permitted to use the Standard Version and create and use Modified * Versions for any purpose without restriction, provided that you do not * Distribute the Modified Version. * * Permissions for Redistribution of the Standard Version * * (2) You may Distribute verbatim copies of the Source form of the Standard * Version of this Package in any medium without restriction, either gratis or * for a Distributor Fee, provided that you duplicate all of the original * copyright notices and associated disclaimers. At your discretion, such * verbatim copies may or may not include a Compiled form of the Package. * * (3) You may apply any bug fixes, portability changes, and other modifications * made available from the Copyright Holder. The resulting Package will still be * considered the Standard Version, and as such will be subject to the Original * License. * * Distribution of Modified Versions of the Package as Source * * (4) You may Distribute your Modified Version as Source (either gratis or for * a Distributor Fee, and with or without a Compiled form of the Modified * Version) provided that you clearly document how it differs from the Standard * Version, including, but not limited to, documenting any non-standard * features, executables, or modules, and provided that you do at least ONE of * the following: * * (a) make the Modified Version available to the Copyright Holder of the * Standard Version, under the Original License, so that the Copyright * Holder may include your modifications in the Standard Version. * * (b) ensure that installation of your Modified Version does not prevent * the user installing or running the Standard Version. In addition, * the Modified Version must bear a name that is different from the * name of the Standard Version. * * (c) allow anyone who receives a copy of the Modified Version to make the * Source form of the Modified Version available to others under * * (i) the Original License or * * (ii) a license that permits the licensee to freely copy, modify and * redistribute the Modified Version using the same licensing terms * that apply to the copy that the licensee received, and requires * that the Source form ofthe Modified Version, and of any works * derived from it, be made freely available in that license fees * are prohibited but Distributor Fees are allowed. * * Distribution of Compiled Forms of the Standard Version or Modified Versions * without the Source * * (5) You may Distribute Compiled forms of the Standard Version without the * Source, provided that you include complete instructions on how to get the * Source of the Standard Version. Such instructions must be valid at the time * of your distribution. If these instructions, at any time while you are * carrying out such distribution, become invalid, you must provide new * instructions on demand or cease further distribution. If you provide valid * instructions or cease distribution within thirty days after you become aware * that the instructions are invalid, then you do not forfeit any of your rights * under this license. * * (6) You may Distribute a Modified Version in Compiled form without the * Source, provided that you comply with Section 4 with respect to the Source of * the Modified Version. * * Aggregating or Linking the Package * * (7) You may aggregate the Package (either the Standard Version or Modified * Version) with other packages and Distribute the resulting aggregation * provided that you do not charge a licensing fee for the Package. Distributor * Fees are permitted, and licensing fees for other components in the * aggregation are permitted. The terms of this license apply to the use and * Distribution of the Standard or Modified Versions as included in the * aggregation. * * (8) You are permitted to link Modified and Standard Versions with other * works, to embed the Package in a larger work of your own, or to build * stand-alone binary or bytecode versions of applications that include the * Package, and Distribute the result without restriction, provided the result * does not expose a direct interface to the Package. * * Items That are Not Considered Part of a Modified Version * * (9) Works (including, but not limited to, modules and scripts) that merely * extend or make use of the Package, do not, by themselves, cause the Package * to be a Modified Version. In addition, such works are not considered parts of * the Package itself, and are not subject to the terms of this license. * * General Provisions * * (10) Any use, modification, and distribution of the Standard or Modified * Versions is governed by this Artistic License. By using, modifying or * distributing the Package, you accept this license. Do not use, modify, or * distribute the Package, if you do not accept this license. * * (11) If your Modified Version has been derived from a Modified Version made * by someone other than you, you are nevertheless required to ensure that your * Modified Version complies with the requirements of this license. * * (12) This license does not grant you the right to use any trademark, service * mark, tradename, or logo of the Copyright Holder. * * (13) This license includes the non-exclusive, worldwide, free-of-charge * patent license to make, have made, use, offer to sell, sell, import and * otherwise transfer the Package with respect to any patent claims licensable * by the Copyright Holder that are necessarily infringed by the Package. If you * institute patent litigation (including a cross-claim or counterclaim) against * any party alleging that the Package constitutes direct or contributory patent * infringement, then this Artistic License to you shall terminate on the date * that such litigation is filed. * * (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER * AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR * NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. * UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY * OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.pentaho.gwt.widgets.client.colorpicker; /** * Copyright (c) 2007, AurorisNET. * * Everyone is permitted to copy and distribute verbatim copies of this license * document, but changing it is not allowed. * * Preamble * * This license establishes the terms under which a given free software Package * may be copied, modified, distributed, and/or redistributed. The intent is * that the Copyright Holder maintains some artistic control over the * development of that Package while still keeping the Package available as open * source and free software. * * You are always permitted to make arrangements wholly outside of this license * directly with the Copyright Holder of a given Package. If the terms of this * license do not permit the full use that you propose to make of the Package, * you should contact the Copyright Holder and seek a different licensing * arrangement. * * Definitions * * "Copyright Holder" means the individual(s) or organization(s) named in the * copyright notice for the entire Package. * * "Contributor" means any party that has contributed code or other material to * the Package, in accordance with the Copyright Holder's procedures. * * "You" and "your" means any person who would like to copy, distribute, or * modify the Package. * * "Package" means the collection of files distributed by the Copyright Holder, * and derivatives of that collection and/or of those files. A given Package may * consist of either the Standard Version, or a Modified Version. * * "Distribute" means providing a copy of the Package or making it accessible to * anyone else, or in the case of a company or organization, to others outside * of your company or organization. * * "Distributor Fee" means any fee that you charge for Distributing this Package * or providing support for this Package to another party. It does not mean * licensing fees. * * "Standard Version" refers to the Package if it has not been modified, or has * been modified only in ways explicitly requested by the Copyright Holder. * * "Modified Version" means the Package, if it has been changed, and such * changes were not explicitly requested by the Copyright Holder. * * "Original License" means this Artistic License as Distributed with the * Standard Version of the Package, in its current version or as it may be * modified by The Perl Foundation in the future. * * "Source" form means the source code, documentation source, and configuration * files for the Package. * * "Compiled" form means the compiled bytecode, object code, binary, or any * other form resulting from mechanical transformation or translation of the * Source form. * * Permission for Use and Modification Without Distribution * * (1) You are permitted to use the Standard Version and create and use Modified * Versions for any purpose without restriction, provided that you do not * Distribute the Modified Version. * * Permissions for Redistribution of the Standard Version * * (2) You may Distribute verbatim copies of the Source form of the Standard * Version of this Package in any medium without restriction, either gratis or * for a Distributor Fee, provided that you duplicate all of the original * copyright notices and associated disclaimers. At your discretion, such * verbatim copies may or may not include a Compiled form of the Package. * * (3) You may apply any bug fixes, portability changes, and other modifications * made available from the Copyright Holder. The resulting Package will still be * considered the Standard Version, and as such will be subject to the Original * License. * * Distribution of Modified Versions of the Package as Source * * (4) You may Distribute your Modified Version as Source (either gratis or for * a Distributor Fee, and with or without a Compiled form of the Modified * Version) provided that you clearly document how it differs from the Standard * Version, including, but not limited to, documenting any non-standard * features, executables, or modules, and provided that you do at least ONE of * the following: * * (a) make the Modified Version available to the Copyright Holder of the * Standard Version, under the Original License, so that the Copyright * Holder may include your modifications in the Standard Version. * * (b) ensure that installation of your Modified Version does not prevent * the user installing or running the Standard Version. In addition, * the Modified Version must bear a name that is different from the * name of the Standard Version. * * (c) allow anyone who receives a copy of the Modified Version to make the * Source form of the Modified Version available to others under * * (i) the Original License or * * (ii) a license that permits the licensee to freely copy, modify and * redistribute the Modified Version using the same licensing terms * that apply to the copy that the licensee received, and requires * that the Source form ofthe Modified Version, and of any works * derived from it, be made freely available in that license fees * are prohibited but Distributor Fees are allowed. * * Distribution of Compiled Forms of the Standard Version or Modified Versions * without the Source * * (5) You may Distribute Compiled forms of the Standard Version without the * Source, provided that you include complete instructions on how to get the * Source of the Standard Version. Such instructions must be valid at the time * of your distribution. If these instructions, at any time while you are * carrying out such distribution, become invalid, you must provide new * instructions on demand or cease further distribution. If you provide valid * instructions or cease distribution within thirty days after you become aware * that the instructions are invalid, then you do not forfeit any of your rights * under this license. * * (6) You may Distribute a Modified Version in Compiled form without the * Source, provided that you comply with Section 4 with respect to the Source of * the Modified Version. * * Aggregating or Linking the Package * * (7) You may aggregate the Package (either the Standard Version or Modified * Version) with other packages and Distribute the resulting aggregation * provided that you do not charge a licensing fee for the Package. Distributor * Fees are permitted, and licensing fees for other components in the * aggregation are permitted. The terms of this license apply to the use and * Distribution of the Standard or Modified Versions as included in the * aggregation. * * (8) You are permitted to link Modified and Standard Versions with other * works, to embed the Package in a larger work of your own, or to build * stand-alone binary or bytecode versions of applications that include the * Package, and Distribute the result without restriction, provided the result * does not expose a direct interface to the Package. * * Items That are Not Considered Part of a Modified Version * * (9) Works (including, but not limited to, modules and scripts) that merely * extend or make use of the Package, do not, by themselves, cause the Package * to be a Modified Version. In addition, such works are not considered parts of * the Package itself, and are not subject to the terms of this license. * * General Provisions * * (10) Any use, modification, and distribution of the Standard or Modified * Versions is governed by this Artistic License. By using, modifying or * distributing the Package, you accept this license. Do not use, modify, or * distribute the Package, if you do not accept this license. * * (11) If your Modified Version has been derived from a Modified Version made * by someone other than you, you are nevertheless required to ensure that your * Modified Version complies with the requirements of this license. * * (12) This license does not grant you the right to use any trademark, service * mark, tradename, or logo of the Copyright Holder. * * (13) This license includes the non-exclusive, worldwide, free-of-charge * patent license to make, have made, use, offer to sell, sell, import and * otherwise transfer the Package with respect to any patent claims licensable * by the Copyright Holder that are necessarily infringed by the Package. If you * institute patent litigation (including a cross-claim or counterclaim) against * any party alleging that the Package constitutes direct or contributory patent * infringement, then this Artistic License to you shall terminate on the date * that such litigation is filed. * * (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER * AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR * NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. * UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY * OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ /** * A helpful class to convert between the HSV and RGB colorspaces. * * @author AurorisNET */ public class Color { private float h; // [0,360] Hue private float s; // [0-1] Saturation private float v; // [0-1] Value private float r; // [0-1] Red private float g; // [0-1] Green private float b; // [0-1] Blue private String hex; // Hexadecimal notation of RGB /** * Set the Hue, Saturation and Value (Brightness) variables. This will automatically populate the Red, Green, Blue, * and Hexadecimal fields, too. * * It represents points in the RGB color space, which attempt to describe perceptual color relationships more * accurately than RGB. HSV describes colors as points in a cylinder whose central axis ranges from black at the * bottom to white at the top with neutral colors between them, where angle around the axis corresponds to hue, * distance from the axis corresponds to saturation, and distance along the axis corresponds to lightness, value, or * brightness. * * @param h * Hue - valid range is 0-359 * @param s * Saturation - valid range is 0-100 * @param v * Value (Brightness) - valid range is 0-100 * @throws java.lang.Exception * A general exception if the Hue, Saturation, or Value variables are out of range. */ public void setHSV( int h, int s, int v ) throws Exception { if ( h < 0 || h > 360 ) { throw new Exception(); } if ( s < 0 || s > 100 ) { throw new Exception(); } if ( v < 0 || v > 100 ) { throw new Exception(); } this.h = (float) h; this.s = (float) s / 100; this.v = (float) v / 100; HSVtoRGB( this.h, this.s, this.v ); setHex(); } /** * Sets the Red, Green, and Blue color variables. This will automatically convert to Hue, Saturation and Brightness * and Hexadecimal. * * The RGB color model is an additive color model in which red, green, and blue light are added together in various * ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive * primary colors, red, green, and blue. * * @param r * Red - valid range is 0-255 * @param g * Green - valid range is 0-255 * @param b * Blue - valid range is 0-255 * @throws java.lang.Exception * Exception if the Red, Green or Blue variables are out of range. */ public void setRGB( int r, int g, int b ) throws Exception { if ( r < 0 || r > 255 ) { throw new Exception(); } if ( g < 0 || g > 255 ) { throw new Exception(); } if ( b < 0 || b > 255 ) { throw new Exception(); } this.r = (float) r / 255; this.g = (float) g / 255; this.b = (float) b / 255; RGBtoHSV( this.r, this.g, this.b ); setHex(); } /** * Sets the hexadecimal representation of Red, Green and Blue. * * @param hex * The hexadecimal string notation. It must be 6 letters long and consist of the characters 0-9 and A-F. * @throws java.lang.Exception * Exception if the hexadecimal string cannot be parsed into its Red, Green, and Blue components. */ public void setHex( String hex ) throws Exception { if ( hex.length() == 6 ) { setRGB( Integer.parseInt( hex.substring( 0, 2 ), 16 ), Integer.parseInt( hex.substring( 2, 4 ), 16 ), Integer .parseInt( hex.substring( 4, 6 ), 16 ) ); } else { throw new Exception(); } } /** * Converts from RGB to Hexadecimal notation. */ private void setHex() { String hRed = Integer.toHexString( getRed() ); String hGreen = Integer.toHexString( getGreen() ); String hBlue = Integer.toHexString( getBlue() ); if ( hRed.length() == 0 ) { hRed = "00"; //$NON-NLS-1$ } if ( hRed.length() == 1 ) { hRed = "0" + hRed; //$NON-NLS-1$ } if ( hGreen.length() == 0 ) { hGreen = "00"; //$NON-NLS-1$ } if ( hGreen.length() == 1 ) { hGreen = "0" + hGreen; //$NON-NLS-1$ } if ( hBlue.length() == 0 ) { hBlue = "00"; //$NON-NLS-1$ } if ( hBlue.length() == 1 ) { hBlue = "0" + hBlue; //$NON-NLS-1$ } this.hex = hRed + hGreen + hBlue; } /** * Returns the integer of the red component of the RGB colorspace, or 0 if it hasn't been set. * * @return red component */ public int getRed() { return (int) ( r * 255.0f + 0.5f ); } /** * Returns the integer of the green component of the RGB colorspace, or 0 if it hasn't been set. * * @return green component */ public int getGreen() { return (int) ( g * 255.0f + 0.5f ); } /** * Returns the integer of the blue component of the RGB colorspace, or 0 if it hasn't been set. * * @return blue component */ public int getBlue() { return (int) ( b * 255.0f + 0.5f ); } /** * Returns the integer of the hue component of the HSV colorspace, or 0 if it hasn't been set. * * @return hue component */ public int getHue() { return Math.round( h ); } /** * Returns the integer of the saturation component of the HSV colorspace, or 0 if it hasn't been set. * * @return saturation component */ public int getSaturation() { return Math.round( s * 100 ); } /** * Returns the integer of the value (brightness) component of the HSV colorspace, or 0 if it hasn't been set. * * @return value component */ public int getValue() { return Math.round( v * 100 ); } /** * Returns the hexadecimal representation of the RGB colorspace. * * @return hexadecimal representation */ public String getHex() { return hex; } // r,g,b values are from 0 to 1 // h = [0,360], s = [0,1], v = [0,1] // if s == 0, then h = (undefined) /** * Converts the RGB colorspace into the HSV colorspace. This private method works exclusively with internal variables * and does not return anything. * * @param r * Red * @param g * Green * @param b * Blue */ private void RGBtoHSV( float r, float g, float b ) { float min = 0; float max = 0; float delta = 0; min = MIN( r, g, b ); max = MAX( r, g, b ); this.v = max; // v delta = max - min; if ( max != 0 ) { this.s = delta / max; // s } else { // r = g = b = 0 // s = 0, v is undefined this.s = 0; this.h = 0; return; } if ( delta == 0 ) { h = 0; return; } if ( r == max ) { this.h = ( g - b ) / delta; // between yellow & magenta } else if ( g == max ) { this.h = 2 + ( b - r ) / delta; // between cyan & yellow } else { this.h = 4 + ( r - g ) / delta; // between magenta & cyan } this.h *= 60; // degrees if ( this.h < 0 ) { this.h += 360; } } /** * Converts the HSV colorspace into the RGB colorspace. This private method works exclusively with internal variables * and does not return anything. * * @param h * Hue * @param s * Saturation * @param v * Value (Brightness) */ private void HSVtoRGB( float h, float s, float v ) { int i; float f; float p; float q; float t; if ( s == 0 ) { // achromatic (grey) this.r = v; this.g = v; this.b = v; return; } h /= 60; // sector 0 to 5 i = (int) Math.floor( h ); f = h - i; // factorial part of h p = v * ( 1 - s ); q = v * ( 1 - s * f ); t = v * ( 1 - s * ( 1 - f ) ); switch ( i ) { case 0: this.r = v; this.g = t; this.b = p; break; case 1: this.r = q; this.g = v; this.b = p; break; case 2: this.r = p; this.g = v; this.b = t; break; case 3: this.r = p; this.g = q; this.b = v; break; case 4: this.r = t; this.g = p; this.b = v; break; default: // case 5: this.r = v; this.g = p; this.b = q; break; } } /** * A helper function to determine the largest value between the three inputs. * * @param a * First value * @param b * Second value * @param c * Third value * @return The value of the largest of the inputs. */ private float MAX( float a, float b, float c ) { float max = Integer.MIN_VALUE; if ( a > max ) { max = a; } if ( b > max ) { max = b; } if ( c > max ) { max = c; } return max; } /** * A helper function to determine the smallest value between the three inputs. * * @param a * First value * @param b * Second value * @param c * Third value * @return The value of the smallest of the inputs. */ private float MIN( float a, float b, float c ) { float min = Integer.MAX_VALUE; if ( a < min ) { min = a; } if ( b < min ) { min = b; } if ( c < min ) { min = c; } return min; } }
pentaho/pentaho-commons-gwt-modules
widgets/src/main/java/org/pentaho/gwt/widgets/client/colorpicker/Color.java
7,837
// between yellow & magenta
line_comment
nl
/** * Copyright (c) 2007, AurorisNET. * * Everyone is permitted to copy and distribute verbatim copies of this license * document, but changing it is not allowed. * * Preamble * * This license establishes the terms under which a given free software Package * may be copied, modified, distributed, and/or redistributed. The intent is * that the Copyright Holder maintains some artistic control over the * development of that Package while still keeping the Package available as open * source and free software. * * You are always permitted to make arrangements wholly outside of this license * directly with the Copyright Holder of a given Package. If the terms of this * license do not permit the full use that you propose to make of the Package, * you should contact the Copyright Holder and seek a different licensing * arrangement. * * Definitions * * "Copyright Holder" means the individual(s) or organization(s) named in the * copyright notice for the entire Package. * * "Contributor" means any party that has contributed code or other material to * the Package, in accordance with the Copyright Holder's procedures. * * "You" and "your" means any person who would like to copy, distribute, or * modify the Package. * * "Package" means the collection of files distributed by the Copyright Holder, * and derivatives of that collection and/or of those files. A given Package may * consist of either the Standard Version, or a Modified Version. * * "Distribute" means providing a copy of the Package or making it accessible to * anyone else, or in the case of a company or organization, to others outside * of your company or organization. * * "Distributor Fee" means any fee that you charge for Distributing this Package * or providing support for this Package to another party. It does not mean * licensing fees. * * "Standard Version" refers to the Package if it has not been modified, or has * been modified only in ways explicitly requested by the Copyright Holder. * * "Modified Version" means the Package, if it has been changed, and such * changes were not explicitly requested by the Copyright Holder. * * "Original License" means this Artistic License as Distributed with the * Standard Version of the Package, in its current version or as it may be * modified by The Perl Foundation in the future. * * "Source" form means the source code, documentation source, and configuration * files for the Package. * * "Compiled" form means the compiled bytecode, object code, binary, or any * other form resulting from mechanical transformation or translation of the * Source form. * * Permission for Use and Modification Without Distribution * * (1) You are permitted to use the Standard Version and create and use Modified * Versions for any purpose without restriction, provided that you do not * Distribute the Modified Version. * * Permissions for Redistribution of the Standard Version * * (2) You may Distribute verbatim copies of the Source form of the Standard * Version of this Package in any medium without restriction, either gratis or * for a Distributor Fee, provided that you duplicate all of the original * copyright notices and associated disclaimers. At your discretion, such * verbatim copies may or may not include a Compiled form of the Package. * * (3) You may apply any bug fixes, portability changes, and other modifications * made available from the Copyright Holder. The resulting Package will still be * considered the Standard Version, and as such will be subject to the Original * License. * * Distribution of Modified Versions of the Package as Source * * (4) You may Distribute your Modified Version as Source (either gratis or for * a Distributor Fee, and with or without a Compiled form of the Modified * Version) provided that you clearly document how it differs from the Standard * Version, including, but not limited to, documenting any non-standard * features, executables, or modules, and provided that you do at least ONE of * the following: * * (a) make the Modified Version available to the Copyright Holder of the * Standard Version, under the Original License, so that the Copyright * Holder may include your modifications in the Standard Version. * * (b) ensure that installation of your Modified Version does not prevent * the user installing or running the Standard Version. In addition, * the Modified Version must bear a name that is different from the * name of the Standard Version. * * (c) allow anyone who receives a copy of the Modified Version to make the * Source form of the Modified Version available to others under * * (i) the Original License or * * (ii) a license that permits the licensee to freely copy, modify and * redistribute the Modified Version using the same licensing terms * that apply to the copy that the licensee received, and requires * that the Source form ofthe Modified Version, and of any works * derived from it, be made freely available in that license fees * are prohibited but Distributor Fees are allowed. * * Distribution of Compiled Forms of the Standard Version or Modified Versions * without the Source * * (5) You may Distribute Compiled forms of the Standard Version without the * Source, provided that you include complete instructions on how to get the * Source of the Standard Version. Such instructions must be valid at the time * of your distribution. If these instructions, at any time while you are * carrying out such distribution, become invalid, you must provide new * instructions on demand or cease further distribution. If you provide valid * instructions or cease distribution within thirty days after you become aware * that the instructions are invalid, then you do not forfeit any of your rights * under this license. * * (6) You may Distribute a Modified Version in Compiled form without the * Source, provided that you comply with Section 4 with respect to the Source of * the Modified Version. * * Aggregating or Linking the Package * * (7) You may aggregate the Package (either the Standard Version or Modified * Version) with other packages and Distribute the resulting aggregation * provided that you do not charge a licensing fee for the Package. Distributor * Fees are permitted, and licensing fees for other components in the * aggregation are permitted. The terms of this license apply to the use and * Distribution of the Standard or Modified Versions as included in the * aggregation. * * (8) You are permitted to link Modified and Standard Versions with other * works, to embed the Package in a larger work of your own, or to build * stand-alone binary or bytecode versions of applications that include the * Package, and Distribute the result without restriction, provided the result * does not expose a direct interface to the Package. * * Items That are Not Considered Part of a Modified Version * * (9) Works (including, but not limited to, modules and scripts) that merely * extend or make use of the Package, do not, by themselves, cause the Package * to be a Modified Version. In addition, such works are not considered parts of * the Package itself, and are not subject to the terms of this license. * * General Provisions * * (10) Any use, modification, and distribution of the Standard or Modified * Versions is governed by this Artistic License. By using, modifying or * distributing the Package, you accept this license. Do not use, modify, or * distribute the Package, if you do not accept this license. * * (11) If your Modified Version has been derived from a Modified Version made * by someone other than you, you are nevertheless required to ensure that your * Modified Version complies with the requirements of this license. * * (12) This license does not grant you the right to use any trademark, service * mark, tradename, or logo of the Copyright Holder. * * (13) This license includes the non-exclusive, worldwide, free-of-charge * patent license to make, have made, use, offer to sell, sell, import and * otherwise transfer the Package with respect to any patent claims licensable * by the Copyright Holder that are necessarily infringed by the Package. If you * institute patent litigation (including a cross-claim or counterclaim) against * any party alleging that the Package constitutes direct or contributory patent * infringement, then this Artistic License to you shall terminate on the date * that such litigation is filed. * * (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER * AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR * NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. * UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY * OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.pentaho.gwt.widgets.client.colorpicker; /** * Copyright (c) 2007, AurorisNET. * * Everyone is permitted to copy and distribute verbatim copies of this license * document, but changing it is not allowed. * * Preamble * * This license establishes the terms under which a given free software Package * may be copied, modified, distributed, and/or redistributed. The intent is * that the Copyright Holder maintains some artistic control over the * development of that Package while still keeping the Package available as open * source and free software. * * You are always permitted to make arrangements wholly outside of this license * directly with the Copyright Holder of a given Package. If the terms of this * license do not permit the full use that you propose to make of the Package, * you should contact the Copyright Holder and seek a different licensing * arrangement. * * Definitions * * "Copyright Holder" means the individual(s) or organization(s) named in the * copyright notice for the entire Package. * * "Contributor" means any party that has contributed code or other material to * the Package, in accordance with the Copyright Holder's procedures. * * "You" and "your" means any person who would like to copy, distribute, or * modify the Package. * * "Package" means the collection of files distributed by the Copyright Holder, * and derivatives of that collection and/or of those files. A given Package may * consist of either the Standard Version, or a Modified Version. * * "Distribute" means providing a copy of the Package or making it accessible to * anyone else, or in the case of a company or organization, to others outside * of your company or organization. * * "Distributor Fee" means any fee that you charge for Distributing this Package * or providing support for this Package to another party. It does not mean * licensing fees. * * "Standard Version" refers to the Package if it has not been modified, or has * been modified only in ways explicitly requested by the Copyright Holder. * * "Modified Version" means the Package, if it has been changed, and such * changes were not explicitly requested by the Copyright Holder. * * "Original License" means this Artistic License as Distributed with the * Standard Version of the Package, in its current version or as it may be * modified by The Perl Foundation in the future. * * "Source" form means the source code, documentation source, and configuration * files for the Package. * * "Compiled" form means the compiled bytecode, object code, binary, or any * other form resulting from mechanical transformation or translation of the * Source form. * * Permission for Use and Modification Without Distribution * * (1) You are permitted to use the Standard Version and create and use Modified * Versions for any purpose without restriction, provided that you do not * Distribute the Modified Version. * * Permissions for Redistribution of the Standard Version * * (2) You may Distribute verbatim copies of the Source form of the Standard * Version of this Package in any medium without restriction, either gratis or * for a Distributor Fee, provided that you duplicate all of the original * copyright notices and associated disclaimers. At your discretion, such * verbatim copies may or may not include a Compiled form of the Package. * * (3) You may apply any bug fixes, portability changes, and other modifications * made available from the Copyright Holder. The resulting Package will still be * considered the Standard Version, and as such will be subject to the Original * License. * * Distribution of Modified Versions of the Package as Source * * (4) You may Distribute your Modified Version as Source (either gratis or for * a Distributor Fee, and with or without a Compiled form of the Modified * Version) provided that you clearly document how it differs from the Standard * Version, including, but not limited to, documenting any non-standard * features, executables, or modules, and provided that you do at least ONE of * the following: * * (a) make the Modified Version available to the Copyright Holder of the * Standard Version, under the Original License, so that the Copyright * Holder may include your modifications in the Standard Version. * * (b) ensure that installation of your Modified Version does not prevent * the user installing or running the Standard Version. In addition, * the Modified Version must bear a name that is different from the * name of the Standard Version. * * (c) allow anyone who receives a copy of the Modified Version to make the * Source form of the Modified Version available to others under * * (i) the Original License or * * (ii) a license that permits the licensee to freely copy, modify and * redistribute the Modified Version using the same licensing terms * that apply to the copy that the licensee received, and requires * that the Source form ofthe Modified Version, and of any works * derived from it, be made freely available in that license fees * are prohibited but Distributor Fees are allowed. * * Distribution of Compiled Forms of the Standard Version or Modified Versions * without the Source * * (5) You may Distribute Compiled forms of the Standard Version without the * Source, provided that you include complete instructions on how to get the * Source of the Standard Version. Such instructions must be valid at the time * of your distribution. If these instructions, at any time while you are * carrying out such distribution, become invalid, you must provide new * instructions on demand or cease further distribution. If you provide valid * instructions or cease distribution within thirty days after you become aware * that the instructions are invalid, then you do not forfeit any of your rights * under this license. * * (6) You may Distribute a Modified Version in Compiled form without the * Source, provided that you comply with Section 4 with respect to the Source of * the Modified Version. * * Aggregating or Linking the Package * * (7) You may aggregate the Package (either the Standard Version or Modified * Version) with other packages and Distribute the resulting aggregation * provided that you do not charge a licensing fee for the Package. Distributor * Fees are permitted, and licensing fees for other components in the * aggregation are permitted. The terms of this license apply to the use and * Distribution of the Standard or Modified Versions as included in the * aggregation. * * (8) You are permitted to link Modified and Standard Versions with other * works, to embed the Package in a larger work of your own, or to build * stand-alone binary or bytecode versions of applications that include the * Package, and Distribute the result without restriction, provided the result * does not expose a direct interface to the Package. * * Items That are Not Considered Part of a Modified Version * * (9) Works (including, but not limited to, modules and scripts) that merely * extend or make use of the Package, do not, by themselves, cause the Package * to be a Modified Version. In addition, such works are not considered parts of * the Package itself, and are not subject to the terms of this license. * * General Provisions * * (10) Any use, modification, and distribution of the Standard or Modified * Versions is governed by this Artistic License. By using, modifying or * distributing the Package, you accept this license. Do not use, modify, or * distribute the Package, if you do not accept this license. * * (11) If your Modified Version has been derived from a Modified Version made * by someone other than you, you are nevertheless required to ensure that your * Modified Version complies with the requirements of this license. * * (12) This license does not grant you the right to use any trademark, service * mark, tradename, or logo of the Copyright Holder. * * (13) This license includes the non-exclusive, worldwide, free-of-charge * patent license to make, have made, use, offer to sell, sell, import and * otherwise transfer the Package with respect to any patent claims licensable * by the Copyright Holder that are necessarily infringed by the Package. If you * institute patent litigation (including a cross-claim or counterclaim) against * any party alleging that the Package constitutes direct or contributory patent * infringement, then this Artistic License to you shall terminate on the date * that such litigation is filed. * * (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER * AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR * NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. * UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY * OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ /** * A helpful class to convert between the HSV and RGB colorspaces. * * @author AurorisNET */ public class Color { private float h; // [0,360] Hue private float s; // [0-1] Saturation private float v; // [0-1] Value private float r; // [0-1] Red private float g; // [0-1] Green private float b; // [0-1] Blue private String hex; // Hexadecimal notation of RGB /** * Set the Hue, Saturation and Value (Brightness) variables. This will automatically populate the Red, Green, Blue, * and Hexadecimal fields, too. * * It represents points in the RGB color space, which attempt to describe perceptual color relationships more * accurately than RGB. HSV describes colors as points in a cylinder whose central axis ranges from black at the * bottom to white at the top with neutral colors between them, where angle around the axis corresponds to hue, * distance from the axis corresponds to saturation, and distance along the axis corresponds to lightness, value, or * brightness. * * @param h * Hue - valid range is 0-359 * @param s * Saturation - valid range is 0-100 * @param v * Value (Brightness) - valid range is 0-100 * @throws java.lang.Exception * A general exception if the Hue, Saturation, or Value variables are out of range. */ public void setHSV( int h, int s, int v ) throws Exception { if ( h < 0 || h > 360 ) { throw new Exception(); } if ( s < 0 || s > 100 ) { throw new Exception(); } if ( v < 0 || v > 100 ) { throw new Exception(); } this.h = (float) h; this.s = (float) s / 100; this.v = (float) v / 100; HSVtoRGB( this.h, this.s, this.v ); setHex(); } /** * Sets the Red, Green, and Blue color variables. This will automatically convert to Hue, Saturation and Brightness * and Hexadecimal. * * The RGB color model is an additive color model in which red, green, and blue light are added together in various * ways to reproduce a broad array of colors. The name of the model comes from the initials of the three additive * primary colors, red, green, and blue. * * @param r * Red - valid range is 0-255 * @param g * Green - valid range is 0-255 * @param b * Blue - valid range is 0-255 * @throws java.lang.Exception * Exception if the Red, Green or Blue variables are out of range. */ public void setRGB( int r, int g, int b ) throws Exception { if ( r < 0 || r > 255 ) { throw new Exception(); } if ( g < 0 || g > 255 ) { throw new Exception(); } if ( b < 0 || b > 255 ) { throw new Exception(); } this.r = (float) r / 255; this.g = (float) g / 255; this.b = (float) b / 255; RGBtoHSV( this.r, this.g, this.b ); setHex(); } /** * Sets the hexadecimal representation of Red, Green and Blue. * * @param hex * The hexadecimal string notation. It must be 6 letters long and consist of the characters 0-9 and A-F. * @throws java.lang.Exception * Exception if the hexadecimal string cannot be parsed into its Red, Green, and Blue components. */ public void setHex( String hex ) throws Exception { if ( hex.length() == 6 ) { setRGB( Integer.parseInt( hex.substring( 0, 2 ), 16 ), Integer.parseInt( hex.substring( 2, 4 ), 16 ), Integer .parseInt( hex.substring( 4, 6 ), 16 ) ); } else { throw new Exception(); } } /** * Converts from RGB to Hexadecimal notation. */ private void setHex() { String hRed = Integer.toHexString( getRed() ); String hGreen = Integer.toHexString( getGreen() ); String hBlue = Integer.toHexString( getBlue() ); if ( hRed.length() == 0 ) { hRed = "00"; //$NON-NLS-1$ } if ( hRed.length() == 1 ) { hRed = "0" + hRed; //$NON-NLS-1$ } if ( hGreen.length() == 0 ) { hGreen = "00"; //$NON-NLS-1$ } if ( hGreen.length() == 1 ) { hGreen = "0" + hGreen; //$NON-NLS-1$ } if ( hBlue.length() == 0 ) { hBlue = "00"; //$NON-NLS-1$ } if ( hBlue.length() == 1 ) { hBlue = "0" + hBlue; //$NON-NLS-1$ } this.hex = hRed + hGreen + hBlue; } /** * Returns the integer of the red component of the RGB colorspace, or 0 if it hasn't been set. * * @return red component */ public int getRed() { return (int) ( r * 255.0f + 0.5f ); } /** * Returns the integer of the green component of the RGB colorspace, or 0 if it hasn't been set. * * @return green component */ public int getGreen() { return (int) ( g * 255.0f + 0.5f ); } /** * Returns the integer of the blue component of the RGB colorspace, or 0 if it hasn't been set. * * @return blue component */ public int getBlue() { return (int) ( b * 255.0f + 0.5f ); } /** * Returns the integer of the hue component of the HSV colorspace, or 0 if it hasn't been set. * * @return hue component */ public int getHue() { return Math.round( h ); } /** * Returns the integer of the saturation component of the HSV colorspace, or 0 if it hasn't been set. * * @return saturation component */ public int getSaturation() { return Math.round( s * 100 ); } /** * Returns the integer of the value (brightness) component of the HSV colorspace, or 0 if it hasn't been set. * * @return value component */ public int getValue() { return Math.round( v * 100 ); } /** * Returns the hexadecimal representation of the RGB colorspace. * * @return hexadecimal representation */ public String getHex() { return hex; } // r,g,b values are from 0 to 1 // h = [0,360], s = [0,1], v = [0,1] // if s == 0, then h = (undefined) /** * Converts the RGB colorspace into the HSV colorspace. This private method works exclusively with internal variables * and does not return anything. * * @param r * Red * @param g * Green * @param b * Blue */ private void RGBtoHSV( float r, float g, float b ) { float min = 0; float max = 0; float delta = 0; min = MIN( r, g, b ); max = MAX( r, g, b ); this.v = max; // v delta = max - min; if ( max != 0 ) { this.s = delta / max; // s } else { // r = g = b = 0 // s = 0, v is undefined this.s = 0; this.h = 0; return; } if ( delta == 0 ) { h = 0; return; } if ( r == max ) { this.h = ( g - b ) / delta; // between yellow<SUF> } else if ( g == max ) { this.h = 2 + ( b - r ) / delta; // between cyan & yellow } else { this.h = 4 + ( r - g ) / delta; // between magenta & cyan } this.h *= 60; // degrees if ( this.h < 0 ) { this.h += 360; } } /** * Converts the HSV colorspace into the RGB colorspace. This private method works exclusively with internal variables * and does not return anything. * * @param h * Hue * @param s * Saturation * @param v * Value (Brightness) */ private void HSVtoRGB( float h, float s, float v ) { int i; float f; float p; float q; float t; if ( s == 0 ) { // achromatic (grey) this.r = v; this.g = v; this.b = v; return; } h /= 60; // sector 0 to 5 i = (int) Math.floor( h ); f = h - i; // factorial part of h p = v * ( 1 - s ); q = v * ( 1 - s * f ); t = v * ( 1 - s * ( 1 - f ) ); switch ( i ) { case 0: this.r = v; this.g = t; this.b = p; break; case 1: this.r = q; this.g = v; this.b = p; break; case 2: this.r = p; this.g = v; this.b = t; break; case 3: this.r = p; this.g = q; this.b = v; break; case 4: this.r = t; this.g = p; this.b = v; break; default: // case 5: this.r = v; this.g = p; this.b = q; break; } } /** * A helper function to determine the largest value between the three inputs. * * @param a * First value * @param b * Second value * @param c * Third value * @return The value of the largest of the inputs. */ private float MAX( float a, float b, float c ) { float max = Integer.MIN_VALUE; if ( a > max ) { max = a; } if ( b > max ) { max = b; } if ( c > max ) { max = c; } return max; } /** * A helper function to determine the smallest value between the three inputs. * * @param a * First value * @param b * Second value * @param c * Third value * @return The value of the smallest of the inputs. */ private float MIN( float a, float b, float c ) { float min = Integer.MAX_VALUE; if ( a < min ) { min = a; } if ( b < min ) { min = b; } if ( c < min ) { min = c; } return min; } }
121471_30
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2021 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.trans.steps.denormaliser; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueDataUtil; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.core.row.value.ValueMetaDate; import org.pentaho.di.core.row.value.ValueMetaInteger; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Denormalises data based on key-value pairs * * @author Matt * @since 17-jan-2006 */ public class Denormaliser extends BaseStep implements StepInterface { private static Class<?> PKG = DenormaliserMeta.class; // for i18n purposes, needed by Translator2!! private DenormaliserMeta meta; private DenormaliserData data; private boolean allNullsAreZero = false; private boolean minNullIsValued = false; private Map<String, ValueMetaInterface> conversionMetaCache = new HashMap<String, ValueMetaInterface>(); public Denormaliser( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans ) { super( stepMeta, stepDataInterface, copyNr, transMeta, trans ); meta = (DenormaliserMeta) getStepMeta().getStepMetaInterface(); data = (DenormaliserData) stepDataInterface; } @Override public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException { Object[] r = getRow(); // get row! if ( r == null ) { // no more input to be expected... handleLastRow(); setOutputDone(); return false; } if ( first ) { // perform all allocations if ( !processFirstRow() ) { // we failed on first row.... return false; } newGroup(); // Create a new result row (init) deNormalise( data.inputRowMeta, r ); data.previous = r; // copy the row to previous // we don't need feedback here first = false; // ok, we done with first row return true; } if ( !sameGroup( data.inputRowMeta, data.previous, r ) ) { Object[] outputRowData = buildResult( data.inputRowMeta, data.previous ); putRow( data.outputRowMeta, outputRowData ); // copy row to possible alternate rowset(s). newGroup(); // Create a new group aggregate (init) deNormalise( data.inputRowMeta, r ); } else { deNormalise( data.inputRowMeta, r ); } data.previous = r; if ( checkFeedback( getLinesRead() ) ) { if ( log.isBasic() ) { logBasic( BaseMessages.getString( PKG, "Denormaliser.Log.LineNumber" ) + getLinesRead() ); } } return true; } private boolean processFirstRow() throws KettleStepException { String val = getVariable( Const.KETTLE_AGGREGATION_ALL_NULLS_ARE_ZERO, "N" ); this.allNullsAreZero = ValueMetaBase.convertStringToBoolean( val ); val = getVariable( Const.KETTLE_AGGREGATION_MIN_NULL_IS_VALUED, "N" ); this.minNullIsValued = ValueMetaBase.convertStringToBoolean( val ); data.inputRowMeta = getInputRowMeta(); data.outputRowMeta = data.inputRowMeta.clone(); meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore ); data.keyFieldNr = data.inputRowMeta.indexOfValue( meta.getKeyField() ); if ( data.keyFieldNr < 0 ) { logError( BaseMessages.getString( PKG, "Denormaliser.Log.KeyFieldNotFound", meta.getKeyField() ) ); setErrors( 1 ); stopAll(); return false; } Map<Integer, Integer> subjects = new Hashtable<Integer, Integer>(); data.fieldNameIndex = new int[meta.getDenormaliserTargetField().length]; for ( int i = 0; i < meta.getDenormaliserTargetField().length; i++ ) { DenormaliserTargetField field = meta.getDenormaliserTargetField()[i]; int idx = data.inputRowMeta.indexOfValue( field.getFieldName() ); if ( idx < 0 ) { logError( BaseMessages.getString( PKG, "Denormaliser.Log.UnpivotFieldNotFound", field.getFieldName() ) ); setErrors( 1 ); stopAll(); return false; } data.fieldNameIndex[i] = idx; subjects.put( Integer.valueOf( idx ), Integer.valueOf( idx ) ); // See if by accident, the value fieldname isn't the same as the key fieldname. // This is not supported of-course and given the complexity of the step, you can miss: if ( data.fieldNameIndex[i] == data.keyFieldNr ) { logError( BaseMessages.getString( PKG, "Denormaliser.Log.ValueFieldSameAsKeyField", field.getFieldName() ) ); setErrors( 1 ); stopAll(); return false; } // Fill a hashtable with the key strings and the position(s) of the field(s) in the row to take. // Store the indexes in a List so that we can accommodate multiple key/value pairs... // String keyValue = environmentSubstitute( field.getKeyValue() ); List<Integer> indexes = data.keyValue.get( keyValue ); if ( indexes == null ) { indexes = new ArrayList<Integer>( 2 ); } indexes.add( Integer.valueOf( i ) ); // Add the index to the list... data.keyValue.put( keyValue, indexes ); // store the list } Set<Integer> subjectSet = subjects.keySet(); data.fieldNrs = subjectSet.toArray( new Integer[subjectSet.size()] ); data.groupnrs = new int[meta.getGroupField().length]; for ( int i = 0; i < meta.getGroupField().length; i++ ) { data.groupnrs[i] = data.inputRowMeta.indexOfValue( meta.getGroupField()[i] ); if ( data.groupnrs[i] < 0 ) { logError( BaseMessages.getString( PKG, "Denormaliser.Log.GroupingFieldNotFound", meta.getGroupField()[i] ) ); setErrors( 1 ); stopAll(); return false; } } List<Integer> removeList = new ArrayList<Integer>(); removeList.add( Integer.valueOf( data.keyFieldNr ) ); for ( int i = 0; i < data.fieldNrs.length; i++ ) { removeList.add( data.fieldNrs[i] ); } Collections.sort( removeList ); data.removeNrs = new int[removeList.size()]; for ( int i = 0; i < removeList.size(); i++ ) { data.removeNrs[i] = removeList.get( i ); } return true; } private void handleLastRow() throws KettleException { // Don't forget the last set of rows... if ( data.previous != null ) { // deNormalise(data.previous); --> That would over-do it. // Object[] outputRowData = buildResult( data.inputRowMeta, data.previous ); putRow( data.outputRowMeta, outputRowData ); } } /** * Used for junits in DenormaliserAggregationsTest * * @param rowMeta * @param rowData * @return * @throws KettleValueException */ Object[] buildResult( RowMetaInterface rowMeta, Object[] rowData ) throws KettleValueException { // Deleting objects: we need to create a new object array // It's useless to call RowDataUtil.resizeArray // Object[] outputRowData = RowDataUtil.allocateRowData( data.outputRowMeta.size() ); int outputIndex = 0; // Copy the data from the incoming row, but remove the unwanted fields in the same loop... // int removeIndex = 0; for ( int i = 0; i < rowMeta.size(); i++ ) { if ( removeIndex < data.removeNrs.length && i == data.removeNrs[removeIndex] ) { removeIndex++; } else { outputRowData[outputIndex++] = rowData[i]; } } // Add the unpivoted fields... // for ( int i = 0; i < data.targetResult.length; i++ ) { Object resultValue = data.targetResult[i]; DenormaliserTargetField field = meta.getDenormaliserTargetField()[i]; switch ( field.getTargetAggregationType() ) { case DenormaliserTargetField.TYPE_AGGR_AVERAGE: long count = data.counters[i]; Object sum = data.sum[i]; if ( count > 0 ) { if ( sum instanceof Long ) { resultValue = (Long) sum / count; } else if ( sum instanceof Double ) { resultValue = (Double) sum / count; } else if ( sum instanceof BigDecimal ) { resultValue = ( (BigDecimal) sum ).divide( new BigDecimal( count ) ); } else { resultValue = null; // TODO: perhaps throw an exception here?< } } break; case DenormaliserTargetField.TYPE_AGGR_COUNT_ALL: if ( resultValue == null ) { resultValue = Long.valueOf( 0 ); } if ( field.getTargetType() != ValueMetaInterface.TYPE_INTEGER ) { resultValue = data.outputRowMeta.getValueMeta( outputIndex ).convertData( new ValueMetaInteger( "num_values_aggregation" ), resultValue ); } break; default: break; } if ( resultValue == null && allNullsAreZero ) { // PDI-9662 seems all rows for min function was nulls... resultValue = getZero( outputIndex ); } outputRowData[outputIndex++] = resultValue; } return outputRowData; } private Object getZero( int field ) throws KettleValueException { ValueMetaInterface vm = data.outputRowMeta.getValueMeta( field ); return ValueDataUtil.getZeroForValueMetaType( vm ); } // Is the row r of the same group as previous? private boolean sameGroup( RowMetaInterface rowMeta, Object[] previous, Object[] rowData ) throws KettleValueException { return rowMeta.compare( previous, rowData, data.groupnrs ) == 0; } /** * Initialize a new group... * * @throws KettleException */ private void newGroup( ) throws KettleException { // There is no need anymore to take care of the meta-data. // That is done once in DenormaliserMeta.getFields() // data.targetResult = new Object[meta.getDenormaliserTargetFields().length]; DenormaliserTargetField[] fields = meta.getDenormaliserTargetField(); for ( int i = 0; i < fields.length; i++ ) { data.counters[i] = 0L; // set to 0 data.sum[i] = null; } } /** * This method de-normalizes a single key-value pair. It looks up the key and determines the value name to store it * in. It converts it to the right type and stores it in the result row. * * Used for junits in DenormaliserAggregationsTest * * @param r * @throws KettleValueException */ void deNormalise( RowMetaInterface rowMeta, Object[] rowData ) throws KettleValueException { ValueMetaInterface valueMeta = rowMeta.getValueMeta( data.keyFieldNr ); Object valueData = rowData[data.keyFieldNr]; String key = valueMeta.getCompatibleString( valueData ); if ( Utils.isEmpty( key ) ) { return; } // Get all the indexes for the given key value... // List<Integer> indexes = data.keyValue.get( key ); if ( indexes == null ) { // otherwise we're not interested. return; } for ( Integer keyNr : indexes ) { if ( keyNr == null ) { continue; } // keyNr is the field in DenormaliserTargetField[] // int idx = keyNr.intValue(); DenormaliserTargetField field = meta.getDenormaliserTargetField()[idx]; // This is the value we need to de-normalise, convert, aggregate. // ValueMetaInterface sourceMeta = rowMeta.getValueMeta( data.fieldNameIndex[idx] ); Object sourceData = rowData[data.fieldNameIndex[idx]]; if ( field.getTargetNullString() != null && field.getTargetNullString().length() > 0 && sourceData != null ) { //We have a "null if" value to check against. To check for equality we must convert the sourceData value to a // string ValueMetaInterface stringMeta = new ValueMetaBase( "stringSource", ValueMetaInterface.TYPE_STRING ); if ( sourceMeta.getConversionMask() != null ) { stringMeta.setConversionMask( sourceMeta.getConversionMask() ); } Object stringValue = stringMeta.convertData( sourceMeta, sourceData ); if ( field.getTargetNullString().equalsIgnoreCase( stringValue.toString() ) ) { sourceData = null; } } Object targetData; // What is the target value metadata?? // ValueMetaInterface targetMeta = data.outputRowMeta.getValueMeta( data.inputRowMeta.size() - data.removeNrs.length + idx ); // What was the previous target in the result row? // Object prevTargetData = data.targetResult[idx]; // clone source meta as it can be used by other steps ans set conversion meta // to convert date to target format // See PDI-4910 for details ValueMetaInterface origSourceMeta = sourceMeta; if ( targetMeta.isDate() ) { sourceMeta = origSourceMeta.clone(); sourceMeta.setConversionMetadata( getConversionMeta( field.getTargetFormat() ) ); } switch ( field.getTargetAggregationType() ) { case DenormaliserTargetField.TYPE_AGGR_SUM: targetData = targetMeta.convertData( sourceMeta, sourceData ); if ( prevTargetData != null ) { prevTargetData = ValueDataUtil.sum( targetMeta, prevTargetData, targetMeta, targetData ); } else { prevTargetData = targetData; } break; case DenormaliserTargetField.TYPE_AGGR_MIN: if ( sourceData == null && !minNullIsValued ) { // PDI-9662 do not compare null break; } if ( ( prevTargetData == null && !minNullIsValued ) || sourceMeta.compare( sourceData, targetMeta, prevTargetData ) < 0 ) { prevTargetData = targetMeta.convertData( sourceMeta, sourceData ); } break; case DenormaliserTargetField.TYPE_AGGR_MAX: if ( sourceMeta.compare( sourceData, targetMeta, prevTargetData ) > 0 ) { prevTargetData = targetMeta.convertData( sourceMeta, sourceData ); } break; case DenormaliserTargetField.TYPE_AGGR_COUNT_ALL: prevTargetData = ++data.counters[idx]; break; case DenormaliserTargetField.TYPE_AGGR_AVERAGE: targetData = targetMeta.convertData( sourceMeta, sourceData ); if ( !sourceMeta.isNull( sourceData ) ) { prevTargetData = data.counters[idx]++; if ( data.sum[idx] == null ) { data.sum[idx] = targetData; } else { data.sum[idx] = ValueDataUtil.plus( targetMeta, data.sum[idx], targetMeta, targetData ); } // data.sum[idx] = (Integer)data.sum[idx] + (Integer)sourceData; } break; case DenormaliserTargetField.TYPE_AGGR_CONCAT_COMMA: String separator = ","; targetData = targetMeta.convertData( sourceMeta, sourceData ); if ( prevTargetData != null ) { prevTargetData = prevTargetData + separator + targetData; } else { prevTargetData = targetData; } break; case DenormaliserTargetField.TYPE_AGGR_NONE: default: prevTargetData = targetMeta.convertData( sourceMeta, sourceData ); // Overwrite the previous break; } // Update the result row too // data.targetResult[idx] = prevTargetData; } } @Override public boolean init( StepMetaInterface smi, StepDataInterface sdi ) { meta = (DenormaliserMeta) smi; data = (DenormaliserData) sdi; if ( super.init( smi, sdi ) ) { data.counters = new long[meta.getDenormaliserTargetField().length]; data.sum = new Object[meta.getDenormaliserTargetField().length]; return true; } return false; } @Override public void batchComplete() throws KettleException { handleLastRow(); data.previous = null; } /** * Get the metadata used for conversion to date format See related PDI-4019 * * @param mask * @return */ private ValueMetaInterface getConversionMeta( String mask ) { ValueMetaInterface meta = null; if ( !Utils.isEmpty( mask ) ) { meta = conversionMetaCache.get( mask ); if ( meta == null ) { meta = new ValueMetaDate(); meta.setConversionMask( mask ); conversionMetaCache.put( mask, meta ); } } return meta; } /** * Used for junits in DenormaliserAggregationsTest * * @param allNullsAreZero * the allNullsAreZero to set */ void setAllNullsAreZero( boolean allNullsAreZero ) { this.allNullsAreZero = allNullsAreZero; } /** * Used for junits in DenormaliserAggregationsTest * * @param minNullIsValued * the minNullIsValued to set */ void setMinNullIsValued( boolean minNullIsValued ) { this.minNullIsValued = minNullIsValued; } }
pentaho/pentaho-kettle
engine/src/main/java/org/pentaho/di/trans/steps/denormaliser/Denormaliser.java
5,533
// That is done once in DenormaliserMeta.getFields()
line_comment
nl
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2021 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.trans.steps.denormaliser; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; import org.pentaho.di.core.Const; import org.pentaho.di.core.util.Utils; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueDataUtil; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.row.value.ValueMetaBase; import org.pentaho.di.core.row.value.ValueMetaDate; import org.pentaho.di.core.row.value.ValueMetaInteger; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Denormalises data based on key-value pairs * * @author Matt * @since 17-jan-2006 */ public class Denormaliser extends BaseStep implements StepInterface { private static Class<?> PKG = DenormaliserMeta.class; // for i18n purposes, needed by Translator2!! private DenormaliserMeta meta; private DenormaliserData data; private boolean allNullsAreZero = false; private boolean minNullIsValued = false; private Map<String, ValueMetaInterface> conversionMetaCache = new HashMap<String, ValueMetaInterface>(); public Denormaliser( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans ) { super( stepMeta, stepDataInterface, copyNr, transMeta, trans ); meta = (DenormaliserMeta) getStepMeta().getStepMetaInterface(); data = (DenormaliserData) stepDataInterface; } @Override public boolean processRow( StepMetaInterface smi, StepDataInterface sdi ) throws KettleException { Object[] r = getRow(); // get row! if ( r == null ) { // no more input to be expected... handleLastRow(); setOutputDone(); return false; } if ( first ) { // perform all allocations if ( !processFirstRow() ) { // we failed on first row.... return false; } newGroup(); // Create a new result row (init) deNormalise( data.inputRowMeta, r ); data.previous = r; // copy the row to previous // we don't need feedback here first = false; // ok, we done with first row return true; } if ( !sameGroup( data.inputRowMeta, data.previous, r ) ) { Object[] outputRowData = buildResult( data.inputRowMeta, data.previous ); putRow( data.outputRowMeta, outputRowData ); // copy row to possible alternate rowset(s). newGroup(); // Create a new group aggregate (init) deNormalise( data.inputRowMeta, r ); } else { deNormalise( data.inputRowMeta, r ); } data.previous = r; if ( checkFeedback( getLinesRead() ) ) { if ( log.isBasic() ) { logBasic( BaseMessages.getString( PKG, "Denormaliser.Log.LineNumber" ) + getLinesRead() ); } } return true; } private boolean processFirstRow() throws KettleStepException { String val = getVariable( Const.KETTLE_AGGREGATION_ALL_NULLS_ARE_ZERO, "N" ); this.allNullsAreZero = ValueMetaBase.convertStringToBoolean( val ); val = getVariable( Const.KETTLE_AGGREGATION_MIN_NULL_IS_VALUED, "N" ); this.minNullIsValued = ValueMetaBase.convertStringToBoolean( val ); data.inputRowMeta = getInputRowMeta(); data.outputRowMeta = data.inputRowMeta.clone(); meta.getFields( data.outputRowMeta, getStepname(), null, null, this, repository, metaStore ); data.keyFieldNr = data.inputRowMeta.indexOfValue( meta.getKeyField() ); if ( data.keyFieldNr < 0 ) { logError( BaseMessages.getString( PKG, "Denormaliser.Log.KeyFieldNotFound", meta.getKeyField() ) ); setErrors( 1 ); stopAll(); return false; } Map<Integer, Integer> subjects = new Hashtable<Integer, Integer>(); data.fieldNameIndex = new int[meta.getDenormaliserTargetField().length]; for ( int i = 0; i < meta.getDenormaliserTargetField().length; i++ ) { DenormaliserTargetField field = meta.getDenormaliserTargetField()[i]; int idx = data.inputRowMeta.indexOfValue( field.getFieldName() ); if ( idx < 0 ) { logError( BaseMessages.getString( PKG, "Denormaliser.Log.UnpivotFieldNotFound", field.getFieldName() ) ); setErrors( 1 ); stopAll(); return false; } data.fieldNameIndex[i] = idx; subjects.put( Integer.valueOf( idx ), Integer.valueOf( idx ) ); // See if by accident, the value fieldname isn't the same as the key fieldname. // This is not supported of-course and given the complexity of the step, you can miss: if ( data.fieldNameIndex[i] == data.keyFieldNr ) { logError( BaseMessages.getString( PKG, "Denormaliser.Log.ValueFieldSameAsKeyField", field.getFieldName() ) ); setErrors( 1 ); stopAll(); return false; } // Fill a hashtable with the key strings and the position(s) of the field(s) in the row to take. // Store the indexes in a List so that we can accommodate multiple key/value pairs... // String keyValue = environmentSubstitute( field.getKeyValue() ); List<Integer> indexes = data.keyValue.get( keyValue ); if ( indexes == null ) { indexes = new ArrayList<Integer>( 2 ); } indexes.add( Integer.valueOf( i ) ); // Add the index to the list... data.keyValue.put( keyValue, indexes ); // store the list } Set<Integer> subjectSet = subjects.keySet(); data.fieldNrs = subjectSet.toArray( new Integer[subjectSet.size()] ); data.groupnrs = new int[meta.getGroupField().length]; for ( int i = 0; i < meta.getGroupField().length; i++ ) { data.groupnrs[i] = data.inputRowMeta.indexOfValue( meta.getGroupField()[i] ); if ( data.groupnrs[i] < 0 ) { logError( BaseMessages.getString( PKG, "Denormaliser.Log.GroupingFieldNotFound", meta.getGroupField()[i] ) ); setErrors( 1 ); stopAll(); return false; } } List<Integer> removeList = new ArrayList<Integer>(); removeList.add( Integer.valueOf( data.keyFieldNr ) ); for ( int i = 0; i < data.fieldNrs.length; i++ ) { removeList.add( data.fieldNrs[i] ); } Collections.sort( removeList ); data.removeNrs = new int[removeList.size()]; for ( int i = 0; i < removeList.size(); i++ ) { data.removeNrs[i] = removeList.get( i ); } return true; } private void handleLastRow() throws KettleException { // Don't forget the last set of rows... if ( data.previous != null ) { // deNormalise(data.previous); --> That would over-do it. // Object[] outputRowData = buildResult( data.inputRowMeta, data.previous ); putRow( data.outputRowMeta, outputRowData ); } } /** * Used for junits in DenormaliserAggregationsTest * * @param rowMeta * @param rowData * @return * @throws KettleValueException */ Object[] buildResult( RowMetaInterface rowMeta, Object[] rowData ) throws KettleValueException { // Deleting objects: we need to create a new object array // It's useless to call RowDataUtil.resizeArray // Object[] outputRowData = RowDataUtil.allocateRowData( data.outputRowMeta.size() ); int outputIndex = 0; // Copy the data from the incoming row, but remove the unwanted fields in the same loop... // int removeIndex = 0; for ( int i = 0; i < rowMeta.size(); i++ ) { if ( removeIndex < data.removeNrs.length && i == data.removeNrs[removeIndex] ) { removeIndex++; } else { outputRowData[outputIndex++] = rowData[i]; } } // Add the unpivoted fields... // for ( int i = 0; i < data.targetResult.length; i++ ) { Object resultValue = data.targetResult[i]; DenormaliserTargetField field = meta.getDenormaliserTargetField()[i]; switch ( field.getTargetAggregationType() ) { case DenormaliserTargetField.TYPE_AGGR_AVERAGE: long count = data.counters[i]; Object sum = data.sum[i]; if ( count > 0 ) { if ( sum instanceof Long ) { resultValue = (Long) sum / count; } else if ( sum instanceof Double ) { resultValue = (Double) sum / count; } else if ( sum instanceof BigDecimal ) { resultValue = ( (BigDecimal) sum ).divide( new BigDecimal( count ) ); } else { resultValue = null; // TODO: perhaps throw an exception here?< } } break; case DenormaliserTargetField.TYPE_AGGR_COUNT_ALL: if ( resultValue == null ) { resultValue = Long.valueOf( 0 ); } if ( field.getTargetType() != ValueMetaInterface.TYPE_INTEGER ) { resultValue = data.outputRowMeta.getValueMeta( outputIndex ).convertData( new ValueMetaInteger( "num_values_aggregation" ), resultValue ); } break; default: break; } if ( resultValue == null && allNullsAreZero ) { // PDI-9662 seems all rows for min function was nulls... resultValue = getZero( outputIndex ); } outputRowData[outputIndex++] = resultValue; } return outputRowData; } private Object getZero( int field ) throws KettleValueException { ValueMetaInterface vm = data.outputRowMeta.getValueMeta( field ); return ValueDataUtil.getZeroForValueMetaType( vm ); } // Is the row r of the same group as previous? private boolean sameGroup( RowMetaInterface rowMeta, Object[] previous, Object[] rowData ) throws KettleValueException { return rowMeta.compare( previous, rowData, data.groupnrs ) == 0; } /** * Initialize a new group... * * @throws KettleException */ private void newGroup( ) throws KettleException { // There is no need anymore to take care of the meta-data. // That is<SUF> // data.targetResult = new Object[meta.getDenormaliserTargetFields().length]; DenormaliserTargetField[] fields = meta.getDenormaliserTargetField(); for ( int i = 0; i < fields.length; i++ ) { data.counters[i] = 0L; // set to 0 data.sum[i] = null; } } /** * This method de-normalizes a single key-value pair. It looks up the key and determines the value name to store it * in. It converts it to the right type and stores it in the result row. * * Used for junits in DenormaliserAggregationsTest * * @param r * @throws KettleValueException */ void deNormalise( RowMetaInterface rowMeta, Object[] rowData ) throws KettleValueException { ValueMetaInterface valueMeta = rowMeta.getValueMeta( data.keyFieldNr ); Object valueData = rowData[data.keyFieldNr]; String key = valueMeta.getCompatibleString( valueData ); if ( Utils.isEmpty( key ) ) { return; } // Get all the indexes for the given key value... // List<Integer> indexes = data.keyValue.get( key ); if ( indexes == null ) { // otherwise we're not interested. return; } for ( Integer keyNr : indexes ) { if ( keyNr == null ) { continue; } // keyNr is the field in DenormaliserTargetField[] // int idx = keyNr.intValue(); DenormaliserTargetField field = meta.getDenormaliserTargetField()[idx]; // This is the value we need to de-normalise, convert, aggregate. // ValueMetaInterface sourceMeta = rowMeta.getValueMeta( data.fieldNameIndex[idx] ); Object sourceData = rowData[data.fieldNameIndex[idx]]; if ( field.getTargetNullString() != null && field.getTargetNullString().length() > 0 && sourceData != null ) { //We have a "null if" value to check against. To check for equality we must convert the sourceData value to a // string ValueMetaInterface stringMeta = new ValueMetaBase( "stringSource", ValueMetaInterface.TYPE_STRING ); if ( sourceMeta.getConversionMask() != null ) { stringMeta.setConversionMask( sourceMeta.getConversionMask() ); } Object stringValue = stringMeta.convertData( sourceMeta, sourceData ); if ( field.getTargetNullString().equalsIgnoreCase( stringValue.toString() ) ) { sourceData = null; } } Object targetData; // What is the target value metadata?? // ValueMetaInterface targetMeta = data.outputRowMeta.getValueMeta( data.inputRowMeta.size() - data.removeNrs.length + idx ); // What was the previous target in the result row? // Object prevTargetData = data.targetResult[idx]; // clone source meta as it can be used by other steps ans set conversion meta // to convert date to target format // See PDI-4910 for details ValueMetaInterface origSourceMeta = sourceMeta; if ( targetMeta.isDate() ) { sourceMeta = origSourceMeta.clone(); sourceMeta.setConversionMetadata( getConversionMeta( field.getTargetFormat() ) ); } switch ( field.getTargetAggregationType() ) { case DenormaliserTargetField.TYPE_AGGR_SUM: targetData = targetMeta.convertData( sourceMeta, sourceData ); if ( prevTargetData != null ) { prevTargetData = ValueDataUtil.sum( targetMeta, prevTargetData, targetMeta, targetData ); } else { prevTargetData = targetData; } break; case DenormaliserTargetField.TYPE_AGGR_MIN: if ( sourceData == null && !minNullIsValued ) { // PDI-9662 do not compare null break; } if ( ( prevTargetData == null && !minNullIsValued ) || sourceMeta.compare( sourceData, targetMeta, prevTargetData ) < 0 ) { prevTargetData = targetMeta.convertData( sourceMeta, sourceData ); } break; case DenormaliserTargetField.TYPE_AGGR_MAX: if ( sourceMeta.compare( sourceData, targetMeta, prevTargetData ) > 0 ) { prevTargetData = targetMeta.convertData( sourceMeta, sourceData ); } break; case DenormaliserTargetField.TYPE_AGGR_COUNT_ALL: prevTargetData = ++data.counters[idx]; break; case DenormaliserTargetField.TYPE_AGGR_AVERAGE: targetData = targetMeta.convertData( sourceMeta, sourceData ); if ( !sourceMeta.isNull( sourceData ) ) { prevTargetData = data.counters[idx]++; if ( data.sum[idx] == null ) { data.sum[idx] = targetData; } else { data.sum[idx] = ValueDataUtil.plus( targetMeta, data.sum[idx], targetMeta, targetData ); } // data.sum[idx] = (Integer)data.sum[idx] + (Integer)sourceData; } break; case DenormaliserTargetField.TYPE_AGGR_CONCAT_COMMA: String separator = ","; targetData = targetMeta.convertData( sourceMeta, sourceData ); if ( prevTargetData != null ) { prevTargetData = prevTargetData + separator + targetData; } else { prevTargetData = targetData; } break; case DenormaliserTargetField.TYPE_AGGR_NONE: default: prevTargetData = targetMeta.convertData( sourceMeta, sourceData ); // Overwrite the previous break; } // Update the result row too // data.targetResult[idx] = prevTargetData; } } @Override public boolean init( StepMetaInterface smi, StepDataInterface sdi ) { meta = (DenormaliserMeta) smi; data = (DenormaliserData) sdi; if ( super.init( smi, sdi ) ) { data.counters = new long[meta.getDenormaliserTargetField().length]; data.sum = new Object[meta.getDenormaliserTargetField().length]; return true; } return false; } @Override public void batchComplete() throws KettleException { handleLastRow(); data.previous = null; } /** * Get the metadata used for conversion to date format See related PDI-4019 * * @param mask * @return */ private ValueMetaInterface getConversionMeta( String mask ) { ValueMetaInterface meta = null; if ( !Utils.isEmpty( mask ) ) { meta = conversionMetaCache.get( mask ); if ( meta == null ) { meta = new ValueMetaDate(); meta.setConversionMask( mask ); conversionMetaCache.put( mask, meta ); } } return meta; } /** * Used for junits in DenormaliserAggregationsTest * * @param allNullsAreZero * the allNullsAreZero to set */ void setAllNullsAreZero( boolean allNullsAreZero ) { this.allNullsAreZero = allNullsAreZero; } /** * Used for junits in DenormaliserAggregationsTest * * @param minNullIsValued * the minNullIsValued to set */ void setMinNullIsValued( boolean minNullIsValued ) { this.minNullIsValued = minNullIsValued; } }
164456_62
// IfStatement.java. // Copyright (C) 2004 Naom Nisan, Ziv Balshai, Amir Levy. // See full copyright license terms in file ../GPL.txt package SFE.Compiler; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.TreeMap; import SFE.Compiler.Operators.NotEqualOperator; import SFE.Compiler.Operators.PlusOperator; import SFE.Compiler.Operators.TimesOperator; import SFE.Compiler.Operators.UnaryMinusOperator; import SFE.Compiler.PolynomialExpression.PolynomialTerm; /** * A class for representing if statement that can be defined in the program. */ public class IfStatement extends Statement implements Optimizable { // ~ Instance fields // -------------------------------------------------------- // data members /* * Holds the condition of the if statement. */ private Expression condition; /* * Holds a variable name guaranteed not to collide with program structures */ private String nameOfCondition; /* * Holds the block of the if statement. */ private Statement thenBlock; /* * Holds the else block of the if statement. */ private Statement elseBlock; // ~ Constructors // ----------------------------------------------------------- /** * Construct a new if statement. * * @param condition * the condition of the if statement. * @param thenBlock * the block of the if statement. * @param elseBlock * the block of the else statement. */ public IfStatement(Expression condition, Statement thenBlock, Statement elseBlock, String nameOfCondition) { this.condition = condition; this.thenBlock = thenBlock; this.elseBlock = elseBlock; this.nameOfCondition = nameOfCondition; } // ~ Methods // ---------------------------------------------------------------- /** * Unique vars transformations. public Statement uniqueVars() { //Uniquify * the condition first. Though, it will do nothing at this point. condition * = condition.changeReference(Function.getVars()); * * if (elseBlock == null){ throw new RuntimeException("Assertion error"); } * * if (condition.size() != 1){ throw new * RuntimeException("Error: condition was not a boolean value"); } * * BlockStatement newBlock = new BlockStatement(); * * //start new scope Function.pushScope(); * * //unique vars transformations on the if block * newBlock.addStatement(thenBlock.uniqueVars()); * * //end the scope Map<String, LvalExpression> thenScope = * Function.popScope(); * * //start new scope Function.pushScope(); * * //unique vars transformations on the if block * newBlock.addStatement(elseBlock.uniqueVars()); * * //end the scope Map<String, LvalExpression> elseScope = * Function.popScope(); * * //Get the scope holding the if statement VariableLUT beforeIf = * Function.getVars(); * * HashSet<String> ConflictVariables = new HashSet(); ArrayList<String> * ConflictVariablesSorted = new ArrayList(); for(String lvalName : * thenScope.keySet()){ LvalExpression lvalBeforeIf = * Function.getVars().getVar(lvalName); if (lvalBeforeIf != null){ * ConflictVariables.add(lvalName); ConflictVariablesSorted.add(lvalName); } * } for(String lvalName : elseScope.keySet()){ if * (ConflictVariables.contains(lvalName)){ continue; } LvalExpression * lvalBeforeIf = Function.getVars().getVar(lvalName); if (lvalBeforeIf != * null){ ConflictVariables.add(lvalName); * ConflictVariablesSorted.add(lvalName); } } * * Collections.sort(ConflictVariablesSorted); * * for(String lvalName : ConflictVariablesSorted){ LvalExpression valueTrue, * valueFalse, valueMostRecent; { //lval before if block LvalExpression * lvalBeforeIf = Function.getVars().getVar(lvalName); if * (lvalBeforeIf.size() != 1){ throw new * RuntimeException("Error: non primitive type in if statement evaluation"); * } LvalExpression lvalInThen = (LvalExpression) thenScope.get(lvalName); * if (lvalInThen != null){ //The variable is overwritten in the then block. * LvalExpression lvalInElse = (LvalExpression) elseScope.get(lvalName); if * (lvalInElse != null){ //The variable is overwritten in the else block * valueTrue = lvalInThen; valueFalse = lvalInElse; valueMostRecent = * lvalInElse; } else { valueTrue = lvalInThen; valueFalse = lvalBeforeIf; * valueMostRecent = lvalInThen; } } else { //The variable is not * overwritten in the then block. LvalExpression lvalInElse = * (LvalExpression) elseScope.get(lvalName); //The variable is overwritten * in the else block. valueTrue = lvalBeforeIf; valueFalse = lvalInElse; * valueMostRecent = lvalInElse; } * * if (valueTrue.size()!=1 || valueFalse.size()!=1){ throw new * RuntimeException("Error: non primitive type in if statement evaluation"); * } } * * //valueTrue * condition + valueFalse + valueFalse * (-1 * condition) = * x*c + y*(1-c) OperationExpression mux = FloatExpressions.mux(condition, * valueTrue, valueFalse); * * //We can't call updateVars on this created assignment, because the right * hand side uses variables inside the //if scope, which * assignmentStatement.updateVars() will mistakenly redirect to the * variables on the outer scope! Function.addVar(valueMostRecent); * valueMostRecent = Function.getVar(valueMostRecent); AssignmentStatement * newAs = new AssignmentStatement(valueMostRecent,mux); //perform the mux * newAs.dedicateAssignment(); newAs.setOutputLine(Program.getLineNumber()); * //Set the line number of the as newBlock.addStatement(newAs); //Add it to * the reult } * * return newBlock; } */ /** * Transforms this multibit AssignmentStatement into singlebit statements * and returns the result. * * @param obj * not needed (null). * @return a BlockStatement containing the result statements. */ public BlockStatement toSLPTCircuit(Object obj) { BlockStatement result = new BlockStatement(); // create a temp var that holds the condition result LvalExpression condition_asBoolean = Function.addTempLocalVar( "conditionResult" + nameOfCondition, new BooleanType()); // create the assignment statement that assings the result AssignmentStatement conditionResultAs = new AssignmentStatement( condition_asBoolean, new BinaryOpExpression( new NotEqualOperator(), condition, new BooleanConstant( false))); // evaluate the condition and stores it in the conditionResult result.addStatement(conditionResultAs.toSLPTCircuit(null)); condition = condition_asBoolean; // .bitAt(0); // Defer this processing until toAssignments. // thenBlock = thenBlock.toSLPTCircuit(null); // elseBlock = elseBlock.toSLPTCircuit(null); result.addStatement(this); return result; } /** * Returns a replica of this IfStatement. * * @return a replica of this IfStatement. */ public Statement duplicate() { return new IfStatement(condition.duplicate(), thenBlock.duplicate(), elseBlock.duplicate(), nameOfCondition); } /** * Returns a string representation of this IfStatement. * * @return a string representation of this IfStatement. */ public String toString() { return "IF (" + condition + ")\nTHEN\n" + thenBlock + "ELSE\n" + elseBlock; } // ~ Static fields/initializers // --------------------------------------------- public void optimize(Optimization job) { // This optimization is only done in the high level stage, because // uniqueVars erases if statements switch (job) { case RENUMBER_ASSIGNMENTS: // Allow the if and else block to receive numberings. ((Optimizable) thenBlock) .optimize(Optimization.RENUMBER_ASSIGNMENTS); if (elseBlock != null) ((Optimizable) elseBlock) .optimize(Optimization.RENUMBER_ASSIGNMENTS); break; case DUPLICATED_IN_FUNCTION: ((Optimizable) thenBlock) .optimize(Optimization.DUPLICATED_IN_FUNCTION); ((Optimizable) elseBlock) .optimize(Optimization.DUPLICATED_IN_FUNCTION); condition.duplicatedInFunction(); break; default: // It's potentially dangerous to perform an optimization on a system // which doesn't implement it throw new RuntimeException("Optimization not implemented: " + job); } } public void blockOptimize(BlockOptimization job, List body) { switch (job) { case DEADCODE_ELIMINATE: // Deadcode elimination currently does nothing break; default: // It's potentially dangerous if we perform an optimization and only // some parts of our system implement it. // Catch that. throw new RuntimeException("Optimization not implemented: " + job); } } public void buildUsedStatementsHash() { // Currently deadcode elimination of if statements not implemented Optimizer.putUsedStatement(this); // The if and else block are privately owned by this if, so we hide them // from the optimizer // Ensure that the condition can be evaluated Collection<LvalExpression> v = condition.getLvalExpressionInputs(); for (LvalExpression q : v) { Statement as = q.getAssigningStatement(); Optimizer.putUsedStatement(as); } } public void toAssignmentStatements(StatementBuffer statements) { condition = Function.getVar((LvalExpression) condition); BooleanConstant asConst = BooleanConstant.toBooleanConstant(condition); if (elseBlock == null) { throw new RuntimeException("Assertion error"); } // Constant condition evaluation? if (asConst != null) { if (asConst.getConst()) { thenBlock = thenBlock.toSLPTCircuit(null); thenBlock.toAssignmentStatements(statements); return; } else { elseBlock = elseBlock.toSLPTCircuit(null); elseBlock.toAssignmentStatements(statements); return; } } // so condition is an lvalue. // start new scope Function.pushScope(); // statements.pushShortCircuit((LvalExpression)condition, // IntConstant.ONE); statements.pushUncertainty(); statements.pushCondition((LvalExpression)condition, true); // toSLPT must occur here, so that the created intermediate variables // are correctly scoped thenBlock = thenBlock.toSLPTCircuit(null); // unique vars transformations on the if block thenBlock.toAssignmentStatements(statements); statements.popCondition(); // end the scope // statements.popShortCircuit(); Map<String, LvalExpression> thenScope = Function.popScope(); // start new scope Function.pushScope(); statements.pushCondition((LvalExpression)condition, false); // push the false condition here. // statements.pushShortCircuit((LvalExpression)condition, new // IntConstant(0)); // toSLPT must occur here, so that the created intermediate variables // are correctly scoped elseBlock = elseBlock.toSLPTCircuit(null); // unique vars transformations on the if block elseBlock.toAssignmentStatements(statements); statements.popCondition(); statements.popUncertainty(); // end the scope // statements.popShortCircuit(); Map<String, LvalExpression> elseScope = Function.popScope(); expandMuxStatements(condition, thenScope, elseScope, statements); } /** * Muxes the three scopes possible in an if statement together, writing * generated statements to the statement buffer. * * 1) The current scope (Function.getVars()) 2) A scope reflecting variables * generated by the end of the then block 3) A scope reflecting variables * generated by the end of the else block * * Name conflicts can occur in multiple ways, mux statements are inlined to * prevent unecessary condition variable multiplication. */ public static void expandMuxStatements(Expression condition, Map<String, LvalExpression> thenScope, Map<String, LvalExpression> elseScope, StatementBuffer statements) { // Get the scope holding the if statement VariableLUT beforeIf = Function.getVars(); HashSet<String> ConflictVariables = new HashSet(); TreeMap<Integer, String> ConflictVariablesSorted = new TreeMap(); for (LvalExpression lvalInThen : thenScope.values()) { String name = lvalInThen.getName(); LvalExpression lvalBeforeIf = Function.getVars().getVar(name); if (lvalBeforeIf != null && lvalBeforeIf.getOutputLine() != -1) { // There // is // some // amount // of // cruft // in // the // variable // lookup // table. // FIXME ConflictVariables.add(name); ConflictVariablesSorted.put((lvalInThen.getAssigningStatement()).getOutputLine(), name); } } for (LvalExpression lvalInElse : elseScope.values()) { String name = lvalInElse.getName(); if (ConflictVariables.contains(name)) { continue; } LvalExpression lvalBeforeIf = Function.getVars().getVar(name); if (lvalBeforeIf != null && lvalBeforeIf.getOutputLine() != -1) { ConflictVariables.add(name); ConflictVariablesSorted.put((lvalInElse.getAssigningStatement()).getOutputLine(), name); } } for (String lvalName : ConflictVariablesSorted.values()) { LvalExpression valueTrue, valueFalse, valueMostRecent; { // lval before if block LvalExpression lvalBeforeIf = Function.getVars().getVar( lvalName); LvalExpression lvalInThen = (LvalExpression) thenScope .get(lvalName); if (lvalInThen != null) { // The variable is overwritten in the then block. LvalExpression lvalInElse = (LvalExpression) elseScope .get(lvalName); if (lvalInElse != null) { // The variable is overwritten in the else block valueTrue = lvalInThen; valueFalse = lvalInElse; valueMostRecent = lvalInElse; } else { valueTrue = lvalInThen; valueFalse = lvalBeforeIf; valueMostRecent = lvalInThen; } } else { // The variable is not overwritten in the then block. LvalExpression lvalInElse = (LvalExpression) elseScope .get(lvalName); // The variable is overwritten in the else block. valueTrue = lvalBeforeIf; valueFalse = lvalInElse; valueMostRecent = lvalInElse; } } // valueTrue * condition + valueFalse + valueFalse * (-1 * // condition) = x*c + y*(1-c) MuxPolynomialExpression mux = null; if (AssignmentStatement.combineExpressions) { // If valueTrue or valueFalse have mux values, can we combine // expressions? Statement valueTrue_ = valueTrue.getAssigningStatement(); Statement valueFalse_ = valueFalse.getAssigningStatement(); if (valueTrue_ instanceof AssignmentStatement && !valueTrue.isReferenced()) { MuxPolynomialExpression rhs_ = MuxPolynomialExpression .toMuxExpression(((AssignmentStatement) valueTrue_) .getLHS()); if (rhs_ != null) { if (mux == null && rhs_.getValueFalse() == valueFalse) { // So mux has the form condition ? (condition2 ? // rhs_.getValueTrue() : valueFalse) : valueFalse // Hence replace mux with (c1) * (c2) ? // rhs_.getValueTrue() : valueFalse PolynomialExpression c1c2 = new PolynomialExpression(); PolynomialTerm t1 = new PolynomialTerm(); t1.addFactor((LvalExpression) condition); t1.addFactor(rhs_.getCondition()); c1c2.addMultiplesOfTerm(IntConstant.ONE, t1); LvalExpression c1c2_ = newLvalOrExisting(c1c2, valueMostRecent.getName(), statements); mux = new MuxPolynomialExpression(c1c2_, rhs_.getValueTrue(), valueFalse); // System.out.println("0"); } if (mux == null && rhs_.getValueTrue() == valueFalse) { // So mux has the form condition ? (condition2 ? // valueFalse : rhs_.getValueFalse()) : valueFalse // Hence replace mux with (c1) * (1 - c2) ? // rhs_.getValueFalse() : valueFalse PolynomialExpression cond = new PolynomialExpression(); PolynomialTerm t = new PolynomialTerm(); t.addFactor((LvalExpression) condition); { PolynomialExpression oneMinC2 = new PolynomialExpression(); PolynomialTerm one = new PolynomialTerm(); PolynomialTerm t2 = new PolynomialTerm(); t2.addFactor(rhs_.getCondition()); oneMinC2.addMultiplesOfTerm(IntConstant.ONE, one); oneMinC2.addMultiplesOfTerm( IntConstant.NEG_ONE, t2); t.addFactor(oneMinC2); } cond.addMultiplesOfTerm(IntConstant.ONE, t); LvalExpression cond_ = newLvalOrExisting(cond, valueMostRecent.getName(), statements); mux = new MuxPolynomialExpression(cond_, rhs_.getValueFalse(), valueFalse); // System.out.println("1"); } } } if (valueFalse_ instanceof AssignmentStatement && !valueFalse.isReferenced()) { MuxPolynomialExpression rhs_ = MuxPolynomialExpression .toMuxExpression(((AssignmentStatement) valueFalse_) .getLHS()); if (rhs_ != null) { if (mux == null && rhs_.getValueFalse() == valueTrue) { // So mux has the form condition ? valueTrue : // (condition2 ? rhs_.getValueTrue() : valueTrue) // So replace it with (1-c1)*(c2) ? // rhs_.getValueTrue() : valueTrue PolynomialExpression cond = new PolynomialExpression(); PolynomialTerm t = new PolynomialTerm(); { PolynomialExpression oneMinC1 = new PolynomialExpression(); PolynomialTerm one = new PolynomialTerm(); PolynomialTerm t2 = new PolynomialTerm(); t2.addFactor(condition); oneMinC1.addMultiplesOfTerm(IntConstant.ONE, one); oneMinC1.addMultiplesOfTerm( IntConstant.NEG_ONE, t2); t.addFactor(oneMinC1); } t.addFactor(rhs_.getCondition()); cond.addMultiplesOfTerm(IntConstant.ONE, t); LvalExpression cond_ = newLvalOrExisting(cond, valueMostRecent.getName(), statements); mux = new MuxPolynomialExpression(cond_, rhs_.getValueTrue(), valueTrue); // System.out.println("2"); } if (mux == null && rhs_.getValueTrue() == valueTrue) { // So mux has the form condition ? valueTrue : // (condition2 ? valueTrue : rhs_.getValueFalse()) // So replace it with (1-c1)*(1-c2) ? // rhs_.getValueFalse() : valueTrue PolynomialExpression cond = new PolynomialExpression(); PolynomialTerm t = new PolynomialTerm(); { PolynomialExpression oneMinC1 = new PolynomialExpression(); PolynomialTerm one = new PolynomialTerm(); PolynomialTerm t2 = new PolynomialTerm(); t2.addFactor(condition); oneMinC1.addMultiplesOfTerm(IntConstant.ONE, one); oneMinC1.addMultiplesOfTerm( IntConstant.NEG_ONE, t2); t.addFactor(oneMinC1); } { PolynomialExpression oneMinC2 = new PolynomialExpression(); PolynomialTerm one = new PolynomialTerm(); PolynomialTerm t2 = new PolynomialTerm(); t2.addFactor(rhs_.getCondition()); oneMinC2.addMultiplesOfTerm(IntConstant.ONE, one); oneMinC2.addMultiplesOfTerm( IntConstant.NEG_ONE, t2); t.addFactor(oneMinC2); } cond.addMultiplesOfTerm(IntConstant.ONE, t); LvalExpression cond_ = newLvalOrExisting(cond, valueMostRecent.getName(), statements); mux = new MuxPolynomialExpression(cond_, rhs_.getValueFalse(), valueTrue); // System.out.println("3"); } } } } // Inlining was not possible? Output as-is. if (mux == null) { mux = new MuxPolynomialExpression((LvalExpression) condition, valueTrue, valueFalse); // System.out.println("-1"); } // Assign the mux to the output variable Function.addVar(valueMostRecent); valueMostRecent = Function.getVar(valueMostRecent); // toAssignmentStatements_NoChangeRef is not compatible with // toSLPTCircuit. // We must build a result that is already SLPT. if (false) { // This doesn' work. AssignmentStatement valueas = new AssignmentStatement( valueMostRecent, (mux).toBinaryOps()); BlockStatement result = (BlockStatement) valueas .toSLPTCircuit(null); // Make sure that the mux information is preserved List<Statement> resultStates = result.getStatements(); AssignmentStatement actualMuxAssign = ((AssignmentStatement) resultStates .get(resultStates.size() - 1)); actualMuxAssign.addAlternativeRHS(mux); for (Statement as : result.getStatements()) { ((AssignmentStatement) as) .toAssignmentStatements_NoChangeRef(statements); } // We can't call updateVars on this created assignment, because // the right hand side uses variables inside the // if scope, which assignmentStatement.updateVars() will // mimuxstakenly redirect to the variables on the outer scope! // newAs.toAssignmentStatements_NoChangeRef(statements); } else { // Evaluating complex expressions is tricky when we can't use // toSLPT. // Have to unroll by hand: // M*(A - B) + B LvalExpression negB = evaluateExpression_if( new BinaryOpExpression(new TimesOperator(), IntConstant.NEG_ONE, mux.getValueFalse()), valueMostRecent.getName(), "negB", statements); LvalExpression AminB = evaluateExpression_if( new BinaryOpExpression(new PlusOperator(), negB, mux.getValueTrue()), valueMostRecent.getName(), "AminB", statements); LvalExpression MtAminB = evaluateExpression_if( new BinaryOpExpression(new TimesOperator(), mux.getCondition(), AminB), valueMostRecent.getName(), "MtAminB", statements); AssignmentStatement muxAssign = new AssignmentStatement( valueMostRecent, new BinaryOpExpression( new PlusOperator(), MtAminB, mux.getValueFalse())); muxAssign.addAlternativeRHS(mux); muxAssign.toAssignmentStatements_NoChangeRef(statements); } } } /** * Evaluates expression toEvaluate into a temporary variable (see syntax for * evaluateExpression). * * However, the statements needed to evaluate toEvaluate are immediately * used with toAssignmentStatements_NoChangeRef(sb). * * Finally, the true result is returned (by getting the newest name from the * VariableLUT). */ private static LvalExpression evaluateExpression_if(Expression toEvaluate, String goal, String tempName, StatementBuffer sb) { BlockStatement result = new BlockStatement(); // This cast will fail if the operation is a compile time operator. One // of the many reasons why this method // is an internal to the ifStatement class - it's not general purpose. LvalExpression tempValue = (LvalExpression) toEvaluate .evaluateExpression(goal, tempName, result); // run result for (Statement as : result.getStatements()) { if (as instanceof AssignmentStatement) { ((AssignmentStatement) as).toAssignmentStatements_NoChangeRef(sb); } else { as.toAssignmentStatements(sb); } } // Now this should be safe - we can rereference the temporary (but not // the inputs that created it) return tempValue.changeReference(Function.getVars()); } /** * If the optimizer has an lval associated with the given expression, return * it. * * Otherwise, create a new lval to hold the given expression and an * assignment to store the expression in that new lval, and add that * assignment to the statement buffer. During this process, changeReferences * is never called on the input expression. This means this method is safe * to use within the if statement transformation. Also associate the created * lval with the given expression in the optimizer. */ private static LvalExpression newLvalOrExisting(Expression expr, String prefixForNewLval, StatementBuffer statements) { LvalExpression existing = Optimizer.getLvalFor(expr); if (existing == null) { BlockStatement result = new BlockStatement(); LvalExpression newLval = (LvalExpression) expr.evaluateExpression( prefixForNewLval, "condProduct", result); if (result.getStatements().size() > 1) { throw new RuntimeException( "Cannot pass a complex (nested) expression to newLvalOrExisting"); } ((AssignmentStatement) result.getStatements().get(0)) .toAssignmentStatements_NoChangeRef(statements); newLval = newLval.changeReference(Function.getVars()); Optimizer.addAssignment(expr, newLval); return newLval; // This is safe, because we just created the // variable on the current scope } else { return existing; } } }
pepper-project/pepper
compiler/frontend/src/SFE/Compiler/IfStatement.java
7,610
// rhs_.getValueFalse() : valueFalse
line_comment
nl
// IfStatement.java. // Copyright (C) 2004 Naom Nisan, Ziv Balshai, Amir Levy. // See full copyright license terms in file ../GPL.txt package SFE.Compiler; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.TreeMap; import SFE.Compiler.Operators.NotEqualOperator; import SFE.Compiler.Operators.PlusOperator; import SFE.Compiler.Operators.TimesOperator; import SFE.Compiler.Operators.UnaryMinusOperator; import SFE.Compiler.PolynomialExpression.PolynomialTerm; /** * A class for representing if statement that can be defined in the program. */ public class IfStatement extends Statement implements Optimizable { // ~ Instance fields // -------------------------------------------------------- // data members /* * Holds the condition of the if statement. */ private Expression condition; /* * Holds a variable name guaranteed not to collide with program structures */ private String nameOfCondition; /* * Holds the block of the if statement. */ private Statement thenBlock; /* * Holds the else block of the if statement. */ private Statement elseBlock; // ~ Constructors // ----------------------------------------------------------- /** * Construct a new if statement. * * @param condition * the condition of the if statement. * @param thenBlock * the block of the if statement. * @param elseBlock * the block of the else statement. */ public IfStatement(Expression condition, Statement thenBlock, Statement elseBlock, String nameOfCondition) { this.condition = condition; this.thenBlock = thenBlock; this.elseBlock = elseBlock; this.nameOfCondition = nameOfCondition; } // ~ Methods // ---------------------------------------------------------------- /** * Unique vars transformations. public Statement uniqueVars() { //Uniquify * the condition first. Though, it will do nothing at this point. condition * = condition.changeReference(Function.getVars()); * * if (elseBlock == null){ throw new RuntimeException("Assertion error"); } * * if (condition.size() != 1){ throw new * RuntimeException("Error: condition was not a boolean value"); } * * BlockStatement newBlock = new BlockStatement(); * * //start new scope Function.pushScope(); * * //unique vars transformations on the if block * newBlock.addStatement(thenBlock.uniqueVars()); * * //end the scope Map<String, LvalExpression> thenScope = * Function.popScope(); * * //start new scope Function.pushScope(); * * //unique vars transformations on the if block * newBlock.addStatement(elseBlock.uniqueVars()); * * //end the scope Map<String, LvalExpression> elseScope = * Function.popScope(); * * //Get the scope holding the if statement VariableLUT beforeIf = * Function.getVars(); * * HashSet<String> ConflictVariables = new HashSet(); ArrayList<String> * ConflictVariablesSorted = new ArrayList(); for(String lvalName : * thenScope.keySet()){ LvalExpression lvalBeforeIf = * Function.getVars().getVar(lvalName); if (lvalBeforeIf != null){ * ConflictVariables.add(lvalName); ConflictVariablesSorted.add(lvalName); } * } for(String lvalName : elseScope.keySet()){ if * (ConflictVariables.contains(lvalName)){ continue; } LvalExpression * lvalBeforeIf = Function.getVars().getVar(lvalName); if (lvalBeforeIf != * null){ ConflictVariables.add(lvalName); * ConflictVariablesSorted.add(lvalName); } } * * Collections.sort(ConflictVariablesSorted); * * for(String lvalName : ConflictVariablesSorted){ LvalExpression valueTrue, * valueFalse, valueMostRecent; { //lval before if block LvalExpression * lvalBeforeIf = Function.getVars().getVar(lvalName); if * (lvalBeforeIf.size() != 1){ throw new * RuntimeException("Error: non primitive type in if statement evaluation"); * } LvalExpression lvalInThen = (LvalExpression) thenScope.get(lvalName); * if (lvalInThen != null){ //The variable is overwritten in the then block. * LvalExpression lvalInElse = (LvalExpression) elseScope.get(lvalName); if * (lvalInElse != null){ //The variable is overwritten in the else block * valueTrue = lvalInThen; valueFalse = lvalInElse; valueMostRecent = * lvalInElse; } else { valueTrue = lvalInThen; valueFalse = lvalBeforeIf; * valueMostRecent = lvalInThen; } } else { //The variable is not * overwritten in the then block. LvalExpression lvalInElse = * (LvalExpression) elseScope.get(lvalName); //The variable is overwritten * in the else block. valueTrue = lvalBeforeIf; valueFalse = lvalInElse; * valueMostRecent = lvalInElse; } * * if (valueTrue.size()!=1 || valueFalse.size()!=1){ throw new * RuntimeException("Error: non primitive type in if statement evaluation"); * } } * * //valueTrue * condition + valueFalse + valueFalse * (-1 * condition) = * x*c + y*(1-c) OperationExpression mux = FloatExpressions.mux(condition, * valueTrue, valueFalse); * * //We can't call updateVars on this created assignment, because the right * hand side uses variables inside the //if scope, which * assignmentStatement.updateVars() will mistakenly redirect to the * variables on the outer scope! Function.addVar(valueMostRecent); * valueMostRecent = Function.getVar(valueMostRecent); AssignmentStatement * newAs = new AssignmentStatement(valueMostRecent,mux); //perform the mux * newAs.dedicateAssignment(); newAs.setOutputLine(Program.getLineNumber()); * //Set the line number of the as newBlock.addStatement(newAs); //Add it to * the reult } * * return newBlock; } */ /** * Transforms this multibit AssignmentStatement into singlebit statements * and returns the result. * * @param obj * not needed (null). * @return a BlockStatement containing the result statements. */ public BlockStatement toSLPTCircuit(Object obj) { BlockStatement result = new BlockStatement(); // create a temp var that holds the condition result LvalExpression condition_asBoolean = Function.addTempLocalVar( "conditionResult" + nameOfCondition, new BooleanType()); // create the assignment statement that assings the result AssignmentStatement conditionResultAs = new AssignmentStatement( condition_asBoolean, new BinaryOpExpression( new NotEqualOperator(), condition, new BooleanConstant( false))); // evaluate the condition and stores it in the conditionResult result.addStatement(conditionResultAs.toSLPTCircuit(null)); condition = condition_asBoolean; // .bitAt(0); // Defer this processing until toAssignments. // thenBlock = thenBlock.toSLPTCircuit(null); // elseBlock = elseBlock.toSLPTCircuit(null); result.addStatement(this); return result; } /** * Returns a replica of this IfStatement. * * @return a replica of this IfStatement. */ public Statement duplicate() { return new IfStatement(condition.duplicate(), thenBlock.duplicate(), elseBlock.duplicate(), nameOfCondition); } /** * Returns a string representation of this IfStatement. * * @return a string representation of this IfStatement. */ public String toString() { return "IF (" + condition + ")\nTHEN\n" + thenBlock + "ELSE\n" + elseBlock; } // ~ Static fields/initializers // --------------------------------------------- public void optimize(Optimization job) { // This optimization is only done in the high level stage, because // uniqueVars erases if statements switch (job) { case RENUMBER_ASSIGNMENTS: // Allow the if and else block to receive numberings. ((Optimizable) thenBlock) .optimize(Optimization.RENUMBER_ASSIGNMENTS); if (elseBlock != null) ((Optimizable) elseBlock) .optimize(Optimization.RENUMBER_ASSIGNMENTS); break; case DUPLICATED_IN_FUNCTION: ((Optimizable) thenBlock) .optimize(Optimization.DUPLICATED_IN_FUNCTION); ((Optimizable) elseBlock) .optimize(Optimization.DUPLICATED_IN_FUNCTION); condition.duplicatedInFunction(); break; default: // It's potentially dangerous to perform an optimization on a system // which doesn't implement it throw new RuntimeException("Optimization not implemented: " + job); } } public void blockOptimize(BlockOptimization job, List body) { switch (job) { case DEADCODE_ELIMINATE: // Deadcode elimination currently does nothing break; default: // It's potentially dangerous if we perform an optimization and only // some parts of our system implement it. // Catch that. throw new RuntimeException("Optimization not implemented: " + job); } } public void buildUsedStatementsHash() { // Currently deadcode elimination of if statements not implemented Optimizer.putUsedStatement(this); // The if and else block are privately owned by this if, so we hide them // from the optimizer // Ensure that the condition can be evaluated Collection<LvalExpression> v = condition.getLvalExpressionInputs(); for (LvalExpression q : v) { Statement as = q.getAssigningStatement(); Optimizer.putUsedStatement(as); } } public void toAssignmentStatements(StatementBuffer statements) { condition = Function.getVar((LvalExpression) condition); BooleanConstant asConst = BooleanConstant.toBooleanConstant(condition); if (elseBlock == null) { throw new RuntimeException("Assertion error"); } // Constant condition evaluation? if (asConst != null) { if (asConst.getConst()) { thenBlock = thenBlock.toSLPTCircuit(null); thenBlock.toAssignmentStatements(statements); return; } else { elseBlock = elseBlock.toSLPTCircuit(null); elseBlock.toAssignmentStatements(statements); return; } } // so condition is an lvalue. // start new scope Function.pushScope(); // statements.pushShortCircuit((LvalExpression)condition, // IntConstant.ONE); statements.pushUncertainty(); statements.pushCondition((LvalExpression)condition, true); // toSLPT must occur here, so that the created intermediate variables // are correctly scoped thenBlock = thenBlock.toSLPTCircuit(null); // unique vars transformations on the if block thenBlock.toAssignmentStatements(statements); statements.popCondition(); // end the scope // statements.popShortCircuit(); Map<String, LvalExpression> thenScope = Function.popScope(); // start new scope Function.pushScope(); statements.pushCondition((LvalExpression)condition, false); // push the false condition here. // statements.pushShortCircuit((LvalExpression)condition, new // IntConstant(0)); // toSLPT must occur here, so that the created intermediate variables // are correctly scoped elseBlock = elseBlock.toSLPTCircuit(null); // unique vars transformations on the if block elseBlock.toAssignmentStatements(statements); statements.popCondition(); statements.popUncertainty(); // end the scope // statements.popShortCircuit(); Map<String, LvalExpression> elseScope = Function.popScope(); expandMuxStatements(condition, thenScope, elseScope, statements); } /** * Muxes the three scopes possible in an if statement together, writing * generated statements to the statement buffer. * * 1) The current scope (Function.getVars()) 2) A scope reflecting variables * generated by the end of the then block 3) A scope reflecting variables * generated by the end of the else block * * Name conflicts can occur in multiple ways, mux statements are inlined to * prevent unecessary condition variable multiplication. */ public static void expandMuxStatements(Expression condition, Map<String, LvalExpression> thenScope, Map<String, LvalExpression> elseScope, StatementBuffer statements) { // Get the scope holding the if statement VariableLUT beforeIf = Function.getVars(); HashSet<String> ConflictVariables = new HashSet(); TreeMap<Integer, String> ConflictVariablesSorted = new TreeMap(); for (LvalExpression lvalInThen : thenScope.values()) { String name = lvalInThen.getName(); LvalExpression lvalBeforeIf = Function.getVars().getVar(name); if (lvalBeforeIf != null && lvalBeforeIf.getOutputLine() != -1) { // There // is // some // amount // of // cruft // in // the // variable // lookup // table. // FIXME ConflictVariables.add(name); ConflictVariablesSorted.put((lvalInThen.getAssigningStatement()).getOutputLine(), name); } } for (LvalExpression lvalInElse : elseScope.values()) { String name = lvalInElse.getName(); if (ConflictVariables.contains(name)) { continue; } LvalExpression lvalBeforeIf = Function.getVars().getVar(name); if (lvalBeforeIf != null && lvalBeforeIf.getOutputLine() != -1) { ConflictVariables.add(name); ConflictVariablesSorted.put((lvalInElse.getAssigningStatement()).getOutputLine(), name); } } for (String lvalName : ConflictVariablesSorted.values()) { LvalExpression valueTrue, valueFalse, valueMostRecent; { // lval before if block LvalExpression lvalBeforeIf = Function.getVars().getVar( lvalName); LvalExpression lvalInThen = (LvalExpression) thenScope .get(lvalName); if (lvalInThen != null) { // The variable is overwritten in the then block. LvalExpression lvalInElse = (LvalExpression) elseScope .get(lvalName); if (lvalInElse != null) { // The variable is overwritten in the else block valueTrue = lvalInThen; valueFalse = lvalInElse; valueMostRecent = lvalInElse; } else { valueTrue = lvalInThen; valueFalse = lvalBeforeIf; valueMostRecent = lvalInThen; } } else { // The variable is not overwritten in the then block. LvalExpression lvalInElse = (LvalExpression) elseScope .get(lvalName); // The variable is overwritten in the else block. valueTrue = lvalBeforeIf; valueFalse = lvalInElse; valueMostRecent = lvalInElse; } } // valueTrue * condition + valueFalse + valueFalse * (-1 * // condition) = x*c + y*(1-c) MuxPolynomialExpression mux = null; if (AssignmentStatement.combineExpressions) { // If valueTrue or valueFalse have mux values, can we combine // expressions? Statement valueTrue_ = valueTrue.getAssigningStatement(); Statement valueFalse_ = valueFalse.getAssigningStatement(); if (valueTrue_ instanceof AssignmentStatement && !valueTrue.isReferenced()) { MuxPolynomialExpression rhs_ = MuxPolynomialExpression .toMuxExpression(((AssignmentStatement) valueTrue_) .getLHS()); if (rhs_ != null) { if (mux == null && rhs_.getValueFalse() == valueFalse) { // So mux has the form condition ? (condition2 ? // rhs_.getValueTrue() : valueFalse) : valueFalse // Hence replace mux with (c1) * (c2) ? // rhs_.getValueTrue() : valueFalse PolynomialExpression c1c2 = new PolynomialExpression(); PolynomialTerm t1 = new PolynomialTerm(); t1.addFactor((LvalExpression) condition); t1.addFactor(rhs_.getCondition()); c1c2.addMultiplesOfTerm(IntConstant.ONE, t1); LvalExpression c1c2_ = newLvalOrExisting(c1c2, valueMostRecent.getName(), statements); mux = new MuxPolynomialExpression(c1c2_, rhs_.getValueTrue(), valueFalse); // System.out.println("0"); } if (mux == null && rhs_.getValueTrue() == valueFalse) { // So mux has the form condition ? (condition2 ? // valueFalse : rhs_.getValueFalse()) : valueFalse // Hence replace mux with (c1) * (1 - c2) ? // rhs_.getValueFalse() :<SUF> PolynomialExpression cond = new PolynomialExpression(); PolynomialTerm t = new PolynomialTerm(); t.addFactor((LvalExpression) condition); { PolynomialExpression oneMinC2 = new PolynomialExpression(); PolynomialTerm one = new PolynomialTerm(); PolynomialTerm t2 = new PolynomialTerm(); t2.addFactor(rhs_.getCondition()); oneMinC2.addMultiplesOfTerm(IntConstant.ONE, one); oneMinC2.addMultiplesOfTerm( IntConstant.NEG_ONE, t2); t.addFactor(oneMinC2); } cond.addMultiplesOfTerm(IntConstant.ONE, t); LvalExpression cond_ = newLvalOrExisting(cond, valueMostRecent.getName(), statements); mux = new MuxPolynomialExpression(cond_, rhs_.getValueFalse(), valueFalse); // System.out.println("1"); } } } if (valueFalse_ instanceof AssignmentStatement && !valueFalse.isReferenced()) { MuxPolynomialExpression rhs_ = MuxPolynomialExpression .toMuxExpression(((AssignmentStatement) valueFalse_) .getLHS()); if (rhs_ != null) { if (mux == null && rhs_.getValueFalse() == valueTrue) { // So mux has the form condition ? valueTrue : // (condition2 ? rhs_.getValueTrue() : valueTrue) // So replace it with (1-c1)*(c2) ? // rhs_.getValueTrue() : valueTrue PolynomialExpression cond = new PolynomialExpression(); PolynomialTerm t = new PolynomialTerm(); { PolynomialExpression oneMinC1 = new PolynomialExpression(); PolynomialTerm one = new PolynomialTerm(); PolynomialTerm t2 = new PolynomialTerm(); t2.addFactor(condition); oneMinC1.addMultiplesOfTerm(IntConstant.ONE, one); oneMinC1.addMultiplesOfTerm( IntConstant.NEG_ONE, t2); t.addFactor(oneMinC1); } t.addFactor(rhs_.getCondition()); cond.addMultiplesOfTerm(IntConstant.ONE, t); LvalExpression cond_ = newLvalOrExisting(cond, valueMostRecent.getName(), statements); mux = new MuxPolynomialExpression(cond_, rhs_.getValueTrue(), valueTrue); // System.out.println("2"); } if (mux == null && rhs_.getValueTrue() == valueTrue) { // So mux has the form condition ? valueTrue : // (condition2 ? valueTrue : rhs_.getValueFalse()) // So replace it with (1-c1)*(1-c2) ? // rhs_.getValueFalse() : valueTrue PolynomialExpression cond = new PolynomialExpression(); PolynomialTerm t = new PolynomialTerm(); { PolynomialExpression oneMinC1 = new PolynomialExpression(); PolynomialTerm one = new PolynomialTerm(); PolynomialTerm t2 = new PolynomialTerm(); t2.addFactor(condition); oneMinC1.addMultiplesOfTerm(IntConstant.ONE, one); oneMinC1.addMultiplesOfTerm( IntConstant.NEG_ONE, t2); t.addFactor(oneMinC1); } { PolynomialExpression oneMinC2 = new PolynomialExpression(); PolynomialTerm one = new PolynomialTerm(); PolynomialTerm t2 = new PolynomialTerm(); t2.addFactor(rhs_.getCondition()); oneMinC2.addMultiplesOfTerm(IntConstant.ONE, one); oneMinC2.addMultiplesOfTerm( IntConstant.NEG_ONE, t2); t.addFactor(oneMinC2); } cond.addMultiplesOfTerm(IntConstant.ONE, t); LvalExpression cond_ = newLvalOrExisting(cond, valueMostRecent.getName(), statements); mux = new MuxPolynomialExpression(cond_, rhs_.getValueFalse(), valueTrue); // System.out.println("3"); } } } } // Inlining was not possible? Output as-is. if (mux == null) { mux = new MuxPolynomialExpression((LvalExpression) condition, valueTrue, valueFalse); // System.out.println("-1"); } // Assign the mux to the output variable Function.addVar(valueMostRecent); valueMostRecent = Function.getVar(valueMostRecent); // toAssignmentStatements_NoChangeRef is not compatible with // toSLPTCircuit. // We must build a result that is already SLPT. if (false) { // This doesn' work. AssignmentStatement valueas = new AssignmentStatement( valueMostRecent, (mux).toBinaryOps()); BlockStatement result = (BlockStatement) valueas .toSLPTCircuit(null); // Make sure that the mux information is preserved List<Statement> resultStates = result.getStatements(); AssignmentStatement actualMuxAssign = ((AssignmentStatement) resultStates .get(resultStates.size() - 1)); actualMuxAssign.addAlternativeRHS(mux); for (Statement as : result.getStatements()) { ((AssignmentStatement) as) .toAssignmentStatements_NoChangeRef(statements); } // We can't call updateVars on this created assignment, because // the right hand side uses variables inside the // if scope, which assignmentStatement.updateVars() will // mimuxstakenly redirect to the variables on the outer scope! // newAs.toAssignmentStatements_NoChangeRef(statements); } else { // Evaluating complex expressions is tricky when we can't use // toSLPT. // Have to unroll by hand: // M*(A - B) + B LvalExpression negB = evaluateExpression_if( new BinaryOpExpression(new TimesOperator(), IntConstant.NEG_ONE, mux.getValueFalse()), valueMostRecent.getName(), "negB", statements); LvalExpression AminB = evaluateExpression_if( new BinaryOpExpression(new PlusOperator(), negB, mux.getValueTrue()), valueMostRecent.getName(), "AminB", statements); LvalExpression MtAminB = evaluateExpression_if( new BinaryOpExpression(new TimesOperator(), mux.getCondition(), AminB), valueMostRecent.getName(), "MtAminB", statements); AssignmentStatement muxAssign = new AssignmentStatement( valueMostRecent, new BinaryOpExpression( new PlusOperator(), MtAminB, mux.getValueFalse())); muxAssign.addAlternativeRHS(mux); muxAssign.toAssignmentStatements_NoChangeRef(statements); } } } /** * Evaluates expression toEvaluate into a temporary variable (see syntax for * evaluateExpression). * * However, the statements needed to evaluate toEvaluate are immediately * used with toAssignmentStatements_NoChangeRef(sb). * * Finally, the true result is returned (by getting the newest name from the * VariableLUT). */ private static LvalExpression evaluateExpression_if(Expression toEvaluate, String goal, String tempName, StatementBuffer sb) { BlockStatement result = new BlockStatement(); // This cast will fail if the operation is a compile time operator. One // of the many reasons why this method // is an internal to the ifStatement class - it's not general purpose. LvalExpression tempValue = (LvalExpression) toEvaluate .evaluateExpression(goal, tempName, result); // run result for (Statement as : result.getStatements()) { if (as instanceof AssignmentStatement) { ((AssignmentStatement) as).toAssignmentStatements_NoChangeRef(sb); } else { as.toAssignmentStatements(sb); } } // Now this should be safe - we can rereference the temporary (but not // the inputs that created it) return tempValue.changeReference(Function.getVars()); } /** * If the optimizer has an lval associated with the given expression, return * it. * * Otherwise, create a new lval to hold the given expression and an * assignment to store the expression in that new lval, and add that * assignment to the statement buffer. During this process, changeReferences * is never called on the input expression. This means this method is safe * to use within the if statement transformation. Also associate the created * lval with the given expression in the optimizer. */ private static LvalExpression newLvalOrExisting(Expression expr, String prefixForNewLval, StatementBuffer statements) { LvalExpression existing = Optimizer.getLvalFor(expr); if (existing == null) { BlockStatement result = new BlockStatement(); LvalExpression newLval = (LvalExpression) expr.evaluateExpression( prefixForNewLval, "condProduct", result); if (result.getStatements().size() > 1) { throw new RuntimeException( "Cannot pass a complex (nested) expression to newLvalOrExisting"); } ((AssignmentStatement) result.getStatements().get(0)) .toAssignmentStatements_NoChangeRef(statements); newLval = newLval.changeReference(Function.getVars()); Optimizer.addAssignment(expr, newLval); return newLval; // This is safe, because we just created the // variable on the current scope } else { return existing; } } }
179423_1
package com.persistentbit.sql.connect; import com.persistentbit.core.doc.annotations.DUsesClass; import com.persistentbit.sql.PersistSqlException; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Logger; /** * A {@link Connection} supplier that uses a connection pool to return new connections.<br> * * @author Peter Muys * @since 13/07/2016 */ @DUsesClass(ConnectionWrapper.class) public class PooledConnectionSupplier implements Supplier<Connection>{ static private final Logger log = Logger.getLogger(PooledConnectionSupplier.class.getName()); private final Supplier<Connection> supplier; private final Consumer<Connection> resetter; private final int poolSize; private final BlockingQueue<Connection> freeConnections; private int activeConnections; public PooledConnectionSupplier(Supplier<Connection> supplier, int poolSize) { this(supplier, poolSize, (c) -> { try { c.setAutoCommit(false); } catch(SQLException e) { throw new PersistSqlException(e); } }); } public PooledConnectionSupplier(Supplier<Connection> supplier, int poolSize, Consumer<Connection> connectionResetter ) { this.supplier = supplier; this.poolSize = poolSize; this.resetter = connectionResetter; this.freeConnections = new LinkedBlockingQueue(poolSize); } @Override public synchronized Connection get() { if(freeConnections.isEmpty()) { if(activeConnections < poolSize) { //Nog geen pool opgebouwd... ConnectionWrapper con = newConnection(supplier.get()); activeConnections++; return con; } } Connection con = null; try { do { try { con = freeConnections.poll(1000, TimeUnit.MILLISECONDS); } catch(InterruptedException e) { log.warning("Waiting for a free connection..."); } } while(con == null); if(con.isValid(0) == false) { return newConnection(supplier.get()); } return newConnection(con); } catch(SQLException e) { throw new PersistSqlException(e); } } private ConnectionWrapper newConnection(Connection realConnection) { resetter.accept(realConnection); ConnectionWrapper con = new ConnectionWrapper(realConnection, new ConnectionWrapper.ConnectionHandler(){ private boolean isCommit = false; @Override public void onClose(Connection connection) throws SQLException { if(isCommit == false || connection.getAutoCommit()) { connection.rollback(); } freeConnections.add(connection); } @Override public void onCommit(Connection connection) throws SQLException { isCommit = true; connection.commit(); } @Override public void onRollback(Connection connection) throws SQLException { isCommit = true; connection.rollback(); } @Override public void onAbort(Connection connection, Executor executor) throws SQLException { activeConnections--; connection.abort(executor); } }); return con; } public synchronized void close() { int inuse = activeConnections - freeConnections.size(); if(inuse > 0) { log.warning("Closing the connection pool with " + inuse + " connections still in use"); } else { log.info("Closing the connection pool with " + activeConnections + " open connections"); } while(activeConnections > 0) { Connection con = null; try { for(int t = 0; t < 20; t++) { con = freeConnections.poll(1000, TimeUnit.MILLISECONDS); if(con != null) { break; } log.warning("Waiting for the release of a connection"); } try { con.close(); } catch(SQLException e) { e.printStackTrace(); } activeConnections--; } catch(InterruptedException e) { log.info("Waiting for connections to close"); } } } }
persistentbit/glasgolia
src/main/java/com/persistentbit/sql/connect/PooledConnectionSupplier.java
1,263
//Nog geen pool opgebouwd...
line_comment
nl
package com.persistentbit.sql.connect; import com.persistentbit.core.doc.annotations.DUsesClass; import com.persistentbit.sql.PersistSqlException; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Logger; /** * A {@link Connection} supplier that uses a connection pool to return new connections.<br> * * @author Peter Muys * @since 13/07/2016 */ @DUsesClass(ConnectionWrapper.class) public class PooledConnectionSupplier implements Supplier<Connection>{ static private final Logger log = Logger.getLogger(PooledConnectionSupplier.class.getName()); private final Supplier<Connection> supplier; private final Consumer<Connection> resetter; private final int poolSize; private final BlockingQueue<Connection> freeConnections; private int activeConnections; public PooledConnectionSupplier(Supplier<Connection> supplier, int poolSize) { this(supplier, poolSize, (c) -> { try { c.setAutoCommit(false); } catch(SQLException e) { throw new PersistSqlException(e); } }); } public PooledConnectionSupplier(Supplier<Connection> supplier, int poolSize, Consumer<Connection> connectionResetter ) { this.supplier = supplier; this.poolSize = poolSize; this.resetter = connectionResetter; this.freeConnections = new LinkedBlockingQueue(poolSize); } @Override public synchronized Connection get() { if(freeConnections.isEmpty()) { if(activeConnections < poolSize) { //Nog geen<SUF> ConnectionWrapper con = newConnection(supplier.get()); activeConnections++; return con; } } Connection con = null; try { do { try { con = freeConnections.poll(1000, TimeUnit.MILLISECONDS); } catch(InterruptedException e) { log.warning("Waiting for a free connection..."); } } while(con == null); if(con.isValid(0) == false) { return newConnection(supplier.get()); } return newConnection(con); } catch(SQLException e) { throw new PersistSqlException(e); } } private ConnectionWrapper newConnection(Connection realConnection) { resetter.accept(realConnection); ConnectionWrapper con = new ConnectionWrapper(realConnection, new ConnectionWrapper.ConnectionHandler(){ private boolean isCommit = false; @Override public void onClose(Connection connection) throws SQLException { if(isCommit == false || connection.getAutoCommit()) { connection.rollback(); } freeConnections.add(connection); } @Override public void onCommit(Connection connection) throws SQLException { isCommit = true; connection.commit(); } @Override public void onRollback(Connection connection) throws SQLException { isCommit = true; connection.rollback(); } @Override public void onAbort(Connection connection, Executor executor) throws SQLException { activeConnections--; connection.abort(executor); } }); return con; } public synchronized void close() { int inuse = activeConnections - freeConnections.size(); if(inuse > 0) { log.warning("Closing the connection pool with " + inuse + " connections still in use"); } else { log.info("Closing the connection pool with " + activeConnections + " open connections"); } while(activeConnections > 0) { Connection con = null; try { for(int t = 0; t < 20; t++) { con = freeConnections.poll(1000, TimeUnit.MILLISECONDS); if(con != null) { break; } log.warning("Waiting for the release of a connection"); } try { con.close(); } catch(SQLException e) { e.printStackTrace(); } activeConnections--; } catch(InterruptedException e) { log.info("Waiting for connections to close"); } } } }
179418_1
package com.persistentbit.sql.connect; import com.persistentbit.sql.PersistSqlException; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Logger; /** * A {@link Connection} supplier that uses a connection pool to return new connections.<br> * * @author Peter Muys * @since 13/07/2016 */ public class PooledConnectionSupplier implements Supplier<Connection>{ static private final Logger log = Logger.getLogger(PooledConnectionSupplier.class.getName()); private final Supplier<Connection> supplier; private final Consumer<Connection> resetter; private final int poolSize; private final BlockingQueue<Connection> freeConnections; private int activeConnections; public PooledConnectionSupplier(Supplier<Connection> supplier, int poolSize) { this(supplier, poolSize, (c) -> { try { c.setAutoCommit(false); } catch(SQLException e) { throw new PersistSqlException(e); } }); } public PooledConnectionSupplier(Supplier<Connection> supplier, int poolSize, Consumer<Connection> connectionResetter ) { this.supplier = supplier; this.poolSize = poolSize; this.resetter = connectionResetter; this.freeConnections = new LinkedBlockingQueue(poolSize); } @Override public synchronized Connection get() { if(freeConnections.isEmpty()) { if(activeConnections < poolSize) { //Nog geen pool opgebouwd... ConnectionWrapper con = newConnection(supplier.get()); activeConnections++; return con; } } Connection con = null; try { do { try { con = freeConnections.poll(1000, TimeUnit.MILLISECONDS); } catch(InterruptedException e) { log.warning("Waiting for a free connection..."); } } while(con == null); if(con.isValid(0) == false) { return newConnection(supplier.get()); } return newConnection(con); } catch(SQLException e) { throw new PersistSqlException(e); } } private ConnectionWrapper newConnection(Connection realConnection) { resetter.accept(realConnection); ConnectionWrapper con = new ConnectionWrapper(realConnection, new ConnectionWrapper.ConnectionHandler(){ private boolean isCommit = false; @Override public void onClose(Connection connection) throws SQLException { if(isCommit == false || connection.getAutoCommit()) { connection.rollback(); } freeConnections.add(connection); } @Override public void onCommit(Connection connection) throws SQLException { isCommit = true; connection.commit(); } @Override public void onRollback(Connection connection) throws SQLException { isCommit = true; connection.rollback(); } @Override public void onAbort(Connection connection, Executor executor) throws SQLException { activeConnections--; connection.abort(executor); } }); return con; } public synchronized void close() { int inuse = activeConnections - freeConnections.size(); if(inuse > 0) { log.warning("Closing the connection pool with " + inuse + " connections still in use"); } else { log.info("Closing the connection pool with " + activeConnections + " open connections"); } while(activeConnections > 0) { Connection con = null; try { for(int t = 0; t < 20; t++) { con = freeConnections.poll(1000, TimeUnit.MILLISECONDS); if(con != null) { break; } log.warning("Waiting for the release of a connection"); } try { con.close(); } catch(SQLException e) { e.printStackTrace(); } activeConnections--; } catch(InterruptedException e) { log.info("Waiting for connections to close"); } } } }
persistentbit/persistent-sql
src/main/java/com/persistentbit/sql/connect/PooledConnectionSupplier.java
1,234
//Nog geen pool opgebouwd...
line_comment
nl
package com.persistentbit.sql.connect; import com.persistentbit.sql.PersistSqlException; import java.sql.Connection; import java.sql.SQLException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.logging.Logger; /** * A {@link Connection} supplier that uses a connection pool to return new connections.<br> * * @author Peter Muys * @since 13/07/2016 */ public class PooledConnectionSupplier implements Supplier<Connection>{ static private final Logger log = Logger.getLogger(PooledConnectionSupplier.class.getName()); private final Supplier<Connection> supplier; private final Consumer<Connection> resetter; private final int poolSize; private final BlockingQueue<Connection> freeConnections; private int activeConnections; public PooledConnectionSupplier(Supplier<Connection> supplier, int poolSize) { this(supplier, poolSize, (c) -> { try { c.setAutoCommit(false); } catch(SQLException e) { throw new PersistSqlException(e); } }); } public PooledConnectionSupplier(Supplier<Connection> supplier, int poolSize, Consumer<Connection> connectionResetter ) { this.supplier = supplier; this.poolSize = poolSize; this.resetter = connectionResetter; this.freeConnections = new LinkedBlockingQueue(poolSize); } @Override public synchronized Connection get() { if(freeConnections.isEmpty()) { if(activeConnections < poolSize) { //Nog geen<SUF> ConnectionWrapper con = newConnection(supplier.get()); activeConnections++; return con; } } Connection con = null; try { do { try { con = freeConnections.poll(1000, TimeUnit.MILLISECONDS); } catch(InterruptedException e) { log.warning("Waiting for a free connection..."); } } while(con == null); if(con.isValid(0) == false) { return newConnection(supplier.get()); } return newConnection(con); } catch(SQLException e) { throw new PersistSqlException(e); } } private ConnectionWrapper newConnection(Connection realConnection) { resetter.accept(realConnection); ConnectionWrapper con = new ConnectionWrapper(realConnection, new ConnectionWrapper.ConnectionHandler(){ private boolean isCommit = false; @Override public void onClose(Connection connection) throws SQLException { if(isCommit == false || connection.getAutoCommit()) { connection.rollback(); } freeConnections.add(connection); } @Override public void onCommit(Connection connection) throws SQLException { isCommit = true; connection.commit(); } @Override public void onRollback(Connection connection) throws SQLException { isCommit = true; connection.rollback(); } @Override public void onAbort(Connection connection, Executor executor) throws SQLException { activeConnections--; connection.abort(executor); } }); return con; } public synchronized void close() { int inuse = activeConnections - freeConnections.size(); if(inuse > 0) { log.warning("Closing the connection pool with " + inuse + " connections still in use"); } else { log.info("Closing the connection pool with " + activeConnections + " open connections"); } while(activeConnections > 0) { Connection con = null; try { for(int t = 0; t < 20; t++) { con = freeConnections.poll(1000, TimeUnit.MILLISECONDS); if(con != null) { break; } log.warning("Waiting for the release of a connection"); } try { con.close(); } catch(SQLException e) { e.printStackTrace(); } activeConnections--; } catch(InterruptedException e) { log.info("Waiting for connections to close"); } } } }
138254_20
package com.persistentbit.string; import com.persistentbit.code.annotations.NotNullable; import com.persistentbit.code.annotations.Nullable; import com.persistentbit.functions.UNamed; import com.persistentbit.logging.Log; import java.text.Normalizer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * General String utilities, because we all have to have our own StringUtils version */ public final class UString{ /** * Takes a raw string and converts it to a java code string:<br> * <ul> * <li>tab to \t</li> * <li>newline to \n</li> * <li>cr to \r</li> * <li>\ to \\</li> * <li>backspace to \b</li> * <li>" to \"</li> * <li>\ to \'</li> * </ul> * * @param s The unescaped string (can't be null) * * @return The escaped string * * @see #unEscapeJavaString(String) */ public static String escapeToJavaString(String s) { return Log.function(s).code(l -> { Objects.requireNonNull(s, "Can't escape a null string"); StringBuilder sb = new StringBuilder(s.length() + 4); for(int t = 0; t < s.length(); t++) { char c = s.charAt(t); if(c == '\t') { sb.append("\\t"); } else if(c == '\n') { sb.append("\\n"); } else if(c == '\r') { sb.append("\\r"); } else if(c == '\\') { sb.append("\\\\"); } else if(c == '\b') { sb.append("\\b"); } else if(c == '\"') { sb.append("\\\""); } else if(c == '\'') { sb.append("\\\'"); } else { sb.append(c); } } return sb.toString(); }); } /** * Does the reverse of {@link #escapeToJavaString(String)} * * @param s The java source escaped string * * @return The unescaped string */ public static String unEscapeJavaString(String s) { return Log.function(s).code(l -> { Objects.requireNonNull(s, "Can't unescape a null string"); StringBuilder sb = new StringBuilder(10); boolean prevSpecial = false; for(int t = 0; t < s.length(); t++) { char c = s.charAt(t); if(prevSpecial) { switch(c) { case 't': sb.append('\t'); break; case '\\': sb.append('\\'); break; case 'n': sb.append('\n'); break; case 'r': sb.append('\r'); break; case 'b': sb.append('\b'); break; case '\"': sb.append('\"'); break; case '\'': sb.append('\''); break; default: sb.append('\\').append(c); break; } prevSpecial = false; } else { if(c == '\\') { prevSpecial = true; } else { //TOFIX prevSpecial is always false here if(prevSpecial) { sb.append('\\'); prevSpecial = false; } sb.append(c); } } } if(prevSpecial) { sb.append('\\'); } return sb.toString(); }); } /** * Convert the first character in the given string to UpperCase. * * @param s String to convert, can't be null * * @return The new string with the first character in uppercase and the rest as it was. */ public static String firstUpperCase(@NotNullable String s) { Objects.requireNonNull(s); if(s.isEmpty()) { return s; } return Character.toUpperCase(s.charAt(0)) + s.substring(1); } /** * Convert the first character in the given string to LowerCase. * * @param s String to convert, can't be null * * @return The new string with the first character in lowercase and the rest as it was. */ public static String firstLowerCase(@NotNullable String s) { Objects.requireNonNull(s); if(s.isEmpty()) { return s; } return Character.toLowerCase(s.charAt(0)) + s.substring(1); } /** * Drop the last charCount chars from a string * * @param txt A Non null string * @param charCount The number of characters to drop * * @return the string with dropped chars. */ public static String dropLast(@NotNullable String txt, int charCount) { Objects.requireNonNull(txt); if(txt.length() <= charCount) { return ""; } return txt.substring(0, txt.length() - charCount); } /** * Splits a string on a combination of \r\n \n orOf \r. * * @param s The String to split * * @return A PList of Strings without the nl orOf cr characters */ public static Collection<String> splitInLines(String s) { Objects.requireNonNull(s); List<String> res = new ArrayList<>(); for(String line : s.split("\\r\\n|\\n|\\r")) { res.add(line); } return res; } /** * converts aStringInCamelCase to a_string_in_snake * * @param s The Non null string in camelCase * * @return The snake version of the name * @see #snake_toCamelCase(String) */ public static String camelCaseTo_snake(String s) { Objects.requireNonNull(s); return s.replaceAll("([a-z])([A-Z]+)", "$1_$2"); } /** * converts a_string_in_snake to aStringInSnake * * @param s The Non null string in snake * * @return The camelCase version of the name * * @see #camelCaseTo_snake(String) */ public static String snake_toCamelCase(String s) { Objects.requireNonNull(s); StringBuilder res = new StringBuilder(); boolean nextUpper = false; for(int t = 0; t < s.length(); t++) { char c = s.charAt(t); if(nextUpper) { c = Character.toUpperCase(c); nextUpper = false; } if(c == '_') { nextUpper = true; } else { res.append(c); } } return res.toString(); } /** * Convert a String to a java identifier by<br> * replace all ' ' with '_' and removing all invalid java identifier characters.<br> * @param value The value to convert * @return A java identifier or an empty string */ public static String toJavaIdentifier(String value){ String res = ""; for(int t=0; t<value.length(); t++){ char c = value.charAt(t); if(c == ' '){ c = '_'; } boolean include = res.isEmpty() ? Character.isJavaIdentifierStart(c) : Character.isJavaIdentifierPart(c); if(include){ res = res + c; } } return res; } /** * Make the given string have a minimum length by left padding the String with the given char * * @param str The string * @param length The minimum length * @param padding The padding char * * @return The new string */ public static String padLeft(String str, int length, char padding) { while(str.length() < length) { str = padding + str; } return str; } /** * Make the given string have a minimum length by right padding the String with the given char * * @param str The string * @param length The minimum length * @param padding The padding char * * @return The new string */ public static String padRight(String str, int length, char padding) { while(str.length() < length) { str += padding; } return str; } public static @Nullable String present(@Nullable String org, int maxLength){ return present(org, maxLength, "..."); } public static @Nullable String present(@Nullable String org, int maxLength, String continueString) { if(org == null){ return null; } if(org.length() <=maxLength){ return org; } String str = org.substring(0, Math.min(org.length(),maxLength-1)); String kleiner = str; while(!kleiner.isEmpty() && "\t\n\r ".contains(kleiner.substring(kleiner.length()-1)) == false){ kleiner = kleiner.substring(0,kleiner.length()-1); } if(kleiner.isEmpty()){ kleiner = str; } return kleiner + continueString; } public static @Nullable String presentEscaped(@Nullable String org, int maxLength){ String presented = present(org,maxLength); return presented == null ? null : escapeToJavaString(presented); } /** * Split text on '-' and ' '.<br> * * @param longString The text to split * @param maxLength The maximum length per line * @return the result stream */ public static Collection<String> splitOnWhitespaceAndHyphen(String longString, int maxLength){ return splitStringOnMaxLength( longString, "(?<=\\-)|(?<=\\s)", false, maxLength, String::trim ); } /** * Split a text into lines with a maximum length.<br> * Expects a regular expression to find the split point.<br> * This regular expression should keep te delimiter, so use something * like (?=char) orOf (?&lt;=char) as regular expression. * Example with space and '-' as delimiters: '(?&lt;=\-)|(?&lt;=\s)" * @param longString The String to split * @param whiteSpaceRegEx Regular Expression for finding the split locations * @param splitLongWords Split words longer that the maximum length ? * @param maxLength The maximum length per lines * @param postProcessLine Function used for building the final line out of the constructed line. Could be used to trim the resulting line * @return List of lines */ public static Collection<String> splitStringOnMaxLength( String longString, String whiteSpaceRegEx, boolean splitLongWords, int maxLength, Function<String,String> postProcessLine ){ Objects.requireNonNull(longString,"longString"); if(maxLength <1){ throw new IllegalArgumentException("maxLength must be >=1"); } if(longString.length()<=maxLength){ return List.of(longString); } List<String> lines = new ArrayList<>(); String currentLine =""; for(String word : longString.split(whiteSpaceRegEx)){ String newLine = (currentLine.isEmpty() ? word : currentLine + word); String newLineProcessed = postProcessLine.apply(newLine); if(newLineProcessed.length() <= maxLength){ currentLine = newLine; } else { newLineProcessed = postProcessLine.apply(currentLine); if(newLineProcessed.isEmpty() == false) { lines.add(newLineProcessed); } currentLine = word; if(splitLongWords) { newLineProcessed = postProcessLine.apply(currentLine); while (newLineProcessed.length() > maxLength) { lines.add(postProcessLine.apply(currentLine.substring(0, maxLength))); currentLine = currentLine.substring(maxLength); newLineProcessed = postProcessLine.apply(currentLine); } } } } if(currentLine.isEmpty() == false){ lines.add(currentLine); } return lines; } public static String deleteWhitespace(String str){ Objects.requireNonNull(str); int cnt = str.length(); if(cnt == 0){ return str; } char[] dest = new char[cnt]; int resultLength = 0; for(int i=0; i<cnt; i++){ if (!Character.isWhitespace(str.charAt(i))) { dest[resultLength++] = str.charAt(i); } } if(resultLength == cnt){ return str; } return new String(dest,0,resultLength); } /** * Convert a String to a Searchable version without accents,spaces, all uppercase * @param normalString The String to convert * @return The Searchable version. */ public static String createSearchableString(String normalString) { Objects.requireNonNull(normalString, "omschrijving"); if(normalString.trim().isEmpty()){ return ""; } String alfaKey; alfaKey = deleteWhitespace(normalString);//delete alle whitespaces //replace alle speciale leestekens op een letter door de gewone letter alfaKey = alfaKey.replaceAll("\\p{Punct}", "");//delete alle andere non-word characters //ae oe ed. symbolen opvangen en replace door equivalent bv ae symbool word ae letters alfaKey = alfaKey.replaceAll("\306", "AE"); alfaKey = alfaKey.replaceAll("\346", "ae"); alfaKey = alfaKey.replaceAll("\330", "O"); alfaKey = alfaKey.replaceAll("\370", "o"); alfaKey = alfaKey.replaceAll("\226", "OE"); alfaKey = alfaKey.replaceAll("\234", "oe"); alfaKey = alfaKey.replaceAll("\320", "D"); alfaKey = alfaKey.replaceAll("\360", "d"); char[] normalized = Normalizer.normalize(alfaKey, Normalizer.Form.NFD).toCharArray(); if (normalized.length > alfaKey.length())//accented letters vervangen door gewone letters (bv é -> e) { StringBuilder sb = new StringBuilder(); for(char aNormalized : normalized) { String str = Character.toString(aNormalized); str = str.replaceAll("\\W", "");//de accented vervangen door een lege string sb.append(str); } alfaKey = sb.toString(); } return alfaKey.toUpperCase(); } public static final String NL = System.lineSeparator(); public static String join(String joinWith, String... textParts) { return join(joinWith, List.of(textParts)); } public static String join(String joinWith, Iterable<String> textParts) { StringBuilder res = new StringBuilder(); boolean first = true; for(String item : textParts){ if(first){ first = false; } else { res.append(joinWith); } res.append(item); } return res.toString(); } public static String joinLines(String... textParts) { return join(NL, textParts); } public static String joinLines(Iterable<String> textParts) { return join(NL, textParts); } public static int countCharOccurrence(String text, char c){ int count = 0; int len = Objects.requireNonNull(text).length(); for(int i = 0; i < len; i++) { if(text.charAt(i) == c) { count++; } } return count; } public static Function<String, String> replaceDelimited(String regExLeft, String regExName, String regExRight, Function<String,String> newContentSupplier){ String fullMatch = "(?:" + regExLeft + ")" + "((" + regExName +"){1}?)"+ "(?:" + regExRight + ")"; return UNamed.namedFunction("replaceDelimited(" + regExLeft + ", " + regExName + ", " + regExRight + ")", source -> { String result = source; while(true){ Matcher m = Pattern.compile(fullMatch, Pattern.MULTILINE).matcher(result); if(m.find() == false){ break; } result = result.substring(0,m.start()) + newContentSupplier.apply(m.group(2)) + result.substring(m.end()); } return result; }); } /* public static Result<Boolean> parseBoolean(String boolString){ return Result.function(boolString).code(l -> { if(boolString == null){ return Result.failure("boolString is null"); } String lowerBool = boolString.trim().toLowerCase(); return Result.success( lowerBool.equals("yes") || lowerBool.equals("true") || lowerBool.equals("y") || lowerBool.equals("1") ); }); }*/ }
persistentbit/persistentbit
persistent-libs/persistent-string/src/main/java/com/persistentbit/string/UString.java
4,890
//accented letters vervangen door gewone letters (bv é -> e)
line_comment
nl
package com.persistentbit.string; import com.persistentbit.code.annotations.NotNullable; import com.persistentbit.code.annotations.Nullable; import com.persistentbit.functions.UNamed; import com.persistentbit.logging.Log; import java.text.Normalizer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * General String utilities, because we all have to have our own StringUtils version */ public final class UString{ /** * Takes a raw string and converts it to a java code string:<br> * <ul> * <li>tab to \t</li> * <li>newline to \n</li> * <li>cr to \r</li> * <li>\ to \\</li> * <li>backspace to \b</li> * <li>" to \"</li> * <li>\ to \'</li> * </ul> * * @param s The unescaped string (can't be null) * * @return The escaped string * * @see #unEscapeJavaString(String) */ public static String escapeToJavaString(String s) { return Log.function(s).code(l -> { Objects.requireNonNull(s, "Can't escape a null string"); StringBuilder sb = new StringBuilder(s.length() + 4); for(int t = 0; t < s.length(); t++) { char c = s.charAt(t); if(c == '\t') { sb.append("\\t"); } else if(c == '\n') { sb.append("\\n"); } else if(c == '\r') { sb.append("\\r"); } else if(c == '\\') { sb.append("\\\\"); } else if(c == '\b') { sb.append("\\b"); } else if(c == '\"') { sb.append("\\\""); } else if(c == '\'') { sb.append("\\\'"); } else { sb.append(c); } } return sb.toString(); }); } /** * Does the reverse of {@link #escapeToJavaString(String)} * * @param s The java source escaped string * * @return The unescaped string */ public static String unEscapeJavaString(String s) { return Log.function(s).code(l -> { Objects.requireNonNull(s, "Can't unescape a null string"); StringBuilder sb = new StringBuilder(10); boolean prevSpecial = false; for(int t = 0; t < s.length(); t++) { char c = s.charAt(t); if(prevSpecial) { switch(c) { case 't': sb.append('\t'); break; case '\\': sb.append('\\'); break; case 'n': sb.append('\n'); break; case 'r': sb.append('\r'); break; case 'b': sb.append('\b'); break; case '\"': sb.append('\"'); break; case '\'': sb.append('\''); break; default: sb.append('\\').append(c); break; } prevSpecial = false; } else { if(c == '\\') { prevSpecial = true; } else { //TOFIX prevSpecial is always false here if(prevSpecial) { sb.append('\\'); prevSpecial = false; } sb.append(c); } } } if(prevSpecial) { sb.append('\\'); } return sb.toString(); }); } /** * Convert the first character in the given string to UpperCase. * * @param s String to convert, can't be null * * @return The new string with the first character in uppercase and the rest as it was. */ public static String firstUpperCase(@NotNullable String s) { Objects.requireNonNull(s); if(s.isEmpty()) { return s; } return Character.toUpperCase(s.charAt(0)) + s.substring(1); } /** * Convert the first character in the given string to LowerCase. * * @param s String to convert, can't be null * * @return The new string with the first character in lowercase and the rest as it was. */ public static String firstLowerCase(@NotNullable String s) { Objects.requireNonNull(s); if(s.isEmpty()) { return s; } return Character.toLowerCase(s.charAt(0)) + s.substring(1); } /** * Drop the last charCount chars from a string * * @param txt A Non null string * @param charCount The number of characters to drop * * @return the string with dropped chars. */ public static String dropLast(@NotNullable String txt, int charCount) { Objects.requireNonNull(txt); if(txt.length() <= charCount) { return ""; } return txt.substring(0, txt.length() - charCount); } /** * Splits a string on a combination of \r\n \n orOf \r. * * @param s The String to split * * @return A PList of Strings without the nl orOf cr characters */ public static Collection<String> splitInLines(String s) { Objects.requireNonNull(s); List<String> res = new ArrayList<>(); for(String line : s.split("\\r\\n|\\n|\\r")) { res.add(line); } return res; } /** * converts aStringInCamelCase to a_string_in_snake * * @param s The Non null string in camelCase * * @return The snake version of the name * @see #snake_toCamelCase(String) */ public static String camelCaseTo_snake(String s) { Objects.requireNonNull(s); return s.replaceAll("([a-z])([A-Z]+)", "$1_$2"); } /** * converts a_string_in_snake to aStringInSnake * * @param s The Non null string in snake * * @return The camelCase version of the name * * @see #camelCaseTo_snake(String) */ public static String snake_toCamelCase(String s) { Objects.requireNonNull(s); StringBuilder res = new StringBuilder(); boolean nextUpper = false; for(int t = 0; t < s.length(); t++) { char c = s.charAt(t); if(nextUpper) { c = Character.toUpperCase(c); nextUpper = false; } if(c == '_') { nextUpper = true; } else { res.append(c); } } return res.toString(); } /** * Convert a String to a java identifier by<br> * replace all ' ' with '_' and removing all invalid java identifier characters.<br> * @param value The value to convert * @return A java identifier or an empty string */ public static String toJavaIdentifier(String value){ String res = ""; for(int t=0; t<value.length(); t++){ char c = value.charAt(t); if(c == ' '){ c = '_'; } boolean include = res.isEmpty() ? Character.isJavaIdentifierStart(c) : Character.isJavaIdentifierPart(c); if(include){ res = res + c; } } return res; } /** * Make the given string have a minimum length by left padding the String with the given char * * @param str The string * @param length The minimum length * @param padding The padding char * * @return The new string */ public static String padLeft(String str, int length, char padding) { while(str.length() < length) { str = padding + str; } return str; } /** * Make the given string have a minimum length by right padding the String with the given char * * @param str The string * @param length The minimum length * @param padding The padding char * * @return The new string */ public static String padRight(String str, int length, char padding) { while(str.length() < length) { str += padding; } return str; } public static @Nullable String present(@Nullable String org, int maxLength){ return present(org, maxLength, "..."); } public static @Nullable String present(@Nullable String org, int maxLength, String continueString) { if(org == null){ return null; } if(org.length() <=maxLength){ return org; } String str = org.substring(0, Math.min(org.length(),maxLength-1)); String kleiner = str; while(!kleiner.isEmpty() && "\t\n\r ".contains(kleiner.substring(kleiner.length()-1)) == false){ kleiner = kleiner.substring(0,kleiner.length()-1); } if(kleiner.isEmpty()){ kleiner = str; } return kleiner + continueString; } public static @Nullable String presentEscaped(@Nullable String org, int maxLength){ String presented = present(org,maxLength); return presented == null ? null : escapeToJavaString(presented); } /** * Split text on '-' and ' '.<br> * * @param longString The text to split * @param maxLength The maximum length per line * @return the result stream */ public static Collection<String> splitOnWhitespaceAndHyphen(String longString, int maxLength){ return splitStringOnMaxLength( longString, "(?<=\\-)|(?<=\\s)", false, maxLength, String::trim ); } /** * Split a text into lines with a maximum length.<br> * Expects a regular expression to find the split point.<br> * This regular expression should keep te delimiter, so use something * like (?=char) orOf (?&lt;=char) as regular expression. * Example with space and '-' as delimiters: '(?&lt;=\-)|(?&lt;=\s)" * @param longString The String to split * @param whiteSpaceRegEx Regular Expression for finding the split locations * @param splitLongWords Split words longer that the maximum length ? * @param maxLength The maximum length per lines * @param postProcessLine Function used for building the final line out of the constructed line. Could be used to trim the resulting line * @return List of lines */ public static Collection<String> splitStringOnMaxLength( String longString, String whiteSpaceRegEx, boolean splitLongWords, int maxLength, Function<String,String> postProcessLine ){ Objects.requireNonNull(longString,"longString"); if(maxLength <1){ throw new IllegalArgumentException("maxLength must be >=1"); } if(longString.length()<=maxLength){ return List.of(longString); } List<String> lines = new ArrayList<>(); String currentLine =""; for(String word : longString.split(whiteSpaceRegEx)){ String newLine = (currentLine.isEmpty() ? word : currentLine + word); String newLineProcessed = postProcessLine.apply(newLine); if(newLineProcessed.length() <= maxLength){ currentLine = newLine; } else { newLineProcessed = postProcessLine.apply(currentLine); if(newLineProcessed.isEmpty() == false) { lines.add(newLineProcessed); } currentLine = word; if(splitLongWords) { newLineProcessed = postProcessLine.apply(currentLine); while (newLineProcessed.length() > maxLength) { lines.add(postProcessLine.apply(currentLine.substring(0, maxLength))); currentLine = currentLine.substring(maxLength); newLineProcessed = postProcessLine.apply(currentLine); } } } } if(currentLine.isEmpty() == false){ lines.add(currentLine); } return lines; } public static String deleteWhitespace(String str){ Objects.requireNonNull(str); int cnt = str.length(); if(cnt == 0){ return str; } char[] dest = new char[cnt]; int resultLength = 0; for(int i=0; i<cnt; i++){ if (!Character.isWhitespace(str.charAt(i))) { dest[resultLength++] = str.charAt(i); } } if(resultLength == cnt){ return str; } return new String(dest,0,resultLength); } /** * Convert a String to a Searchable version without accents,spaces, all uppercase * @param normalString The String to convert * @return The Searchable version. */ public static String createSearchableString(String normalString) { Objects.requireNonNull(normalString, "omschrijving"); if(normalString.trim().isEmpty()){ return ""; } String alfaKey; alfaKey = deleteWhitespace(normalString);//delete alle whitespaces //replace alle speciale leestekens op een letter door de gewone letter alfaKey = alfaKey.replaceAll("\\p{Punct}", "");//delete alle andere non-word characters //ae oe ed. symbolen opvangen en replace door equivalent bv ae symbool word ae letters alfaKey = alfaKey.replaceAll("\306", "AE"); alfaKey = alfaKey.replaceAll("\346", "ae"); alfaKey = alfaKey.replaceAll("\330", "O"); alfaKey = alfaKey.replaceAll("\370", "o"); alfaKey = alfaKey.replaceAll("\226", "OE"); alfaKey = alfaKey.replaceAll("\234", "oe"); alfaKey = alfaKey.replaceAll("\320", "D"); alfaKey = alfaKey.replaceAll("\360", "d"); char[] normalized = Normalizer.normalize(alfaKey, Normalizer.Form.NFD).toCharArray(); if (normalized.length > alfaKey.length())//accented letters<SUF> { StringBuilder sb = new StringBuilder(); for(char aNormalized : normalized) { String str = Character.toString(aNormalized); str = str.replaceAll("\\W", "");//de accented vervangen door een lege string sb.append(str); } alfaKey = sb.toString(); } return alfaKey.toUpperCase(); } public static final String NL = System.lineSeparator(); public static String join(String joinWith, String... textParts) { return join(joinWith, List.of(textParts)); } public static String join(String joinWith, Iterable<String> textParts) { StringBuilder res = new StringBuilder(); boolean first = true; for(String item : textParts){ if(first){ first = false; } else { res.append(joinWith); } res.append(item); } return res.toString(); } public static String joinLines(String... textParts) { return join(NL, textParts); } public static String joinLines(Iterable<String> textParts) { return join(NL, textParts); } public static int countCharOccurrence(String text, char c){ int count = 0; int len = Objects.requireNonNull(text).length(); for(int i = 0; i < len; i++) { if(text.charAt(i) == c) { count++; } } return count; } public static Function<String, String> replaceDelimited(String regExLeft, String regExName, String regExRight, Function<String,String> newContentSupplier){ String fullMatch = "(?:" + regExLeft + ")" + "((" + regExName +"){1}?)"+ "(?:" + regExRight + ")"; return UNamed.namedFunction("replaceDelimited(" + regExLeft + ", " + regExName + ", " + regExRight + ")", source -> { String result = source; while(true){ Matcher m = Pattern.compile(fullMatch, Pattern.MULTILINE).matcher(result); if(m.find() == false){ break; } result = result.substring(0,m.start()) + newContentSupplier.apply(m.group(2)) + result.substring(m.end()); } return result; }); } /* public static Result<Boolean> parseBoolean(String boolString){ return Result.function(boolString).code(l -> { if(boolString == null){ return Result.failure("boolString is null"); } String lowerBool = boolString.trim().toLowerCase(); return Result.success( lowerBool.equals("yes") || lowerBool.equals("true") || lowerBool.equals("y") || lowerBool.equals("1") ); }); }*/ }
54657_8
/* * Copyright 2015 - Per Wendel * * 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 spark.ssl; /** * SSL Stores */ public class SslStores { protected String keystoreFile; protected String keystorePassword; protected String certAlias; protected String truststoreFile; protected String truststorePassword; protected boolean needsClientCert; /** * Creates a Stores instance. * * @param keystoreFile the keystoreFile * @param keystorePassword the keystorePassword * @param truststoreFile the truststoreFile * @param truststorePassword the truststorePassword * @return the SslStores instance. */ public static SslStores create(String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword) { return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false); } public static SslStores create(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword) { return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false); } public static SslStores create(String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword, boolean needsClientCert) { return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert); } public static SslStores create(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword, boolean needsClientCert) { return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert); } private SslStores(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword, boolean needsClientCert) { this.keystoreFile = keystoreFile; this.keystorePassword = keystorePassword; this.certAlias = certAlias; this.truststoreFile = truststoreFile; this.truststorePassword = truststorePassword; this.needsClientCert = needsClientCert; } /** * @return keystoreFile */ public String keystoreFile() { return keystoreFile; } /** * @return keystorePassword */ public String keystorePassword() { return keystorePassword; } /** * @return certAlias */ public String certAlias() { return certAlias; } /** * @return trustStoreFile */ public String trustStoreFile() { return truststoreFile; } /** * @return trustStorePassword */ public String trustStorePassword() { return truststorePassword; } /** * @return needsClientCert */ public boolean needsClientCert() { return needsClientCert; } }
perwendel/spark
src/main/java/spark/ssl/SslStores.java
994
/** * @return needsClientCert */
block_comment
nl
/* * Copyright 2015 - Per Wendel * * 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 spark.ssl; /** * SSL Stores */ public class SslStores { protected String keystoreFile; protected String keystorePassword; protected String certAlias; protected String truststoreFile; protected String truststorePassword; protected boolean needsClientCert; /** * Creates a Stores instance. * * @param keystoreFile the keystoreFile * @param keystorePassword the keystorePassword * @param truststoreFile the truststoreFile * @param truststorePassword the truststorePassword * @return the SslStores instance. */ public static SslStores create(String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword) { return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, false); } public static SslStores create(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword) { return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, false); } public static SslStores create(String keystoreFile, String keystorePassword, String truststoreFile, String truststorePassword, boolean needsClientCert) { return new SslStores(keystoreFile, keystorePassword, null, truststoreFile, truststorePassword, needsClientCert); } public static SslStores create(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword, boolean needsClientCert) { return new SslStores(keystoreFile, keystorePassword, certAlias, truststoreFile, truststorePassword, needsClientCert); } private SslStores(String keystoreFile, String keystorePassword, String certAlias, String truststoreFile, String truststorePassword, boolean needsClientCert) { this.keystoreFile = keystoreFile; this.keystorePassword = keystorePassword; this.certAlias = certAlias; this.truststoreFile = truststoreFile; this.truststorePassword = truststorePassword; this.needsClientCert = needsClientCert; } /** * @return keystoreFile */ public String keystoreFile() { return keystoreFile; } /** * @return keystorePassword */ public String keystorePassword() { return keystorePassword; } /** * @return certAlias */ public String certAlias() { return certAlias; } /** * @return trustStoreFile */ public String trustStoreFile() { return truststoreFile; } /** * @return trustStorePassword */ public String trustStorePassword() { return truststorePassword; } /** * @return needsClientCert <SUF>*/ public boolean needsClientCert() { return needsClientCert; } }
33327_20
package jmri.jmrix.zimo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents a single command or response to the Zimo Binary Protocol. * <p> * Content is represented with ints to avoid the problems with sign-extension * that bytes have, and because a Java char is actually a variable number of * bytes in Unicode. * * @author Kevin Dickerson Copyright (C) 2014 * * Adapted by Sip Bosch for use with zimo MX-1 * */ public class Mx1Message extends jmri.jmrix.NetMessage { public Mx1Message(int len) { this(len, Mx1Packetizer.ASCII); } /** * Create a new object, representing a specific-length message. * * @param len Total bytes in message, including opcode and * error-detection byte. * @param protocol one of {@link Mx1Packetizer#ASCII} or * {@link Mx1Packetizer#BINARY} */ public Mx1Message(int len, boolean protocol) { super(len); this.protocol = protocol; if (!protocol) { if (len > 15 || len < 0) { log.error("Invalid length in ctor: {}", len); } } } boolean protocol = Mx1Packetizer.ASCII; //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(Integer[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, contents[i]); } } //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(byte[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, (contents[i] & 0xff)); } } public boolean getLongMessage() { if (protocol == Mx1Packetizer.BINARY) { if ((getElement(1) & 0x80) == 0x80) { return true; } } return false; } final static int PRIMARY = 0x00; final static int ACKREP1 = 0x40; final static int REPLY2 = 0x20; final static int ACK2 = 0x60; /** * Indicates where the message is to/from in the header byte. * <p> * Up to JMRI 4.3.5, this was doing {@code ((mod & MX1) == MX1)} for the * first test, which is really 0 == 0 and always true. At that point it was * changed to just check the bottom two bits. * * @return one of {@link #MX1}, {@link #MX8}, {@link #MX9} or 0x0F */ public int getModule() { int mod = getElement(1) & 0x0F; if ((mod & 0x03) == MX1) { return MX1; } if ((mod & 0x03) == MX8) { return MX8; } if ((mod & 0x03) == MX9) { return MX9; } return mod; } public int getMessageType() { return getElement(1) & 0x60; } public int getPrimaryMessage() { return getElement(2); } /** * Message to/from Command Station MX1 */ static final int MX1 = 0x00; /** * Message to/from Accessory module MX8 */ static final int MX8 = 0x01; /** * Message to/from Track Section module MX9 */ static final int MX9 = 0x02; /** * Indicates the message source is a command station. {@value #CS} * * @see #messageSource() */ final static boolean CS = true; /** * Indicates the message source is a command station. {@value #PC} * * @see #messageSource() */ final static boolean PC = false; /** * Indicates the source of the message. * * @return {@link #PC} or {@link #CS} */ public boolean messageSource() { if ((getElement(0) & 0x08) == 0x08) { return PC; } return CS; } long timeStamp = 0L; protected long getTimeStamp() { return timeStamp; } protected void setTimeStamp(long ts) { timeStamp = ts; } int retries = 3; public int getRetry() { return retries; } public void setRetries(int i) { retries = i; } //byte sequenceNo = 0x00; public boolean replyL1Expected() { return true; } byte[] rawPacket; public void setRawPacket(byte[] b) { rawPacket = b; } protected byte[] getRawPacket() { return rawPacket; } public void setSequenceNo(byte s) { setElement(0, (s & 0xff)); } public int getSequenceNo() { return (getElement(0) & 0xff); } boolean crcError = false; public void setCRCError() { crcError = true; } public boolean isCRCError() { return crcError; } /** * Check if the message has a valid parity (actually check for CR or LF as * end of message). * * @return true if message has correct parity bit */ @Override public boolean checkParity() { //javax.swing.JOptionPane.showMessageDialog(null, "A-Programma komt tot hier!"); int len = getNumDataElements(); return (getElement(len - 1) == (0x0D | 0x0A)); } // programma komt hier volgens mij nooit // in fact set CR as end of message @Override public void setParity() { javax.swing.JOptionPane.showMessageDialog(null, "B-Programma komt tot hier!"); int len = getNumDataElements(); setElement(len - 1, 0x0D); } // decode messages of a particular form public String getStringMsg() { StringBuilder txt = new StringBuilder(); if (protocol == Mx1Packetizer.BINARY) { if (isCRCError()) { txt.append(" === CRC ERROR === "); } if (getNumDataElements() <= 3) { txt.append("Short Packet "); return txt.toString(); } if ((getElement(1) & 0x10) == 0x10) { txt.append("From PC"); } else { txt.append("From CS"); } txt.append(" Seq ").append(getElement(0) & 0xff); if (getLongMessage()) { txt.append(" (L)"); } else { txt.append(" (S)"); } int offset; switch (getMessageType()) { case PRIMARY: txt.append(" Prim"); break; case ACKREP1: txt.append(" Ack/Reply 1"); break; case REPLY2: txt.append(" Reply 2"); break; case ACK2: txt.append(" Ack 2"); break; default: txt.append(" Unknown msg"); break; } if (getModule() == MX1) { //was (getElement(1)&0x00) == 0x00 txt.append(" to/from CS (MX1)"); switch (getPrimaryMessage()) { //was getElement(2) case TRACKCTL: offset = 0; if (getMessageType() == ACKREP1) { offset++; } txt.append(" Track Control "); if ((getElement(3 + offset) & 0x03) == 0x03) { txt.append(" Query Track Status "); } else if ((getElement(3 + offset) & 0x01) == 0x01) { txt.append(" Turn Track Off "); } else if ((getElement(3 + offset) & 0x02) == 0x02) { txt.append(" Turn Track On "); } else { txt.append(" Stop All Locos "); } break; case 3: txt.append(" Loco Control : "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(6) & 0x20) == 0x20) ? " Fwd " : " Rev "); txt.append(((getElement(6) & 0x10) == 0x10) ? " F0: On " : " F0: Off "); txt.append(decodeFunctionStates(getElement(7), getElement(8))); } break; case 4: txt.append(" Loco Funct "); break; case 5: txt.append(" Loco Acc/Dec "); break; case 6: txt.append(" Shuttle "); break; case 7: txt.append(" Accessory "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(5) & 0x04) == 0x04) ? " Thrown " : " Closed "); } break; case 8: txt.append(" Loco Status "); break; case 9: txt.append(" Acc Status "); break; case 10: txt.append(" Address Control "); break; case 11: txt.append(" CS State "); break; case 12: txt.append(" Read/Write CS CV "); break; case 13: txt.append(" CS Equip Query "); break; case 17: txt.append(" Tool Type "); break; case PROGCMD: offset = 0; if (getMessageType() == ACKREP1) { txt.append(" Prog CV "); break; } if (getMessageType() == REPLY2) { offset++; } if (getMessageType() == ACK2) { txt.append("Ack to CS Message"); break; } if (getNumDataElements() == 7 && getMessageType() == ACKREP1) { txt.append(" Error Occured "); txt.append(getErrorCode(getElement(6))); txt.append(" Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); break; } /*if(getNumDataElements()<7){ txt.append(" Ack L1 "); break; }*/ if ((getMessageType() == PRIMARY && getNumDataElements() == 8)) { txt.append(" Write CV "); } else { txt.append(" Read CV "); } txt.append("Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); if ((getElement(3 + offset) & 0x80) == 0x80) { txt.append(" DCC"); } int cv = (((getElement(5 + offset) & 0xff) << 8) + (getElement(6 + offset) & 0xff)); txt.append(" CV: ").append(cv); if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet txt.append(" Set To: ").append(getElement(7 + offset) & 0xff); } break; case 254: txt.append(" Cur Acc Memory "); break; case 255: txt.append(" Cur Loco Memory "); break; default: txt.append(" Unknown "); } } else if ((getElement(1) & 0x01) == 0x01) { txt.append(" to/from Accessory Mod (MX8)"); } else if ((getElement(1) & 0x02) == 0x02) { txt.append(" to/from Track Section (MX9)"); } else { txt.append(" unknown"); } } //int type = getElement(2); return txt.toString(); } private String decodeFunctionStates(int cData2, int cData3) { StringBuilder txt = new StringBuilder(); txt.append(((cData2 & 0x1) == 0x1) ? " F1: On " : " F1: Off "); txt.append(((cData2 & 0x2) == 0x2) ? " F2: On " : " F2: Off "); txt.append(((cData2 & 0x4) == 0x4) ? " F3: On " : " F3: Off "); txt.append(((cData2 & 0x8) == 0x8) ? " F4: On " : " F4: Off "); txt.append(((cData2 & 0x10) == 0x10) ? " F5: On " : " F5: Off "); txt.append(((cData2 & 0x20) == 0x20) ? " F6: On " : " F6: Off "); txt.append(((cData2 & 0x40) == 0x40) ? " F7: On " : " F7: Off "); txt.append(((cData2 & 0x80) == 0x80) ? " F8: On " : " F8: Off "); txt.append(((cData3 & 0x1) == 0x1) ? " F9: On " : " F9: Off "); txt.append(((cData3 & 0x2) == 0x2) ? " F10: On " : " F10: Off "); txt.append(((cData3 & 0x4) == 0x4) ? " F11: On " : " F11: Off "); txt.append(((cData3 & 0x8) == 0x8) ? " F12: On " : " F12: Off "); return txt.toString(); } public int getLocoAddress() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() == (4 + offset)) { return getLocoAddress(getElement(3 + offset), getElement(4 + offset)); } return -1; } public int getCvValue() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet return (getElement(7 + offset) & 0xff); } return -1; } int getLocoAddress(int hi, int lo) { hi = hi & 0x3F; if (hi == 0) { return lo; } else { hi = (((hi & 255) - 192) << 8); hi = hi + (lo & 255); return hi; } } String getErrorCode(int i) { switch (i) { case NO_ERROR: return "No Error"; case ERR_ADDRESS: return "Invalid Address"; case ERR_INDEX: return "Invalid Index"; case ERR_FORWARD: return "Could not be Forwarded"; case ERR_BUSY: return "CMD Busy"; case ERR_NO_MOT: return "Motorola Jump Off"; case ERR_NO_DCC: return "DCC Jump Off"; case ERR_CV_ADDRESS: return "Invalid CV"; case ERR_SECTION: return "Invalid Section"; case ERR_NO_MODUL: return "No Module Found"; case ERR_MESSAGE: return "Error in Message"; case ERR_SPEED: return "Invalid Speed"; default: return "Unknown Error"; } } final static int NO_ERROR = 0x00; final static int ERR_ADDRESS = 0x01; final static int ERR_INDEX = 0x02; final static int ERR_FORWARD = 0x03; final static int ERR_BUSY = 0x04; final static int ERR_NO_MOT = 0x05; final static int ERR_NO_DCC = 0x06; final static int ERR_CV_ADDRESS = 0x07; final static int ERR_SECTION = 0x08; final static int ERR_NO_MODUL = 0x09; final static int ERR_MESSAGE = 0x0a; final static int ERR_SPEED = 0x0b; final static int TRACKCTL = 0x02; final static int PROGCMD = 0x13; final static int LOCOCMD = 0x03; final static int ACCCMD = 0x07; static public Mx1Message getCmdStnDetails() { Mx1Message m = new Mx1Message(4); m.setElement(1, 0x10); m.setElement(2, 0x13); m.setElement(3, 0x00); return m; } /** * Set Track Power Off/Emergency Stop * * @return MrcMessage */ static public Mx1Message setPowerOff() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x01); return m; } static public Mx1Message setPowerOn() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x02); return m; } static public Mx1Message getTrackStatus() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x03); return m; } /** * Create a message to read or write a CV. * * @param locoAddress address of the loco * @param cv CV to read or write * @param value value to write to CV, if -1 CV is read * @param dcc true if decoder is DCC; false if decoder is Motorola * @return a message to read or write a CV */ // javadoc did indicate locoAddress could be blank to use programming track, but that's not possible with an int static public Mx1Message getDecProgCmd(int locoAddress, int cv, int value, boolean dcc) { Mx1Message m; if (value == -1) { m = new Mx1Message(7, Mx1Packetizer.BINARY); } else { m = new Mx1Message(8, Mx1Packetizer.BINARY); } m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, PROGCMD); int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, cv >> 8); m.setElement(6, cv & 0xff); if (value != -1) { m.setElement(7, value); } return m; } /** * Create a locomotive control message. * * @param locoAddress address of the loco * @param speed Speed Step in the actual Speed Step System * @param dcc true if decoder is DCC; false if decoder is Motorola * @param cData1 ??? * @param cData2 functions output 0-7 * @param cData3 functions output 9-12 * @return message controlling a locomotive */ static public Mx1Message getLocoControl(int locoAddress, int speed, boolean dcc, int cData1, int cData2, int cData3) { Mx1Message m = new Mx1Message(9, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, LOCOCMD); //High add 80 to indicate DCC int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, speed); m.setElement(6, cData1); m.setElement(7, cData2); m.setElement(8, cData3); return m; } static public Mx1Message getSwitchMsg(int accAddress, int setting, boolean dcc) { Mx1Message m = new Mx1Message(6, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, ACCCMD); //High add 80 to indicate DCC int accHi = accAddress >> 8; if (dcc) { accHi = accHi + 128; } else { accHi = accHi + 64; } m.setElement(3, (accHi)); m.setElement(4, (accAddress & 0xff)); m.setElement(5, 0x00); if (setting == jmri.Turnout.THROWN) { m.setElement(5, 0x04); } return m; } // initialize logging private final static Logger log = LoggerFactory.getLogger(Mx1Message.class); }
petecressman/JMRI
java/src/jmri/jmrix/zimo/Mx1Message.java
6,427
//int type = getElement(2);
line_comment
nl
package jmri.jmrix.zimo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Represents a single command or response to the Zimo Binary Protocol. * <p> * Content is represented with ints to avoid the problems with sign-extension * that bytes have, and because a Java char is actually a variable number of * bytes in Unicode. * * @author Kevin Dickerson Copyright (C) 2014 * * Adapted by Sip Bosch for use with zimo MX-1 * */ public class Mx1Message extends jmri.jmrix.NetMessage { public Mx1Message(int len) { this(len, Mx1Packetizer.ASCII); } /** * Create a new object, representing a specific-length message. * * @param len Total bytes in message, including opcode and * error-detection byte. * @param protocol one of {@link Mx1Packetizer#ASCII} or * {@link Mx1Packetizer#BINARY} */ public Mx1Message(int len, boolean protocol) { super(len); this.protocol = protocol; if (!protocol) { if (len > 15 || len < 0) { log.error("Invalid length in ctor: {}", len); } } } boolean protocol = Mx1Packetizer.ASCII; //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(Integer[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, contents[i]); } } //Version 5 and above allow for a message size greater than 15 bytes public Mx1Message(byte[] contents) { super(contents.length); protocol = Mx1Packetizer.BINARY; for (int i = 0; i < contents.length; i++) { this.setElement(i, (contents[i] & 0xff)); } } public boolean getLongMessage() { if (protocol == Mx1Packetizer.BINARY) { if ((getElement(1) & 0x80) == 0x80) { return true; } } return false; } final static int PRIMARY = 0x00; final static int ACKREP1 = 0x40; final static int REPLY2 = 0x20; final static int ACK2 = 0x60; /** * Indicates where the message is to/from in the header byte. * <p> * Up to JMRI 4.3.5, this was doing {@code ((mod & MX1) == MX1)} for the * first test, which is really 0 == 0 and always true. At that point it was * changed to just check the bottom two bits. * * @return one of {@link #MX1}, {@link #MX8}, {@link #MX9} or 0x0F */ public int getModule() { int mod = getElement(1) & 0x0F; if ((mod & 0x03) == MX1) { return MX1; } if ((mod & 0x03) == MX8) { return MX8; } if ((mod & 0x03) == MX9) { return MX9; } return mod; } public int getMessageType() { return getElement(1) & 0x60; } public int getPrimaryMessage() { return getElement(2); } /** * Message to/from Command Station MX1 */ static final int MX1 = 0x00; /** * Message to/from Accessory module MX8 */ static final int MX8 = 0x01; /** * Message to/from Track Section module MX9 */ static final int MX9 = 0x02; /** * Indicates the message source is a command station. {@value #CS} * * @see #messageSource() */ final static boolean CS = true; /** * Indicates the message source is a command station. {@value #PC} * * @see #messageSource() */ final static boolean PC = false; /** * Indicates the source of the message. * * @return {@link #PC} or {@link #CS} */ public boolean messageSource() { if ((getElement(0) & 0x08) == 0x08) { return PC; } return CS; } long timeStamp = 0L; protected long getTimeStamp() { return timeStamp; } protected void setTimeStamp(long ts) { timeStamp = ts; } int retries = 3; public int getRetry() { return retries; } public void setRetries(int i) { retries = i; } //byte sequenceNo = 0x00; public boolean replyL1Expected() { return true; } byte[] rawPacket; public void setRawPacket(byte[] b) { rawPacket = b; } protected byte[] getRawPacket() { return rawPacket; } public void setSequenceNo(byte s) { setElement(0, (s & 0xff)); } public int getSequenceNo() { return (getElement(0) & 0xff); } boolean crcError = false; public void setCRCError() { crcError = true; } public boolean isCRCError() { return crcError; } /** * Check if the message has a valid parity (actually check for CR or LF as * end of message). * * @return true if message has correct parity bit */ @Override public boolean checkParity() { //javax.swing.JOptionPane.showMessageDialog(null, "A-Programma komt tot hier!"); int len = getNumDataElements(); return (getElement(len - 1) == (0x0D | 0x0A)); } // programma komt hier volgens mij nooit // in fact set CR as end of message @Override public void setParity() { javax.swing.JOptionPane.showMessageDialog(null, "B-Programma komt tot hier!"); int len = getNumDataElements(); setElement(len - 1, 0x0D); } // decode messages of a particular form public String getStringMsg() { StringBuilder txt = new StringBuilder(); if (protocol == Mx1Packetizer.BINARY) { if (isCRCError()) { txt.append(" === CRC ERROR === "); } if (getNumDataElements() <= 3) { txt.append("Short Packet "); return txt.toString(); } if ((getElement(1) & 0x10) == 0x10) { txt.append("From PC"); } else { txt.append("From CS"); } txt.append(" Seq ").append(getElement(0) & 0xff); if (getLongMessage()) { txt.append(" (L)"); } else { txt.append(" (S)"); } int offset; switch (getMessageType()) { case PRIMARY: txt.append(" Prim"); break; case ACKREP1: txt.append(" Ack/Reply 1"); break; case REPLY2: txt.append(" Reply 2"); break; case ACK2: txt.append(" Ack 2"); break; default: txt.append(" Unknown msg"); break; } if (getModule() == MX1) { //was (getElement(1)&0x00) == 0x00 txt.append(" to/from CS (MX1)"); switch (getPrimaryMessage()) { //was getElement(2) case TRACKCTL: offset = 0; if (getMessageType() == ACKREP1) { offset++; } txt.append(" Track Control "); if ((getElement(3 + offset) & 0x03) == 0x03) { txt.append(" Query Track Status "); } else if ((getElement(3 + offset) & 0x01) == 0x01) { txt.append(" Turn Track Off "); } else if ((getElement(3 + offset) & 0x02) == 0x02) { txt.append(" Turn Track On "); } else { txt.append(" Stop All Locos "); } break; case 3: txt.append(" Loco Control : "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(6) & 0x20) == 0x20) ? " Fwd " : " Rev "); txt.append(((getElement(6) & 0x10) == 0x10) ? " F0: On " : " F0: Off "); txt.append(decodeFunctionStates(getElement(7), getElement(8))); } break; case 4: txt.append(" Loco Funct "); break; case 5: txt.append(" Loco Acc/Dec "); break; case 6: txt.append(" Shuttle "); break; case 7: txt.append(" Accessory "); if (getMessageType() == PRIMARY) { txt.append(getLocoAddress(getElement((3)), getElement(4))); txt.append(((getElement(5) & 0x04) == 0x04) ? " Thrown " : " Closed "); } break; case 8: txt.append(" Loco Status "); break; case 9: txt.append(" Acc Status "); break; case 10: txt.append(" Address Control "); break; case 11: txt.append(" CS State "); break; case 12: txt.append(" Read/Write CS CV "); break; case 13: txt.append(" CS Equip Query "); break; case 17: txt.append(" Tool Type "); break; case PROGCMD: offset = 0; if (getMessageType() == ACKREP1) { txt.append(" Prog CV "); break; } if (getMessageType() == REPLY2) { offset++; } if (getMessageType() == ACK2) { txt.append("Ack to CS Message"); break; } if (getNumDataElements() == 7 && getMessageType() == ACKREP1) { txt.append(" Error Occured "); txt.append(getErrorCode(getElement(6))); txt.append(" Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); break; } /*if(getNumDataElements()<7){ txt.append(" Ack L1 "); break; }*/ if ((getMessageType() == PRIMARY && getNumDataElements() == 8)) { txt.append(" Write CV "); } else { txt.append(" Read CV "); } txt.append("Loco: ").append(getLocoAddress(getElement((3 + offset)), getElement(4 + offset))); if ((getElement(3 + offset) & 0x80) == 0x80) { txt.append(" DCC"); } int cv = (((getElement(5 + offset) & 0xff) << 8) + (getElement(6 + offset) & 0xff)); txt.append(" CV: ").append(cv); if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet txt.append(" Set To: ").append(getElement(7 + offset) & 0xff); } break; case 254: txt.append(" Cur Acc Memory "); break; case 255: txt.append(" Cur Loco Memory "); break; default: txt.append(" Unknown "); } } else if ((getElement(1) & 0x01) == 0x01) { txt.append(" to/from Accessory Mod (MX8)"); } else if ((getElement(1) & 0x02) == 0x02) { txt.append(" to/from Track Section (MX9)"); } else { txt.append(" unknown"); } } //int type<SUF> return txt.toString(); } private String decodeFunctionStates(int cData2, int cData3) { StringBuilder txt = new StringBuilder(); txt.append(((cData2 & 0x1) == 0x1) ? " F1: On " : " F1: Off "); txt.append(((cData2 & 0x2) == 0x2) ? " F2: On " : " F2: Off "); txt.append(((cData2 & 0x4) == 0x4) ? " F3: On " : " F3: Off "); txt.append(((cData2 & 0x8) == 0x8) ? " F4: On " : " F4: Off "); txt.append(((cData2 & 0x10) == 0x10) ? " F5: On " : " F5: Off "); txt.append(((cData2 & 0x20) == 0x20) ? " F6: On " : " F6: Off "); txt.append(((cData2 & 0x40) == 0x40) ? " F7: On " : " F7: Off "); txt.append(((cData2 & 0x80) == 0x80) ? " F8: On " : " F8: Off "); txt.append(((cData3 & 0x1) == 0x1) ? " F9: On " : " F9: Off "); txt.append(((cData3 & 0x2) == 0x2) ? " F10: On " : " F10: Off "); txt.append(((cData3 & 0x4) == 0x4) ? " F11: On " : " F11: Off "); txt.append(((cData3 & 0x8) == 0x8) ? " F12: On " : " F12: Off "); return txt.toString(); } public int getLocoAddress() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() == (4 + offset)) { return getLocoAddress(getElement(3 + offset), getElement(4 + offset)); } return -1; } public int getCvValue() { int offset = 0; if (getMessageType() == REPLY2) { offset++; } else if (getMessageType() == ACKREP1) { offset = +2; } if (getNumDataElements() >= (8 + offset)) { //Version 61.26 and later includes an extra error bit at the end of the packet return (getElement(7 + offset) & 0xff); } return -1; } int getLocoAddress(int hi, int lo) { hi = hi & 0x3F; if (hi == 0) { return lo; } else { hi = (((hi & 255) - 192) << 8); hi = hi + (lo & 255); return hi; } } String getErrorCode(int i) { switch (i) { case NO_ERROR: return "No Error"; case ERR_ADDRESS: return "Invalid Address"; case ERR_INDEX: return "Invalid Index"; case ERR_FORWARD: return "Could not be Forwarded"; case ERR_BUSY: return "CMD Busy"; case ERR_NO_MOT: return "Motorola Jump Off"; case ERR_NO_DCC: return "DCC Jump Off"; case ERR_CV_ADDRESS: return "Invalid CV"; case ERR_SECTION: return "Invalid Section"; case ERR_NO_MODUL: return "No Module Found"; case ERR_MESSAGE: return "Error in Message"; case ERR_SPEED: return "Invalid Speed"; default: return "Unknown Error"; } } final static int NO_ERROR = 0x00; final static int ERR_ADDRESS = 0x01; final static int ERR_INDEX = 0x02; final static int ERR_FORWARD = 0x03; final static int ERR_BUSY = 0x04; final static int ERR_NO_MOT = 0x05; final static int ERR_NO_DCC = 0x06; final static int ERR_CV_ADDRESS = 0x07; final static int ERR_SECTION = 0x08; final static int ERR_NO_MODUL = 0x09; final static int ERR_MESSAGE = 0x0a; final static int ERR_SPEED = 0x0b; final static int TRACKCTL = 0x02; final static int PROGCMD = 0x13; final static int LOCOCMD = 0x03; final static int ACCCMD = 0x07; static public Mx1Message getCmdStnDetails() { Mx1Message m = new Mx1Message(4); m.setElement(1, 0x10); m.setElement(2, 0x13); m.setElement(3, 0x00); return m; } /** * Set Track Power Off/Emergency Stop * * @return MrcMessage */ static public Mx1Message setPowerOff() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x01); return m; } static public Mx1Message setPowerOn() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x02); return m; } static public Mx1Message getTrackStatus() { Mx1Message m = new Mx1Message(4, Mx1Packetizer.BINARY); m.setElement(1, 0x10); // PC control short message m.setElement(2, TRACKCTL); m.setElement(3, 0x03); return m; } /** * Create a message to read or write a CV. * * @param locoAddress address of the loco * @param cv CV to read or write * @param value value to write to CV, if -1 CV is read * @param dcc true if decoder is DCC; false if decoder is Motorola * @return a message to read or write a CV */ // javadoc did indicate locoAddress could be blank to use programming track, but that's not possible with an int static public Mx1Message getDecProgCmd(int locoAddress, int cv, int value, boolean dcc) { Mx1Message m; if (value == -1) { m = new Mx1Message(7, Mx1Packetizer.BINARY); } else { m = new Mx1Message(8, Mx1Packetizer.BINARY); } m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, PROGCMD); int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, cv >> 8); m.setElement(6, cv & 0xff); if (value != -1) { m.setElement(7, value); } return m; } /** * Create a locomotive control message. * * @param locoAddress address of the loco * @param speed Speed Step in the actual Speed Step System * @param dcc true if decoder is DCC; false if decoder is Motorola * @param cData1 ??? * @param cData2 functions output 0-7 * @param cData3 functions output 9-12 * @return message controlling a locomotive */ static public Mx1Message getLocoControl(int locoAddress, int speed, boolean dcc, int cData1, int cData2, int cData3) { Mx1Message m = new Mx1Message(9, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, LOCOCMD); //High add 80 to indicate DCC int locoHi = locoAddress >> 8; if (dcc) { locoHi = locoHi + 128; } else { locoHi = locoHi + 64; } m.setElement(3, (locoHi)); m.setElement(4, (locoAddress & 0xff)); m.setElement(5, speed); m.setElement(6, cData1); m.setElement(7, cData2); m.setElement(8, cData3); return m; } static public Mx1Message getSwitchMsg(int accAddress, int setting, boolean dcc) { Mx1Message m = new Mx1Message(6, Mx1Packetizer.BINARY); m.setElement(0, 0x00); m.setElement(1, 0x10); // PC control short message m.setElement(2, ACCCMD); //High add 80 to indicate DCC int accHi = accAddress >> 8; if (dcc) { accHi = accHi + 128; } else { accHi = accHi + 64; } m.setElement(3, (accHi)); m.setElement(4, (accAddress & 0xff)); m.setElement(5, 0x00); if (setting == jmri.Turnout.THROWN) { m.setElement(5, 0x04); } return m; } // initialize logging private final static Logger log = LoggerFactory.getLogger(Mx1Message.class); }
173211_0
package nl.ordina.jtech.ws.jerseyjaxrs; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import javax.ws.rs.ServiceUnavailableException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * JAX-RS client die RESTful requests afvuurt op een server-side AsyncEntityResource. * Client is zelf synchroon, maar is vrij eenvoudig asynchroon te maken. */ public class AsyncEntityClient { private static final Logger LOG = LoggerFactory.getLogger(AsyncEntityClient.class); private final Client client; private final String entityServiceUrl; public AsyncEntityClient(final String url) { client = ClientBuilder.newClient(); entityServiceUrl = url; } public String getEntity(final int id) throws InterruptedException, ExecutionException, TimeoutException { LOG.debug("get entity {}", id); final WebTarget target = client.target(entityServiceUrl); // response code wrapper final Response response = target // .path(String.format("entity/%d", id)) // .request() // .accept("text/html") // // TODO bonus: add async variant using simply .async() // // ... but is that enough? .get(Response.class); return extractEntity(id, target, response); } private String extractEntity(final int id, final WebTarget target, final Response response) { switch (response.getStatus()) { case 200: return response.readEntity(String.class); case 404: LOG.info("Entity {} not found", id); return null; case 400: LOG.info("illegal Entity id {}", id); throw new IllegalArgumentException(Integer.toString(id)); case 503: LOG.info("Service not available - probably timeout"); throw new ServiceUnavailableException(response); default: LOG.info("unknown error requesting Entity id {}", id); throw new RuntimeException(String.format("unknown error requesting Entity id %s", id)); } } public String createEntity(final String entityName) { LOG.debug("create entity {}", entityName); final WebTarget target = client.target(entityServiceUrl); final Response response = target // .path(String.format("entity")) // .request(MediaType.APPLICATION_FORM_URLENCODED) // .post(Entity.form(new Form("name", entityName))); return extractEntity(-1, target, response); } public String getEntityList() { final WebTarget target = client.target(entityServiceUrl); final Response response = target // .path("entity") // .request() // // TODO bonus: add async variant using simply .async() // // ... but is that enough? .accept("text/html") // .get(Response.class); return extractEntity(-1, target, response); } }
petereijgermans11/websockets_http2
cursus-websockets-server-push-master/workspace/jersey-jaxrs-async/src/main/java/nl/ordina/jtech/ws/jerseyjaxrs/AsyncEntityClient.java
865
/** * JAX-RS client die RESTful requests afvuurt op een server-side AsyncEntityResource. * Client is zelf synchroon, maar is vrij eenvoudig asynchroon te maken. */
block_comment
nl
package nl.ordina.jtech.ws.jerseyjaxrs; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import javax.ws.rs.ServiceUnavailableException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * JAX-RS client die<SUF>*/ public class AsyncEntityClient { private static final Logger LOG = LoggerFactory.getLogger(AsyncEntityClient.class); private final Client client; private final String entityServiceUrl; public AsyncEntityClient(final String url) { client = ClientBuilder.newClient(); entityServiceUrl = url; } public String getEntity(final int id) throws InterruptedException, ExecutionException, TimeoutException { LOG.debug("get entity {}", id); final WebTarget target = client.target(entityServiceUrl); // response code wrapper final Response response = target // .path(String.format("entity/%d", id)) // .request() // .accept("text/html") // // TODO bonus: add async variant using simply .async() // // ... but is that enough? .get(Response.class); return extractEntity(id, target, response); } private String extractEntity(final int id, final WebTarget target, final Response response) { switch (response.getStatus()) { case 200: return response.readEntity(String.class); case 404: LOG.info("Entity {} not found", id); return null; case 400: LOG.info("illegal Entity id {}", id); throw new IllegalArgumentException(Integer.toString(id)); case 503: LOG.info("Service not available - probably timeout"); throw new ServiceUnavailableException(response); default: LOG.info("unknown error requesting Entity id {}", id); throw new RuntimeException(String.format("unknown error requesting Entity id %s", id)); } } public String createEntity(final String entityName) { LOG.debug("create entity {}", entityName); final WebTarget target = client.target(entityServiceUrl); final Response response = target // .path(String.format("entity")) // .request(MediaType.APPLICATION_FORM_URLENCODED) // .post(Entity.form(new Form("name", entityName))); return extractEntity(-1, target, response); } public String getEntityList() { final WebTarget target = client.target(entityServiceUrl); final Response response = target // .path("entity") // .request() // // TODO bonus: add async variant using simply .async() // // ... but is that enough? .accept("text/html") // .get(Response.class); return extractEntity(-1, target, response); } }
174041_2
/** * */ package schere_stein_papier; /** * Klasse zum Regeln des Spielverlaufs * * @author Daniel May * @version 1.0 * */ public class MyModel { private Wahl pczug; private Wahl menschzug; private int pccounter; private int menschcounter; private int[] stat;// Siege, Unentschieden, Niederlagen private String aktuellerText; private int aktuellesSpiel; // 0 unentschieden <0 verloren >0 gewonnen /** * Standard konstruktor */ public MyModel() { this.stat = new int[3]; reset(); } /** * @return the aktuellesSpiel */ public int getAktuellesSpiel() { return aktuellesSpiel; } /** * @return the pczug */ public Wahl getPczug() { return pczug; } /** * @return the pccounter */ public int getPccounter() { return pccounter; } /** * @param pccounter * the pccounter to set */ public void setPccounter(int pccounter) { this.pccounter = pccounter; } /** * @return the menschcounter */ public int getMenschcounter() { return menschcounter; } /** * @param menschcounter * the menschcounter to set */ public void setMenschcounter(int menschcounter) { this.menschcounter = menschcounter; } /** * @return the stat */ public int[] getStat() { return stat; } /** * @param stat * the stat to set */ public void setStat(int[] stat) { this.stat = stat; } /** * @return the aktuellerText */ public String getAktuellerText() { return aktuellerText; } /** * @param aktuellerText * the aktuellerText to set */ public void setAktuellerText(String aktuellerText) { this.aktuellerText = aktuellerText; } /** * Methode zum ueberpruefen des gewinners * * @param menschzug * Zug des Spielers * @return Auswertung des Zuges 0=unentscheiden, <0 verloren, >0 gewonnen */ public int check() { if (menschzug == pczug) { aktuellesSpiel = 0; aktuellerText = "Unentschieden!"; menschcounter++; pccounter++; stat[1]++; } else if ((menschzug == Wahl.SCHERE && pczug == Wahl.STEIN) || (menschzug == Wahl.PAPIER && pczug == Wahl.SCHERE) || (menschzug == Wahl.STEIN && pczug == Wahl.PAPIER)) { aktuellesSpiel = -1; aktuellerText = "Niederlage!"; pccounter += 2; stat[2]++; } else // if ((menschzug==Wahl.STEIN && pczug==Wahl.SCHERE) || // (menschzug==Wahl.SCHERE && pczug == Wahl.PAPIER) || // (menschzug==Wahl.PAPIER && pczug == Wahl.STEIN)) { aktuellesSpiel = 1; aktuellerText = "Sieg!"; menschcounter += 2; stat[0]++; } return aktuellesSpiel; } /** * @return the menschzug */ public Wahl getMenschzug() { if (menschzug != null) return menschzug; else return null; } /** * @param menschzug * the menschzug to set */ public void setMenschzug(Wahl menschzug) { this.menschzug = menschzug; } /** * Laesst den PC zufaellig Schere, Stein oder Papier waehlen */ public Wahl pczug() { int value = (int) (Math.random() * 3); switch (value) { case 1: pczug = Wahl.STEIN; break; case 2: pczug = Wahl.PAPIER; break; default: pczug = Wahl.SCHERE; } return pczug; } /** * ruecksetzen der statistik */ public void reset() { this.aktuellesSpiel = 0; this.pczug = Wahl.SCHERE; this.pccounter = 0; this.menschcounter = 0; for (int i = 0; i < stat.length; i++) { stat[i] = 0; } } }
peterfuchs1/2JG
2JG/src/schere_stein_papier/MyModel.java
1,375
// 0 unentschieden <0 verloren >0 gewonnen
line_comment
nl
/** * */ package schere_stein_papier; /** * Klasse zum Regeln des Spielverlaufs * * @author Daniel May * @version 1.0 * */ public class MyModel { private Wahl pczug; private Wahl menschzug; private int pccounter; private int menschcounter; private int[] stat;// Siege, Unentschieden, Niederlagen private String aktuellerText; private int aktuellesSpiel; // 0 unentschieden<SUF> /** * Standard konstruktor */ public MyModel() { this.stat = new int[3]; reset(); } /** * @return the aktuellesSpiel */ public int getAktuellesSpiel() { return aktuellesSpiel; } /** * @return the pczug */ public Wahl getPczug() { return pczug; } /** * @return the pccounter */ public int getPccounter() { return pccounter; } /** * @param pccounter * the pccounter to set */ public void setPccounter(int pccounter) { this.pccounter = pccounter; } /** * @return the menschcounter */ public int getMenschcounter() { return menschcounter; } /** * @param menschcounter * the menschcounter to set */ public void setMenschcounter(int menschcounter) { this.menschcounter = menschcounter; } /** * @return the stat */ public int[] getStat() { return stat; } /** * @param stat * the stat to set */ public void setStat(int[] stat) { this.stat = stat; } /** * @return the aktuellerText */ public String getAktuellerText() { return aktuellerText; } /** * @param aktuellerText * the aktuellerText to set */ public void setAktuellerText(String aktuellerText) { this.aktuellerText = aktuellerText; } /** * Methode zum ueberpruefen des gewinners * * @param menschzug * Zug des Spielers * @return Auswertung des Zuges 0=unentscheiden, <0 verloren, >0 gewonnen */ public int check() { if (menschzug == pczug) { aktuellesSpiel = 0; aktuellerText = "Unentschieden!"; menschcounter++; pccounter++; stat[1]++; } else if ((menschzug == Wahl.SCHERE && pczug == Wahl.STEIN) || (menschzug == Wahl.PAPIER && pczug == Wahl.SCHERE) || (menschzug == Wahl.STEIN && pczug == Wahl.PAPIER)) { aktuellesSpiel = -1; aktuellerText = "Niederlage!"; pccounter += 2; stat[2]++; } else // if ((menschzug==Wahl.STEIN && pczug==Wahl.SCHERE) || // (menschzug==Wahl.SCHERE && pczug == Wahl.PAPIER) || // (menschzug==Wahl.PAPIER && pczug == Wahl.STEIN)) { aktuellesSpiel = 1; aktuellerText = "Sieg!"; menschcounter += 2; stat[0]++; } return aktuellesSpiel; } /** * @return the menschzug */ public Wahl getMenschzug() { if (menschzug != null) return menschzug; else return null; } /** * @param menschzug * the menschzug to set */ public void setMenschzug(Wahl menschzug) { this.menschzug = menschzug; } /** * Laesst den PC zufaellig Schere, Stein oder Papier waehlen */ public Wahl pczug() { int value = (int) (Math.random() * 3); switch (value) { case 1: pczug = Wahl.STEIN; break; case 2: pczug = Wahl.PAPIER; break; default: pczug = Wahl.SCHERE; } return pczug; } /** * ruecksetzen der statistik */ public void reset() { this.aktuellesSpiel = 0; this.pczug = Wahl.SCHERE; this.pccounter = 0; this.menschcounter = 0; for (int i = 0; i < stat.length; i++) { stat[i] = 0; } } }
83997_1
package screens; import components.Game; import components.Screen; import helper.Helper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class RankingScreen extends Screen { public RankingScreen() {} public RankingScreen(String notification) { super(notification); } @Override public void showScreen() { System.out.println("[Rangschikking]"); List<String> categories = new ArrayList<>(); for (Game game : Game.getAllGames()) categories.add(game.getCategory()); categories = categories.stream().distinct().collect(Collectors.toList()); // haal dubbelen weg Scanner scanner = new Scanner(System.in); System.out.println("1. Normaal"); // laat gebruiker keuze maken int counter = 2; for (String category : categories) { System.out.println(STR."\{counter}. \{category}"); counter++; } System.out.print("Maak uw keuze: "); int choice = scanner.nextInt(); String category = choice == 1 ? null : categories.get(choice - 2); Helper.clearScreen(); // sorteer games op cijfer ArrayList<Game> games = Game.getAllGames(); games.sort((game1, game2) -> Integer.compare(game2.getGrade(), game1.getGrade())); // print alle games counter = 1; for (Game game : games) { if (category != null && !category.equals(game.getCategory())) continue; double price = game.inSale() ? game.getPrice() / 100 * 80 : game.getPrice(); System.out.print(STR."\{counter}. \{game.getName()}, prijs: €\{Helper.formatToEuro(price)}, rating: \{game.getGrade()}"); if (game.inSale()) System.out.print(" (20% KORTING)"); System.out.println(); counter++; } new StartScreen("\nBoven u staan de resultaten").showScreen(); } }
peterjarian/good-ol-reviews
src/screens/RankingScreen.java
609
// laat gebruiker keuze maken
line_comment
nl
package screens; import components.Game; import components.Screen; import helper.Helper; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class RankingScreen extends Screen { public RankingScreen() {} public RankingScreen(String notification) { super(notification); } @Override public void showScreen() { System.out.println("[Rangschikking]"); List<String> categories = new ArrayList<>(); for (Game game : Game.getAllGames()) categories.add(game.getCategory()); categories = categories.stream().distinct().collect(Collectors.toList()); // haal dubbelen weg Scanner scanner = new Scanner(System.in); System.out.println("1. Normaal"); // laat gebruiker<SUF> int counter = 2; for (String category : categories) { System.out.println(STR."\{counter}. \{category}"); counter++; } System.out.print("Maak uw keuze: "); int choice = scanner.nextInt(); String category = choice == 1 ? null : categories.get(choice - 2); Helper.clearScreen(); // sorteer games op cijfer ArrayList<Game> games = Game.getAllGames(); games.sort((game1, game2) -> Integer.compare(game2.getGrade(), game1.getGrade())); // print alle games counter = 1; for (Game game : games) { if (category != null && !category.equals(game.getCategory())) continue; double price = game.inSale() ? game.getPrice() / 100 * 80 : game.getPrice(); System.out.print(STR."\{counter}. \{game.getName()}, prijs: €\{Helper.formatToEuro(price)}, rating: \{game.getGrade()}"); if (game.inSale()) System.out.print(" (20% KORTING)"); System.out.println(); counter++; } new StartScreen("\nBoven u staan de resultaten").showScreen(); } }
122449_48
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.net.IDN; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import junit.framework.TestCase; /** * Tests for the DomainValidator. * * @version $Revision$ */ public class DomainValidatorTest extends TestCase { private DomainValidator validator; public void setUp() { validator = DomainValidator.getInstance(); } public void testValidDomains() { assertTrue("apache.org should validate", validator.isValid("apache.org")); assertTrue("www.google.com should validate", validator.isValid("www.google.com")); assertTrue("test-domain.com should validate", validator.isValid("test-domain.com")); assertTrue("test---domain.com should validate", validator.isValid("test---domain.com")); assertTrue("test-d-o-m-ain.com should validate", validator.isValid("test-d-o-m-ain.com")); assertTrue("two-letter domain label should validate", validator.isValid("as.uk")); assertTrue("case-insensitive ApAchE.Org should validate", validator.isValid("ApAchE.Org")); assertTrue("single-character domain label should validate", validator.isValid("z.com")); assertTrue("i.have.an-example.domain.name should validate", validator.isValid("i.have.an-example.domain.name")); } public void testInvalidDomains() { assertFalse("bare TLD .org shouldn't validate", validator.isValid(".org")); assertFalse("domain name with spaces shouldn't validate", validator.isValid(" apache.org ")); assertFalse("domain name containing spaces shouldn't validate", validator.isValid("apa che.org")); assertFalse("domain name starting with dash shouldn't validate", validator.isValid("-testdomain.name")); assertFalse("domain name ending with dash shouldn't validate", validator.isValid("testdomain-.name")); assertFalse("domain name starting with multiple dashes shouldn't validate", validator.isValid("---c.com")); assertFalse("domain name ending with multiple dashes shouldn't validate", validator.isValid("c--.com")); assertFalse("domain name with invalid TLD shouldn't validate", validator.isValid("apache.rog")); assertFalse("URL shouldn't validate", validator.isValid("http://www.apache.org")); assertFalse("Empty string shouldn't validate as domain name", validator.isValid(" ")); assertFalse("Null shouldn't validate as domain name", validator.isValid(null)); } public void testTopLevelDomains() { // infrastructure TLDs assertTrue(".arpa should validate as iTLD", validator.isValidInfrastructureTld(".arpa")); assertFalse(".com shouldn't validate as iTLD", validator.isValidInfrastructureTld(".com")); // generic TLDs assertTrue(".name should validate as gTLD", validator.isValidGenericTld(".name")); assertFalse(".us shouldn't validate as gTLD", validator.isValidGenericTld(".us")); // country code TLDs assertTrue(".uk should validate as ccTLD", validator.isValidCountryCodeTld(".uk")); assertFalse(".org shouldn't validate as ccTLD", validator.isValidCountryCodeTld(".org")); // case-insensitive assertTrue(".COM should validate as TLD", validator.isValidTld(".COM")); assertTrue(".BiZ should validate as TLD", validator.isValidTld(".BiZ")); // corner cases assertFalse("invalid TLD shouldn't validate", validator.isValid(".nope")); // TODO this is not guaranteed invalid forever assertFalse("empty string shouldn't validate as TLD", validator.isValid("")); assertFalse("null shouldn't validate as TLD", validator.isValid(null)); } public void testAllowLocal() { DomainValidator noLocal = DomainValidator.getInstance(false); DomainValidator allowLocal = DomainValidator.getInstance(true); // Default is false, and should use singletons assertEquals(noLocal, validator); // Default won't allow local assertFalse("localhost.localdomain should validate", noLocal.isValid("localhost.localdomain")); assertFalse("localhost should validate", noLocal.isValid("localhost")); // But it may be requested assertTrue("localhost.localdomain should validate", allowLocal.isValid("localhost.localdomain")); assertTrue("localhost should validate", allowLocal.isValid("localhost")); assertTrue("hostname should validate", allowLocal.isValid("hostname")); assertTrue("machinename should validate", allowLocal.isValid("machinename")); // Check the localhost one with a few others assertTrue("apache.org should validate", allowLocal.isValid("apache.org")); assertFalse("domain name with spaces shouldn't validate", allowLocal.isValid(" apache.org ")); } public void testIDN() { assertTrue("b\u00fccher.ch in IDN should validate", validator.isValid("www.xn--bcher-kva.ch")); } public void testIDNJava6OrLater() { String version = System.getProperty("java.version"); if (version.compareTo("1.6") < 0) { System.out.println("Cannot run Unicode IDN tests"); return; // Cannot run the test } // xn--d1abbgf6aiiy.xn--p1ai http://президент.рф assertTrue("b\u00fccher.ch should validate", validator.isValid("www.b\u00fccher.ch")); assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("xn--d1abbgf6aiiy.xn--p1ai")); assertTrue("президент.рф should validate", validator.isValid("президент.рф")); assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("www.\uFFFD.ch")); } // RFC2396: domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum public void testRFC2396domainlabel() { // use fixed valid TLD assertTrue("a.ch should validate", validator.isValid("a.ch")); assertTrue("9.ch should validate", validator.isValid("9.ch")); assertTrue("az.ch should validate", validator.isValid("az.ch")); assertTrue("09.ch should validate", validator.isValid("09.ch")); assertTrue("9-1.ch should validate", validator.isValid("9-1.ch")); assertFalse("91-.ch should not validate", validator.isValid("91-.ch")); assertFalse("-.ch should not validate", validator.isValid("-.ch")); } // RFC2396 toplabel = alpha | alpha *( alphanum | "-" ) alphanum public void testRFC2396toplabel() { // These tests use non-existent TLDs so currently need to use a package protected method assertTrue("a.c (alpha) should validate", validator.isValidDomainSyntax("a.c")); assertTrue("a.cc (alpha alpha) should validate", validator.isValidDomainSyntax("a.cc")); assertTrue("a.c9 (alpha alphanum) should validate", validator.isValidDomainSyntax("a.c9")); assertTrue("a.c-9 (alpha - alphanum) should validate", validator.isValidDomainSyntax("a.c-9")); assertTrue("a.c-z (alpha - alpha) should validate", validator.isValidDomainSyntax("a.c-z")); assertFalse("a.9c (alphanum alpha) should fail", validator.isValidDomainSyntax("a.9c")); assertFalse("a.c- (alpha -) should fail", validator.isValidDomainSyntax("a.c-")); assertFalse("a.- (-) should fail", validator.isValidDomainSyntax("a.-")); assertFalse("a.-9 (- alphanum) should fail", validator.isValidDomainSyntax("a.-9")); } public void testDomainNoDots() {// rfc1123 assertTrue("a (alpha) should validate", validator.isValidDomainSyntax("a")); assertTrue("9 (alphanum) should validate", validator.isValidDomainSyntax("9")); assertTrue("c-z (alpha - alpha) should validate", validator.isValidDomainSyntax("c-z")); assertFalse("c- (alpha -) should fail", validator.isValidDomainSyntax("c-")); assertFalse("-c (- alpha) should fail", validator.isValidDomainSyntax("-c")); assertFalse("- (-) should fail", validator.isValidDomainSyntax("-")); } public void testValidator297() { assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("xn--d1abbgf6aiiy.xn--p1ai")); // This uses a valid TLD } // labels are a max of 63 chars and domains 253 public void testValidator306() { final String longString = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789A"; assertEquals(63, longString.length()); // 26 * 2 + 11 assertTrue("63 chars label should validate", validator.isValidDomainSyntax(longString+".com")); assertFalse("64 chars label should fail", validator.isValidDomainSyntax(longString+"x.com")); assertTrue("63 chars TLD should validate", validator.isValidDomainSyntax("test."+longString)); assertFalse("64 chars TLD should fail", validator.isValidDomainSyntax("test.x"+longString)); final String longDomain = longString + "." + longString + "." + longString + "." + longString.substring(0,61) ; assertEquals(253, longDomain.length()); assertTrue("253 chars domain should validate", validator.isValidDomainSyntax(longDomain)); assertFalse("254 chars domain should fail", validator.isValidDomainSyntax(longDomain+"x")); } // Check that IDN.toASCII behaves as it should (when wrapped by DomainValidator.unicodeToASCII) // Tests show that method incorrectly trims a trailing "." character public void testUnicodeToASCII() { String[] asciidots = { "", ",", ".", // fails IDN.toASCII, but should pass wrapped version "a.", // ditto "a.b", "a..b", "a...b", ".a", "..a", }; for(String s : asciidots) { assertEquals(s,DomainValidator.unicodeToASCII(s)); } // RFC3490 3.1. 1) // Whenever dots are used as label separators, the following // characters MUST be recognized as dots: U+002E (full stop), U+3002 // (ideographic full stop), U+FF0E (fullwidth full stop), U+FF61 // (halfwidth ideographic full stop). final String otherDots[][] = { {"b\u3002", "b.",}, {"b\uFF0E", "b.",}, {"b\uFF61", "b.",}, {"\u3002", ".",}, {"\uFF0E", ".",}, {"\uFF61", ".",}, }; for(String s[] : otherDots) { assertEquals(s[1],DomainValidator.unicodeToASCII(s[0])); } } // Check if IDN.toASCII is broken or not public void testIsIDNtoASCIIBroken() { System.out.println(">>DomainValidatorTest.testIsIDNtoASCIIBroken()"); final String input = "."; final boolean ok = input.equals(IDN.toASCII(input)); System.out.println("IDN.toASCII is " + (ok? "OK" : "BROKEN")); String props[] = { "java.version", // Java Runtime Environment version "java.vendor", // Java Runtime Environment vendor "java.vm.specification.version", // Java Virtual Machine specification version "java.vm.specification.vendor", // Java Virtual Machine specification vendor "java.vm.specification.name", // Java Virtual Machine specification name "java.vm.version", // Java Virtual Machine implementation version "java.vm.vendor", // Java Virtual Machine implementation vendor "java.vm.name", // Java Virtual Machine implementation name "java.specification.version", // Java Runtime Environment specification version "java.specification.vendor", // Java Runtime Environment specification vendor "java.specification.name", // Java Runtime Environment specification name "java.class.version", // Java class format version number }; for(String t : props) { System.out.println(t + "=" + System.getProperty(t)); } System.out.println("<<DomainValidatorTest.testIsIDNtoASCIIBroken()"); } // Check array is sorted and is lower-case public void test_INFRASTRUCTURE_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("INFRASTRUCTURE_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case public void test_COUNTRY_CODE_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("COUNTRY_CODE_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case public void test_GENERIC_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("GENERIC_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case public void test_LOCAL_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("LOCAL_TLDS"); assertTrue(sorted); } // Download and process local copy of http://data.iana.org/TLD/tlds-alpha-by-domain.txt // Check if the internal TLD table is up to date // Check if the internal TLD tables have any spurious entries public static void main(String a[]) throws Exception { Set<String> ianaTlds = new HashSet<String>(); // keep for comparison with array contents DomainValidator dv = DomainValidator.getInstance();; File txtFile = new File("target/tlds-alpha-by-domain.txt"); long timestamp = download(txtFile, "http://data.iana.org/TLD/tlds-alpha-by-domain.txt", 0L); final File htmlFile = new File("target/tlds-alpha-by-domain.html"); // N.B. sometimes the html file may be updated a day or so after the txt file // if the txt file contains entries not found in the html file, try again in a day or two download(htmlFile,"http://www.iana.org/domains/root/db", timestamp); BufferedReader br = new BufferedReader(new FileReader(txtFile)); String line; final String header; line = br.readLine(); // header if (line.startsWith("# Version ")) { header = line.substring(2); } else { br.close(); throw new IOException("File does not have expected Version header"); } final boolean generateUnicodeTlds = false; // Change this to generate Unicode TLDs as well // Parse html page to get entries Map<String, String[]> htmlInfo = getHtmlInfo(htmlFile); Map<String, String> missingTLD = new TreeMap<String, String>(); // stores entry and comments as String[] Map<String, String> missingCC = new TreeMap<String, String>(); while((line = br.readLine()) != null) { if (!line.startsWith("#")) { final String unicodeTld; // only different from asciiTld if that was punycode final String asciiTld = line.toLowerCase(Locale.ENGLISH); if (line.startsWith("XN--")) { unicodeTld = IDN.toUnicode(line); } else { unicodeTld = asciiTld; } if (!dv.isValidTld(asciiTld)) { String [] info = (String[]) htmlInfo.get(asciiTld); if (info != null) { String type = info[0]; String comment = info[1]; if ("country-code".equals(type)) { // Which list to use? missingCC.put(asciiTld, unicodeTld + " " + comment); if (generateUnicodeTlds) { missingCC.put(unicodeTld, asciiTld + " " + comment); } } else { missingTLD.put(asciiTld, unicodeTld + " " + comment); if (generateUnicodeTlds) { missingTLD.put(unicodeTld, asciiTld + " " + comment); } } } else { System.err.println("Expected to find info for "+ asciiTld); } } ianaTlds.add(asciiTld); // Don't merge these conditions; generateUnicodeTlds is final so needs to be separate to avoid a warning if (generateUnicodeTlds) { if (!unicodeTld.equals(asciiTld)) { ianaTlds.add(unicodeTld); } } } } br.close(); // List html entries not in TLD text list for(String key : (new TreeMap<String, String[]>(htmlInfo)).keySet()) { if (!ianaTlds.contains(key)) { System.err.println("Expected to find text entry for html: "+key); } } if (!missingTLD.isEmpty()) { printMap(header, missingTLD, "TLD"); } if (!missingCC.isEmpty()) { printMap(header, missingCC, "CC"); } // Check if internal tables contain any additional entries isInIanaList("INFRASTRUCTURE_TLDS", ianaTlds); isInIanaList("COUNTRY_CODE_TLDS", ianaTlds); isInIanaList("GENERIC_TLDS", ianaTlds); // Don't check local TLDS isInIanaList("LOCAL_TLDS", ianaTlds); System.out.println("Finished checks"); } private static void printMap(final String header, Map<String, String> map, String string) { System.out.println("Entries missing from "+ string +" List\n"); if (header != null) { System.out.println(" // Taken from " + header); } Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while(it.hasNext()){ Map.Entry<String, String> me = it.next(); System.out.println(" \"" + me.getKey() + "\", // " + me.getValue()); } System.out.println("\nDone"); } private static Map<String, String[]> getHtmlInfo(final File f) throws IOException { final Map<String, String[]> info = new HashMap<String, String[]>(); // <td><span class="domain tld"><a href="/domains/root/db/ax.html">.ax</a></span></td> final Pattern domain = Pattern.compile(".*<a href=\"/domains/root/db/([^.]+)\\.html"); // <td>country-code</td> final Pattern type = Pattern.compile("\\s+<td>([^<]+)</td>"); // <!-- <td>Åland Islands<br/><span class="tld-table-so">Ålands landskapsregering</span></td> </td> --> // <td>Ålands landskapsregering</td> final Pattern comment = Pattern.compile("\\s+<td>([^<]+)</td>"); final BufferedReader br = new BufferedReader(new FileReader(f)); String line; while((line=br.readLine())!=null){ Matcher m = domain.matcher(line); if (m.lookingAt()) { String dom = m.group(1); String typ = "??"; String com = "??"; line = br.readLine(); Matcher t = type.matcher(line); if (t.lookingAt()) { typ = t.group(1); line = br.readLine(); if (line.matches("\\s+<!--.*")) { while(!line.matches(".*-->.*")){ line = br.readLine(); } line = br.readLine(); } // Should have comment; is it wrapped? while(!line.matches(".*</td>.*")){ line += " " +br.readLine(); } Matcher n = comment.matcher(line); if (n.lookingAt()) { com = n.group(1); } // Don't save unused entries if (com.contains("Not assigned") || com.contains("Retired") || typ.equals("test")) { // System.out.println(dom + " " + typ + " " +com); } else { info.put(dom.toLowerCase(Locale.ENGLISH), new String[]{typ, com}); // System.out.println(dom + " " + typ + " " +com); } } } } br.close(); return info; } /* * Download a file if it is more recent than our cached copy. * Unfortunately the server does not seem to honour If-Modified-Since for the * Html page, so we check if it is newer than the txt file and skip download if so */ private static long download(File f, String tldurl, long timestamp) throws IOException { if (timestamp > 0 && f.canRead()) { long modTime = f.lastModified(); if (modTime > timestamp) { System.out.println("Skipping download - found recent " + f); return modTime; } } HttpURLConnection hc = (HttpURLConnection) new URL(tldurl).openConnection(); if (f.canRead()) { long modTime = f.lastModified(); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");//Sun, 06 Nov 1994 08:49:37 GMT String since = sdf.format(new Date(modTime)); hc.addRequestProperty("If-Modified-Since", since); System.out.println("Found " + f + " with date " + since); } if (hc.getResponseCode() == 304) { System.out.println("Already have most recent " + tldurl); } else { System.out.println("Downloading " + tldurl); byte buff[] = new byte[1024]; InputStream is = hc.getInputStream(); FileOutputStream fos = new FileOutputStream(f); int len; while((len=is.read(buff)) != -1) { fos.write(buff, 0, len); } fos.close(); is.close(); System.out.println("Done"); } return f.lastModified(); } // isInIanaList and isSorted are split into two methods. // If/when access to the arrays is possible without reflection, the intermediate // methods can be dropped private static boolean isInIanaList(String arrayName, Set<String> ianaTlds) throws Exception { Field f = DomainValidator.class.getDeclaredField(arrayName); final boolean isPrivate = Modifier.isPrivate(f.getModifiers()); if (isPrivate) { f.setAccessible(true); } String[] array = (String[]) f.get(null); try { return isInIanaList(arrayName, array, ianaTlds); } finally { if (isPrivate) { f.setAccessible(false); } } } private static boolean isInIanaList(String name, String [] array, Set<String> ianaTlds) { for(int i = 0; i < array.length; i++) { if (!ianaTlds.contains(array[i])) { System.out.println(name + " contains unexpected value: " + array[i]); } } return true; } private boolean isSortedLowerCase(String arrayName) throws Exception { Field f = DomainValidator.class.getDeclaredField(arrayName); final boolean isPrivate = Modifier.isPrivate(f.getModifiers()); if (isPrivate) { f.setAccessible(true); } String[] array = (String[]) f.get(null); try { return isSortedLowerCase(arrayName, array); } finally { if (isPrivate) { f.setAccessible(false); } } } private static boolean isLowerCase(String string) { return string.equals(string.toLowerCase(Locale.ENGLISH)); } // Check if an array is strictly sorted - and lowerCase private static boolean isSortedLowerCase(String name, String [] array) { boolean sorted = true; boolean strictlySorted = true; final int length = array.length; boolean lowerCase = isLowerCase(array[length-1]); // Check the last entry for(int i = 0; i < length-1; i++) { // compare all but last entry with next final String entry = array[i]; final String nextEntry = array[i+1]; final int cmp = entry.compareTo(nextEntry); if (cmp > 0) { // out of order System.out.println("Out of order entry: " + entry + " < " + nextEntry + " in " + name); sorted = false; } else if (cmp == 0) { strictlySorted = false; System.out.println("Duplicated entry: " + entry + " in " + name); } if (!isLowerCase(entry)) { System.out.println("Non lowerCase entry: " + entry + " in " + name); lowerCase = false; } } return sorted && strictlySorted && lowerCase; } }
peterjurkovic/commons-validator
src/test/java/org/apache/commons/validator/routines/DomainValidatorTest.java
7,470
// Parse html page to get entries
line_comment
nl
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.HttpURLConnection; import java.net.IDN; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import junit.framework.TestCase; /** * Tests for the DomainValidator. * * @version $Revision$ */ public class DomainValidatorTest extends TestCase { private DomainValidator validator; public void setUp() { validator = DomainValidator.getInstance(); } public void testValidDomains() { assertTrue("apache.org should validate", validator.isValid("apache.org")); assertTrue("www.google.com should validate", validator.isValid("www.google.com")); assertTrue("test-domain.com should validate", validator.isValid("test-domain.com")); assertTrue("test---domain.com should validate", validator.isValid("test---domain.com")); assertTrue("test-d-o-m-ain.com should validate", validator.isValid("test-d-o-m-ain.com")); assertTrue("two-letter domain label should validate", validator.isValid("as.uk")); assertTrue("case-insensitive ApAchE.Org should validate", validator.isValid("ApAchE.Org")); assertTrue("single-character domain label should validate", validator.isValid("z.com")); assertTrue("i.have.an-example.domain.name should validate", validator.isValid("i.have.an-example.domain.name")); } public void testInvalidDomains() { assertFalse("bare TLD .org shouldn't validate", validator.isValid(".org")); assertFalse("domain name with spaces shouldn't validate", validator.isValid(" apache.org ")); assertFalse("domain name containing spaces shouldn't validate", validator.isValid("apa che.org")); assertFalse("domain name starting with dash shouldn't validate", validator.isValid("-testdomain.name")); assertFalse("domain name ending with dash shouldn't validate", validator.isValid("testdomain-.name")); assertFalse("domain name starting with multiple dashes shouldn't validate", validator.isValid("---c.com")); assertFalse("domain name ending with multiple dashes shouldn't validate", validator.isValid("c--.com")); assertFalse("domain name with invalid TLD shouldn't validate", validator.isValid("apache.rog")); assertFalse("URL shouldn't validate", validator.isValid("http://www.apache.org")); assertFalse("Empty string shouldn't validate as domain name", validator.isValid(" ")); assertFalse("Null shouldn't validate as domain name", validator.isValid(null)); } public void testTopLevelDomains() { // infrastructure TLDs assertTrue(".arpa should validate as iTLD", validator.isValidInfrastructureTld(".arpa")); assertFalse(".com shouldn't validate as iTLD", validator.isValidInfrastructureTld(".com")); // generic TLDs assertTrue(".name should validate as gTLD", validator.isValidGenericTld(".name")); assertFalse(".us shouldn't validate as gTLD", validator.isValidGenericTld(".us")); // country code TLDs assertTrue(".uk should validate as ccTLD", validator.isValidCountryCodeTld(".uk")); assertFalse(".org shouldn't validate as ccTLD", validator.isValidCountryCodeTld(".org")); // case-insensitive assertTrue(".COM should validate as TLD", validator.isValidTld(".COM")); assertTrue(".BiZ should validate as TLD", validator.isValidTld(".BiZ")); // corner cases assertFalse("invalid TLD shouldn't validate", validator.isValid(".nope")); // TODO this is not guaranteed invalid forever assertFalse("empty string shouldn't validate as TLD", validator.isValid("")); assertFalse("null shouldn't validate as TLD", validator.isValid(null)); } public void testAllowLocal() { DomainValidator noLocal = DomainValidator.getInstance(false); DomainValidator allowLocal = DomainValidator.getInstance(true); // Default is false, and should use singletons assertEquals(noLocal, validator); // Default won't allow local assertFalse("localhost.localdomain should validate", noLocal.isValid("localhost.localdomain")); assertFalse("localhost should validate", noLocal.isValid("localhost")); // But it may be requested assertTrue("localhost.localdomain should validate", allowLocal.isValid("localhost.localdomain")); assertTrue("localhost should validate", allowLocal.isValid("localhost")); assertTrue("hostname should validate", allowLocal.isValid("hostname")); assertTrue("machinename should validate", allowLocal.isValid("machinename")); // Check the localhost one with a few others assertTrue("apache.org should validate", allowLocal.isValid("apache.org")); assertFalse("domain name with spaces shouldn't validate", allowLocal.isValid(" apache.org ")); } public void testIDN() { assertTrue("b\u00fccher.ch in IDN should validate", validator.isValid("www.xn--bcher-kva.ch")); } public void testIDNJava6OrLater() { String version = System.getProperty("java.version"); if (version.compareTo("1.6") < 0) { System.out.println("Cannot run Unicode IDN tests"); return; // Cannot run the test } // xn--d1abbgf6aiiy.xn--p1ai http://президент.рф assertTrue("b\u00fccher.ch should validate", validator.isValid("www.b\u00fccher.ch")); assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("xn--d1abbgf6aiiy.xn--p1ai")); assertTrue("президент.рф should validate", validator.isValid("президент.рф")); assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("www.\uFFFD.ch")); } // RFC2396: domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum public void testRFC2396domainlabel() { // use fixed valid TLD assertTrue("a.ch should validate", validator.isValid("a.ch")); assertTrue("9.ch should validate", validator.isValid("9.ch")); assertTrue("az.ch should validate", validator.isValid("az.ch")); assertTrue("09.ch should validate", validator.isValid("09.ch")); assertTrue("9-1.ch should validate", validator.isValid("9-1.ch")); assertFalse("91-.ch should not validate", validator.isValid("91-.ch")); assertFalse("-.ch should not validate", validator.isValid("-.ch")); } // RFC2396 toplabel = alpha | alpha *( alphanum | "-" ) alphanum public void testRFC2396toplabel() { // These tests use non-existent TLDs so currently need to use a package protected method assertTrue("a.c (alpha) should validate", validator.isValidDomainSyntax("a.c")); assertTrue("a.cc (alpha alpha) should validate", validator.isValidDomainSyntax("a.cc")); assertTrue("a.c9 (alpha alphanum) should validate", validator.isValidDomainSyntax("a.c9")); assertTrue("a.c-9 (alpha - alphanum) should validate", validator.isValidDomainSyntax("a.c-9")); assertTrue("a.c-z (alpha - alpha) should validate", validator.isValidDomainSyntax("a.c-z")); assertFalse("a.9c (alphanum alpha) should fail", validator.isValidDomainSyntax("a.9c")); assertFalse("a.c- (alpha -) should fail", validator.isValidDomainSyntax("a.c-")); assertFalse("a.- (-) should fail", validator.isValidDomainSyntax("a.-")); assertFalse("a.-9 (- alphanum) should fail", validator.isValidDomainSyntax("a.-9")); } public void testDomainNoDots() {// rfc1123 assertTrue("a (alpha) should validate", validator.isValidDomainSyntax("a")); assertTrue("9 (alphanum) should validate", validator.isValidDomainSyntax("9")); assertTrue("c-z (alpha - alpha) should validate", validator.isValidDomainSyntax("c-z")); assertFalse("c- (alpha -) should fail", validator.isValidDomainSyntax("c-")); assertFalse("-c (- alpha) should fail", validator.isValidDomainSyntax("-c")); assertFalse("- (-) should fail", validator.isValidDomainSyntax("-")); } public void testValidator297() { assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("xn--d1abbgf6aiiy.xn--p1ai")); // This uses a valid TLD } // labels are a max of 63 chars and domains 253 public void testValidator306() { final String longString = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789A"; assertEquals(63, longString.length()); // 26 * 2 + 11 assertTrue("63 chars label should validate", validator.isValidDomainSyntax(longString+".com")); assertFalse("64 chars label should fail", validator.isValidDomainSyntax(longString+"x.com")); assertTrue("63 chars TLD should validate", validator.isValidDomainSyntax("test."+longString)); assertFalse("64 chars TLD should fail", validator.isValidDomainSyntax("test.x"+longString)); final String longDomain = longString + "." + longString + "." + longString + "." + longString.substring(0,61) ; assertEquals(253, longDomain.length()); assertTrue("253 chars domain should validate", validator.isValidDomainSyntax(longDomain)); assertFalse("254 chars domain should fail", validator.isValidDomainSyntax(longDomain+"x")); } // Check that IDN.toASCII behaves as it should (when wrapped by DomainValidator.unicodeToASCII) // Tests show that method incorrectly trims a trailing "." character public void testUnicodeToASCII() { String[] asciidots = { "", ",", ".", // fails IDN.toASCII, but should pass wrapped version "a.", // ditto "a.b", "a..b", "a...b", ".a", "..a", }; for(String s : asciidots) { assertEquals(s,DomainValidator.unicodeToASCII(s)); } // RFC3490 3.1. 1) // Whenever dots are used as label separators, the following // characters MUST be recognized as dots: U+002E (full stop), U+3002 // (ideographic full stop), U+FF0E (fullwidth full stop), U+FF61 // (halfwidth ideographic full stop). final String otherDots[][] = { {"b\u3002", "b.",}, {"b\uFF0E", "b.",}, {"b\uFF61", "b.",}, {"\u3002", ".",}, {"\uFF0E", ".",}, {"\uFF61", ".",}, }; for(String s[] : otherDots) { assertEquals(s[1],DomainValidator.unicodeToASCII(s[0])); } } // Check if IDN.toASCII is broken or not public void testIsIDNtoASCIIBroken() { System.out.println(">>DomainValidatorTest.testIsIDNtoASCIIBroken()"); final String input = "."; final boolean ok = input.equals(IDN.toASCII(input)); System.out.println("IDN.toASCII is " + (ok? "OK" : "BROKEN")); String props[] = { "java.version", // Java Runtime Environment version "java.vendor", // Java Runtime Environment vendor "java.vm.specification.version", // Java Virtual Machine specification version "java.vm.specification.vendor", // Java Virtual Machine specification vendor "java.vm.specification.name", // Java Virtual Machine specification name "java.vm.version", // Java Virtual Machine implementation version "java.vm.vendor", // Java Virtual Machine implementation vendor "java.vm.name", // Java Virtual Machine implementation name "java.specification.version", // Java Runtime Environment specification version "java.specification.vendor", // Java Runtime Environment specification vendor "java.specification.name", // Java Runtime Environment specification name "java.class.version", // Java class format version number }; for(String t : props) { System.out.println(t + "=" + System.getProperty(t)); } System.out.println("<<DomainValidatorTest.testIsIDNtoASCIIBroken()"); } // Check array is sorted and is lower-case public void test_INFRASTRUCTURE_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("INFRASTRUCTURE_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case public void test_COUNTRY_CODE_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("COUNTRY_CODE_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case public void test_GENERIC_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("GENERIC_TLDS"); assertTrue(sorted); } // Check array is sorted and is lower-case public void test_LOCAL_TLDS_sortedAndLowerCase() throws Exception { final boolean sorted = isSortedLowerCase("LOCAL_TLDS"); assertTrue(sorted); } // Download and process local copy of http://data.iana.org/TLD/tlds-alpha-by-domain.txt // Check if the internal TLD table is up to date // Check if the internal TLD tables have any spurious entries public static void main(String a[]) throws Exception { Set<String> ianaTlds = new HashSet<String>(); // keep for comparison with array contents DomainValidator dv = DomainValidator.getInstance();; File txtFile = new File("target/tlds-alpha-by-domain.txt"); long timestamp = download(txtFile, "http://data.iana.org/TLD/tlds-alpha-by-domain.txt", 0L); final File htmlFile = new File("target/tlds-alpha-by-domain.html"); // N.B. sometimes the html file may be updated a day or so after the txt file // if the txt file contains entries not found in the html file, try again in a day or two download(htmlFile,"http://www.iana.org/domains/root/db", timestamp); BufferedReader br = new BufferedReader(new FileReader(txtFile)); String line; final String header; line = br.readLine(); // header if (line.startsWith("# Version ")) { header = line.substring(2); } else { br.close(); throw new IOException("File does not have expected Version header"); } final boolean generateUnicodeTlds = false; // Change this to generate Unicode TLDs as well // Parse html<SUF> Map<String, String[]> htmlInfo = getHtmlInfo(htmlFile); Map<String, String> missingTLD = new TreeMap<String, String>(); // stores entry and comments as String[] Map<String, String> missingCC = new TreeMap<String, String>(); while((line = br.readLine()) != null) { if (!line.startsWith("#")) { final String unicodeTld; // only different from asciiTld if that was punycode final String asciiTld = line.toLowerCase(Locale.ENGLISH); if (line.startsWith("XN--")) { unicodeTld = IDN.toUnicode(line); } else { unicodeTld = asciiTld; } if (!dv.isValidTld(asciiTld)) { String [] info = (String[]) htmlInfo.get(asciiTld); if (info != null) { String type = info[0]; String comment = info[1]; if ("country-code".equals(type)) { // Which list to use? missingCC.put(asciiTld, unicodeTld + " " + comment); if (generateUnicodeTlds) { missingCC.put(unicodeTld, asciiTld + " " + comment); } } else { missingTLD.put(asciiTld, unicodeTld + " " + comment); if (generateUnicodeTlds) { missingTLD.put(unicodeTld, asciiTld + " " + comment); } } } else { System.err.println("Expected to find info for "+ asciiTld); } } ianaTlds.add(asciiTld); // Don't merge these conditions; generateUnicodeTlds is final so needs to be separate to avoid a warning if (generateUnicodeTlds) { if (!unicodeTld.equals(asciiTld)) { ianaTlds.add(unicodeTld); } } } } br.close(); // List html entries not in TLD text list for(String key : (new TreeMap<String, String[]>(htmlInfo)).keySet()) { if (!ianaTlds.contains(key)) { System.err.println("Expected to find text entry for html: "+key); } } if (!missingTLD.isEmpty()) { printMap(header, missingTLD, "TLD"); } if (!missingCC.isEmpty()) { printMap(header, missingCC, "CC"); } // Check if internal tables contain any additional entries isInIanaList("INFRASTRUCTURE_TLDS", ianaTlds); isInIanaList("COUNTRY_CODE_TLDS", ianaTlds); isInIanaList("GENERIC_TLDS", ianaTlds); // Don't check local TLDS isInIanaList("LOCAL_TLDS", ianaTlds); System.out.println("Finished checks"); } private static void printMap(final String header, Map<String, String> map, String string) { System.out.println("Entries missing from "+ string +" List\n"); if (header != null) { System.out.println(" // Taken from " + header); } Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while(it.hasNext()){ Map.Entry<String, String> me = it.next(); System.out.println(" \"" + me.getKey() + "\", // " + me.getValue()); } System.out.println("\nDone"); } private static Map<String, String[]> getHtmlInfo(final File f) throws IOException { final Map<String, String[]> info = new HashMap<String, String[]>(); // <td><span class="domain tld"><a href="/domains/root/db/ax.html">.ax</a></span></td> final Pattern domain = Pattern.compile(".*<a href=\"/domains/root/db/([^.]+)\\.html"); // <td>country-code</td> final Pattern type = Pattern.compile("\\s+<td>([^<]+)</td>"); // <!-- <td>Åland Islands<br/><span class="tld-table-so">Ålands landskapsregering</span></td> </td> --> // <td>Ålands landskapsregering</td> final Pattern comment = Pattern.compile("\\s+<td>([^<]+)</td>"); final BufferedReader br = new BufferedReader(new FileReader(f)); String line; while((line=br.readLine())!=null){ Matcher m = domain.matcher(line); if (m.lookingAt()) { String dom = m.group(1); String typ = "??"; String com = "??"; line = br.readLine(); Matcher t = type.matcher(line); if (t.lookingAt()) { typ = t.group(1); line = br.readLine(); if (line.matches("\\s+<!--.*")) { while(!line.matches(".*-->.*")){ line = br.readLine(); } line = br.readLine(); } // Should have comment; is it wrapped? while(!line.matches(".*</td>.*")){ line += " " +br.readLine(); } Matcher n = comment.matcher(line); if (n.lookingAt()) { com = n.group(1); } // Don't save unused entries if (com.contains("Not assigned") || com.contains("Retired") || typ.equals("test")) { // System.out.println(dom + " " + typ + " " +com); } else { info.put(dom.toLowerCase(Locale.ENGLISH), new String[]{typ, com}); // System.out.println(dom + " " + typ + " " +com); } } } } br.close(); return info; } /* * Download a file if it is more recent than our cached copy. * Unfortunately the server does not seem to honour If-Modified-Since for the * Html page, so we check if it is newer than the txt file and skip download if so */ private static long download(File f, String tldurl, long timestamp) throws IOException { if (timestamp > 0 && f.canRead()) { long modTime = f.lastModified(); if (modTime > timestamp) { System.out.println("Skipping download - found recent " + f); return modTime; } } HttpURLConnection hc = (HttpURLConnection) new URL(tldurl).openConnection(); if (f.canRead()) { long modTime = f.lastModified(); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");//Sun, 06 Nov 1994 08:49:37 GMT String since = sdf.format(new Date(modTime)); hc.addRequestProperty("If-Modified-Since", since); System.out.println("Found " + f + " with date " + since); } if (hc.getResponseCode() == 304) { System.out.println("Already have most recent " + tldurl); } else { System.out.println("Downloading " + tldurl); byte buff[] = new byte[1024]; InputStream is = hc.getInputStream(); FileOutputStream fos = new FileOutputStream(f); int len; while((len=is.read(buff)) != -1) { fos.write(buff, 0, len); } fos.close(); is.close(); System.out.println("Done"); } return f.lastModified(); } // isInIanaList and isSorted are split into two methods. // If/when access to the arrays is possible without reflection, the intermediate // methods can be dropped private static boolean isInIanaList(String arrayName, Set<String> ianaTlds) throws Exception { Field f = DomainValidator.class.getDeclaredField(arrayName); final boolean isPrivate = Modifier.isPrivate(f.getModifiers()); if (isPrivate) { f.setAccessible(true); } String[] array = (String[]) f.get(null); try { return isInIanaList(arrayName, array, ianaTlds); } finally { if (isPrivate) { f.setAccessible(false); } } } private static boolean isInIanaList(String name, String [] array, Set<String> ianaTlds) { for(int i = 0; i < array.length; i++) { if (!ianaTlds.contains(array[i])) { System.out.println(name + " contains unexpected value: " + array[i]); } } return true; } private boolean isSortedLowerCase(String arrayName) throws Exception { Field f = DomainValidator.class.getDeclaredField(arrayName); final boolean isPrivate = Modifier.isPrivate(f.getModifiers()); if (isPrivate) { f.setAccessible(true); } String[] array = (String[]) f.get(null); try { return isSortedLowerCase(arrayName, array); } finally { if (isPrivate) { f.setAccessible(false); } } } private static boolean isLowerCase(String string) { return string.equals(string.toLowerCase(Locale.ENGLISH)); } // Check if an array is strictly sorted - and lowerCase private static boolean isSortedLowerCase(String name, String [] array) { boolean sorted = true; boolean strictlySorted = true; final int length = array.length; boolean lowerCase = isLowerCase(array[length-1]); // Check the last entry for(int i = 0; i < length-1; i++) { // compare all but last entry with next final String entry = array[i]; final String nextEntry = array[i+1]; final int cmp = entry.compareTo(nextEntry); if (cmp > 0) { // out of order System.out.println("Out of order entry: " + entry + " < " + nextEntry + " in " + name); sorted = false; } else if (cmp == 0) { strictlySorted = false; System.out.println("Duplicated entry: " + entry + " in " + name); } if (!isLowerCase(entry)) { System.out.println("Non lowerCase entry: " + entry + " in " + name); lowerCase = false; } } return sorted && strictlySorted && lowerCase; } }
10058_4
package helpers; import java.math.BigInteger; import java.util.Arrays; /** * * @author Arno, Nick, Peter */ public class ByteHelper { // joins two blocks each containing 4 significant bits (4 right most bits contain data) public static byte joinBlocks(byte block1, byte block2) { return (byte) (block1 << 4 | block2); } // based on http://stackoverflow.com/a/784842 public static byte[] concatBlocks(byte[] left, byte[] right) { byte[] result = Arrays.copyOf(left, left.length + right.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } // Herschikt de bits in de source byte array volgens de positions array // - Lengte van resultaat wordt bepaald door lengte van positions array public static byte[] permutate(byte[] source, int[] positions) { byte[] newBlock = new byte[positions.length / 8]; int byteIndex = -1; // voor elke positie for (int i = 0; i < positions.length; i++) { // neem de index van de bit int bitIndex = positions[i] - 1; // neem de waarde van de bit (0 of 1) byte bit = getBit(source, bitIndex); if (i % 8 == 0) { byteIndex++; } // zet de bit in de nieuwe blok op de juiste plaats newBlock[byteIndex] = (byte) ((bit << (bitIndex % 8)) | newBlock[byteIndex]); } return newBlock; } // http://n3vrax.wordpress.com/2011/07/23/des-algorithm-java-implementation/ public static byte[] permutFunc(byte[] input, int[] table) { int nrBytes = (table.length - 1) / 8 + 1; byte[] out = new byte[nrBytes]; for (int i = 0; i < table.length; i++) { int val = getBitInt(input, table[i] - 1); setBit(out, i, val); } return out; } // Kijkt of een bepaalde bit in een byte array gelijk aan 1 is public static byte getBit(byte[] data, int pos) { int posByte = pos / 8; int posBit = pos % 8; byte valByte = data[posByte]; return (byte) (isBitSet(valByte, posBit) ? 1 : 0); } // Kijkt of een bepaalde bit in een byte gelijk aan 1 is // Source: http://stackoverflow.com/questions/1034473/java-iterate-bits-in-byte-array public static Boolean isBitSet(byte value, int bit) { return (value & (1 << bit)) != 0; } // Voert XOR uit op twee byte arrays // Arrays moeten van de zelfde lengte zijn public static byte[] xorByteBlocks(byte[] blockOne, byte[] blockTwo) { byte[] newBlock = new byte[blockOne.length]; for (int i = 0; i < newBlock.length; i++) { newBlock[i] = (byte) (blockOne[i] ^ blockTwo[i]); } return newBlock; } // Zorgt voor de left shift // Source: http://www.herongyang.com/Java/Bit-String-Left-Rotation-All-Bits-in-Byte-Array.html public static byte[] rotateLeft(byte[] in, int len, int step) { int numOfBytes = (len - 1) / 8 + 1; byte[] out = new byte[numOfBytes]; for (int i = 0; i < len; i++) { int val = getBitInt(in, (i + step) % len); setBit(out, i, val); } return out; } //nick: Arno heeft hier een functie voor weet niet zeker of zelfde resultaat, later testen. // Haalt de bit op op positie pos in de byte array data // Source: http://www.herongyang.com/Java/Bit-String-Get-Bit-from-Byte-Array.html public static int getBitInt(byte[] data, int pos) { int posByte = pos / 8; int posBit = pos % 8; byte valByte = data[posByte]; int valInt = valByte >> (8 - (posBit + 1)) & 0x0001; return valInt; } //nick: misschien deze functie zelf uitschrijven, deze komt rechstreeks van de site. // Stelt de bit op op positie pos in de byte array data // Source: http://www.herongyang.com/Java/Bit-String-Get-Bit-from-Byte-Array.html public static void setBit(byte[] data, int pos, int val) { int posByte = pos / 8; int posBit = pos % 8; byte oldByte = data[posByte]; oldByte = (byte) (((0xFF7F >> posBit) & oldByte) & 0x00FF); byte newByte = (byte) ((val << (8 - (posBit + 1))) | oldByte); data[posByte] = newByte; } // http://stackoverflow.com/a/6393904 public static void printByteArray(byte[] bytes) { for (byte b : bytes) { System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1) + " "); } System.out.println(); } public static void printByte(byte b){ System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1) + " \n"); } public static byte[] convertBinaryStringToByteArray(String binaryString) { byte[] bytes = new BigInteger(binaryString.replace(" ", ""), 2).toByteArray(); // als eerste bit == 1 wordt een extra byte met allemaal nullen toegevoegd if (binaryString.charAt(0) == '1') { return Arrays.copyOfRange(bytes, 1, bytes.length); } return bytes; } /** * Get the first half of the specified block. * The significant bits are on the left. * eg. when a block with an odd length is split in half, only the first 4 bits * of the last byte are significant. * * @param block the block to be split in half * @return byte[] the first half of the specified block */ public static byte[] getFirstHalf(byte[] block) { return Arrays.copyOfRange(block, 0, (int) Math.ceil(block.length / 2.0)); } /** * Get the second half of the specified block. * The significant bits are on the left. * eg. when a block with an odd length is split in half, only the first 4 bits * of the last byte are significant. * * @param block the block to be split in half * @return byte[] the second half of the specified block */ public static byte[] getSecondHalf(byte[] block) { byte[] temp = Arrays.copyOfRange(block, block.length / 2, block.length); // middle of block is in the middle of a byte if ( (block.length / 2d) % 1 == 0.5) { temp = ByteHelper.rotateLeft(temp, temp.length * 8, 4); } return temp; } }
peterneyens/DES
src/main/java/helpers/ByteHelper.java
1,999
// - Lengte van resultaat wordt bepaald door lengte van positions array
line_comment
nl
package helpers; import java.math.BigInteger; import java.util.Arrays; /** * * @author Arno, Nick, Peter */ public class ByteHelper { // joins two blocks each containing 4 significant bits (4 right most bits contain data) public static byte joinBlocks(byte block1, byte block2) { return (byte) (block1 << 4 | block2); } // based on http://stackoverflow.com/a/784842 public static byte[] concatBlocks(byte[] left, byte[] right) { byte[] result = Arrays.copyOf(left, left.length + right.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } // Herschikt de bits in de source byte array volgens de positions array // - Lengte<SUF> public static byte[] permutate(byte[] source, int[] positions) { byte[] newBlock = new byte[positions.length / 8]; int byteIndex = -1; // voor elke positie for (int i = 0; i < positions.length; i++) { // neem de index van de bit int bitIndex = positions[i] - 1; // neem de waarde van de bit (0 of 1) byte bit = getBit(source, bitIndex); if (i % 8 == 0) { byteIndex++; } // zet de bit in de nieuwe blok op de juiste plaats newBlock[byteIndex] = (byte) ((bit << (bitIndex % 8)) | newBlock[byteIndex]); } return newBlock; } // http://n3vrax.wordpress.com/2011/07/23/des-algorithm-java-implementation/ public static byte[] permutFunc(byte[] input, int[] table) { int nrBytes = (table.length - 1) / 8 + 1; byte[] out = new byte[nrBytes]; for (int i = 0; i < table.length; i++) { int val = getBitInt(input, table[i] - 1); setBit(out, i, val); } return out; } // Kijkt of een bepaalde bit in een byte array gelijk aan 1 is public static byte getBit(byte[] data, int pos) { int posByte = pos / 8; int posBit = pos % 8; byte valByte = data[posByte]; return (byte) (isBitSet(valByte, posBit) ? 1 : 0); } // Kijkt of een bepaalde bit in een byte gelijk aan 1 is // Source: http://stackoverflow.com/questions/1034473/java-iterate-bits-in-byte-array public static Boolean isBitSet(byte value, int bit) { return (value & (1 << bit)) != 0; } // Voert XOR uit op twee byte arrays // Arrays moeten van de zelfde lengte zijn public static byte[] xorByteBlocks(byte[] blockOne, byte[] blockTwo) { byte[] newBlock = new byte[blockOne.length]; for (int i = 0; i < newBlock.length; i++) { newBlock[i] = (byte) (blockOne[i] ^ blockTwo[i]); } return newBlock; } // Zorgt voor de left shift // Source: http://www.herongyang.com/Java/Bit-String-Left-Rotation-All-Bits-in-Byte-Array.html public static byte[] rotateLeft(byte[] in, int len, int step) { int numOfBytes = (len - 1) / 8 + 1; byte[] out = new byte[numOfBytes]; for (int i = 0; i < len; i++) { int val = getBitInt(in, (i + step) % len); setBit(out, i, val); } return out; } //nick: Arno heeft hier een functie voor weet niet zeker of zelfde resultaat, later testen. // Haalt de bit op op positie pos in de byte array data // Source: http://www.herongyang.com/Java/Bit-String-Get-Bit-from-Byte-Array.html public static int getBitInt(byte[] data, int pos) { int posByte = pos / 8; int posBit = pos % 8; byte valByte = data[posByte]; int valInt = valByte >> (8 - (posBit + 1)) & 0x0001; return valInt; } //nick: misschien deze functie zelf uitschrijven, deze komt rechstreeks van de site. // Stelt de bit op op positie pos in de byte array data // Source: http://www.herongyang.com/Java/Bit-String-Get-Bit-from-Byte-Array.html public static void setBit(byte[] data, int pos, int val) { int posByte = pos / 8; int posBit = pos % 8; byte oldByte = data[posByte]; oldByte = (byte) (((0xFF7F >> posBit) & oldByte) & 0x00FF); byte newByte = (byte) ((val << (8 - (posBit + 1))) | oldByte); data[posByte] = newByte; } // http://stackoverflow.com/a/6393904 public static void printByteArray(byte[] bytes) { for (byte b : bytes) { System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1) + " "); } System.out.println(); } public static void printByte(byte b){ System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1) + " \n"); } public static byte[] convertBinaryStringToByteArray(String binaryString) { byte[] bytes = new BigInteger(binaryString.replace(" ", ""), 2).toByteArray(); // als eerste bit == 1 wordt een extra byte met allemaal nullen toegevoegd if (binaryString.charAt(0) == '1') { return Arrays.copyOfRange(bytes, 1, bytes.length); } return bytes; } /** * Get the first half of the specified block. * The significant bits are on the left. * eg. when a block with an odd length is split in half, only the first 4 bits * of the last byte are significant. * * @param block the block to be split in half * @return byte[] the first half of the specified block */ public static byte[] getFirstHalf(byte[] block) { return Arrays.copyOfRange(block, 0, (int) Math.ceil(block.length / 2.0)); } /** * Get the second half of the specified block. * The significant bits are on the left. * eg. when a block with an odd length is split in half, only the first 4 bits * of the last byte are significant. * * @param block the block to be split in half * @return byte[] the second half of the specified block */ public static byte[] getSecondHalf(byte[] block) { byte[] temp = Arrays.copyOfRange(block, block.length / 2, block.length); // middle of block is in the middle of a byte if ( (block.length / 2d) % 1 == 0.5) { temp = ByteHelper.rotateLeft(temp, temp.length * 8, 4); } return temp; } }
147132_9
/* DroidFish - An Android chess program. Copyright (C) 2020 Peter Österlund, [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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.petero.droidfish.book; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import org.petero.droidfish.book.DroidBook.BookEntry; import org.petero.droidfish.gamelogic.ChessParseError; import org.petero.droidfish.gamelogic.Move; import org.petero.droidfish.gamelogic.Piece; import org.petero.droidfish.gamelogic.Position; import org.petero.droidfish.gamelogic.TextIO; /** Handle Arena Chess GUI opening books. */ class AbkBook implements IOpeningBook { private File abkFile; // The ".abk" file private Position startPos; /** Constructor. */ public AbkBook() { try { startPos = TextIO.readFEN(TextIO.startPosFEN); } catch (ChessParseError ex) { throw new RuntimeException(ex); } } static boolean canHandle(BookOptions options) { String filename = options.filename; return filename.endsWith(".abk"); } @Override public boolean enabled() { return abkFile.canRead(); } @Override public void setOptions(BookOptions options) { abkFile = new File(options.filename); } private static class MoveData { Move move; double weightPrio; double weightNGames; double weightScore; } @Override public ArrayList<BookEntry> getBookEntries(BookPosInput posInput) { if (!startPos.equals(posInput.getPrevPos())) return null; try (RandomAccessFile abkF = new RandomAccessFile(abkFile, "r")) { ArrayList<Move> gameMoves = posInput.getMoves(); BookSettings bs = new BookSettings(abkF); if (gameMoves.size() >= bs.maxPly) return null; AbkBookEntry ent = new AbkBookEntry(); int entNo = 900; for (Move m : gameMoves) { int iter = 0; while (true) { if (entNo < 0) return null; ent.read(abkF, entNo); if (ent.getMove().equals(m) && ent.isValid()) { entNo = ent.nextMove; break; } entNo = ent.nextSibling; iter++; if (iter > 255) return null; // Corrupt book } } if (entNo < 0) return null; boolean wtm = (gameMoves.size() % 2) == 0; ArrayList<MoveData> moves = new ArrayList<>(); while (entNo >= 0) { ent.read(abkF, entNo); MoveData md = new MoveData(); md.move = ent.getMove(); int nWon = wtm ? ent.nWon : ent.nLost; int nLost = wtm ? ent.nLost : ent.nWon; int nDraw = ent.nGames - nWon - nLost; md.weightPrio = scaleWeight(ent.priority, bs.prioImportance); md.weightNGames = scaleWeight(ent.nGames, bs.nGamesImportance); double score = (nWon + nDraw * 0.5) / ent.nGames; md.weightScore = scaleWeight(score, bs.scoreImportance); if (ent.isValid() && (!bs.skipPrio0Moves || ent.priority > 0) && (ent.nGames >= bs.minGames) && (nWon >= bs.minWonGames) && (score * 100 >= (wtm ? bs.minWinPercentWhite : bs.minWinPercentBlack))) { moves.add(md); } if (moves.size() > 255) return null; // Corrupt book entNo = ent.nextSibling; } double sumWeightPrio = 0; double sumWeightNGames = 0; double sumWeightScore = 0; for (MoveData md : moves) { sumWeightPrio += md.weightPrio; sumWeightNGames += md.weightNGames; sumWeightScore += md.weightScore; } ArrayList<BookEntry> ret = new ArrayList<>(); boolean hasNonZeroWeight = false; for (MoveData md : moves) { BookEntry be = new BookEntry(md.move); double wP = sumWeightPrio > 0 ? md.weightPrio / sumWeightPrio : 0.0; double wN = sumWeightNGames > 0 ? md.weightNGames / sumWeightNGames : 0.0; double wS = sumWeightScore > 0 ? md.weightScore / sumWeightScore : 0.0; double a = 0.624; double w = wP * Math.exp(a * bs.prioImportance) + wN * Math.exp(a * bs.nGamesImportance) + wS * Math.exp(a * bs.scoreImportance) * 1.4; hasNonZeroWeight |= w > 0; be.weight = (float)w; ret.add(be); } if (!hasNonZeroWeight) for (BookEntry be : ret) be.weight = 1; return ret; } catch (IOException e) { return null; } } private static class AbkBookEntry { private byte[] data = new byte[28]; private byte from; // From square, 0 = a1, 7 = h1, 8 = a2, 63 = h8 private byte to; // To square private byte promotion; // 0 = none, +-1 = rook, +-2 = knight, +-3 = bishop, +-4 = queen byte priority; // 0 = bad, >0 better, 9 best int nGames; // Number of times games in which move was played int nWon; // Number of won games for white int nLost; // Number of lost games for white int flags; // Value is 0x01000000 if move has been deleted int nextMove; // First following move (by opposite color) int nextSibling; // Next alternative move (by same color) AbkBookEntry() { } void read(RandomAccessFile f, long entNo) throws IOException { f.seek(entNo * 28); f.readFully(data); from = data[0]; to = data[1]; promotion = data[2]; priority = data[3]; nGames = extractInt(4); nWon = extractInt(8); nLost = extractInt(12); flags = extractInt(16); nextMove = extractInt(20); nextSibling = extractInt(24); } Move getMove() { int prom; switch (promotion) { case 0: prom = Piece.EMPTY; break; case -1: prom = Piece.WROOK; break; case -2: prom = Piece.WKNIGHT; break; case -3: prom = Piece.WBISHOP; break; case -4: prom = Piece.WQUEEN; break; case 1: prom = Piece.BROOK; break; case 2: prom = Piece.BKNIGHT; break; case 3: prom = Piece.BBISHOP; break; case 4: prom = Piece.BQUEEN; break; default: prom = -1; break; } return new Move(from, to, prom); } boolean isValid() { return flags != 0x01000000; } private int extractInt(int offs) { return AbkBook.extractInt(data, offs); } } /** Convert 4 bytes starting at "offs" in buf[] to an integer. */ private static int extractInt(byte[] buf, int offs) { int ret = 0; for (int i = 3; i >= 0; i--) { int b = buf[offs + i]; if (b < 0) b += 256; ret = (ret << 8) + b; } return ret; } private static class BookSettings { private byte[] buf = new byte[256]; int minGames; int minWonGames; int minWinPercentWhite; // 0 - 100 int minWinPercentBlack; // 0 - 100 int prioImportance; // 0 - 15 int nGamesImportance; // 0 - 15 int scoreImportance; // 0 - 15 int maxPly; boolean skipPrio0Moves = false; // Not stored in abk file public BookSettings(RandomAccessFile abkF) throws IOException { abkF.seek(0); abkF.readFully(buf); minGames = getInt(0xde, Integer.MAX_VALUE); minWonGames = getInt(0xe2, Integer.MAX_VALUE); minWinPercentWhite = getInt(0xe6, 100); minWinPercentBlack = getInt(0xea, 100); prioImportance = getInt(0xee, 15); nGamesImportance = getInt(0xf2, 15); scoreImportance = getInt(0xf6, 15); maxPly = getInt(0xfa, 9999); if (prioImportance == 0 && nGamesImportance == 0 && scoreImportance == 0) { minGames = 0; minWonGames = 0; minWinPercentWhite = 0; minWinPercentBlack = 0; } } private int getInt(int offs, int maxVal) { int val = extractInt(buf, offs); return Math.min(Math.max(val, 0), maxVal); } } private static double scaleWeight(double w, int importance) { double e; switch (importance) { case 0: return 0; case 1: e = 0.66; break; case 2: e = 0.86; break; default: e = 1 + ((double)importance - 3) / 6; break; } return Math.pow(w, e); } }
peterosterlund2/droidfish
DroidFishApp/src/main/java/org/petero/droidfish/book/AbkBook.java
3,086
// Value is 0x01000000 if move has been deleted
line_comment
nl
/* DroidFish - An Android chess program. Copyright (C) 2020 Peter Österlund, [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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.petero.droidfish.book; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import org.petero.droidfish.book.DroidBook.BookEntry; import org.petero.droidfish.gamelogic.ChessParseError; import org.petero.droidfish.gamelogic.Move; import org.petero.droidfish.gamelogic.Piece; import org.petero.droidfish.gamelogic.Position; import org.petero.droidfish.gamelogic.TextIO; /** Handle Arena Chess GUI opening books. */ class AbkBook implements IOpeningBook { private File abkFile; // The ".abk" file private Position startPos; /** Constructor. */ public AbkBook() { try { startPos = TextIO.readFEN(TextIO.startPosFEN); } catch (ChessParseError ex) { throw new RuntimeException(ex); } } static boolean canHandle(BookOptions options) { String filename = options.filename; return filename.endsWith(".abk"); } @Override public boolean enabled() { return abkFile.canRead(); } @Override public void setOptions(BookOptions options) { abkFile = new File(options.filename); } private static class MoveData { Move move; double weightPrio; double weightNGames; double weightScore; } @Override public ArrayList<BookEntry> getBookEntries(BookPosInput posInput) { if (!startPos.equals(posInput.getPrevPos())) return null; try (RandomAccessFile abkF = new RandomAccessFile(abkFile, "r")) { ArrayList<Move> gameMoves = posInput.getMoves(); BookSettings bs = new BookSettings(abkF); if (gameMoves.size() >= bs.maxPly) return null; AbkBookEntry ent = new AbkBookEntry(); int entNo = 900; for (Move m : gameMoves) { int iter = 0; while (true) { if (entNo < 0) return null; ent.read(abkF, entNo); if (ent.getMove().equals(m) && ent.isValid()) { entNo = ent.nextMove; break; } entNo = ent.nextSibling; iter++; if (iter > 255) return null; // Corrupt book } } if (entNo < 0) return null; boolean wtm = (gameMoves.size() % 2) == 0; ArrayList<MoveData> moves = new ArrayList<>(); while (entNo >= 0) { ent.read(abkF, entNo); MoveData md = new MoveData(); md.move = ent.getMove(); int nWon = wtm ? ent.nWon : ent.nLost; int nLost = wtm ? ent.nLost : ent.nWon; int nDraw = ent.nGames - nWon - nLost; md.weightPrio = scaleWeight(ent.priority, bs.prioImportance); md.weightNGames = scaleWeight(ent.nGames, bs.nGamesImportance); double score = (nWon + nDraw * 0.5) / ent.nGames; md.weightScore = scaleWeight(score, bs.scoreImportance); if (ent.isValid() && (!bs.skipPrio0Moves || ent.priority > 0) && (ent.nGames >= bs.minGames) && (nWon >= bs.minWonGames) && (score * 100 >= (wtm ? bs.minWinPercentWhite : bs.minWinPercentBlack))) { moves.add(md); } if (moves.size() > 255) return null; // Corrupt book entNo = ent.nextSibling; } double sumWeightPrio = 0; double sumWeightNGames = 0; double sumWeightScore = 0; for (MoveData md : moves) { sumWeightPrio += md.weightPrio; sumWeightNGames += md.weightNGames; sumWeightScore += md.weightScore; } ArrayList<BookEntry> ret = new ArrayList<>(); boolean hasNonZeroWeight = false; for (MoveData md : moves) { BookEntry be = new BookEntry(md.move); double wP = sumWeightPrio > 0 ? md.weightPrio / sumWeightPrio : 0.0; double wN = sumWeightNGames > 0 ? md.weightNGames / sumWeightNGames : 0.0; double wS = sumWeightScore > 0 ? md.weightScore / sumWeightScore : 0.0; double a = 0.624; double w = wP * Math.exp(a * bs.prioImportance) + wN * Math.exp(a * bs.nGamesImportance) + wS * Math.exp(a * bs.scoreImportance) * 1.4; hasNonZeroWeight |= w > 0; be.weight = (float)w; ret.add(be); } if (!hasNonZeroWeight) for (BookEntry be : ret) be.weight = 1; return ret; } catch (IOException e) { return null; } } private static class AbkBookEntry { private byte[] data = new byte[28]; private byte from; // From square, 0 = a1, 7 = h1, 8 = a2, 63 = h8 private byte to; // To square private byte promotion; // 0 = none, +-1 = rook, +-2 = knight, +-3 = bishop, +-4 = queen byte priority; // 0 = bad, >0 better, 9 best int nGames; // Number of times games in which move was played int nWon; // Number of won games for white int nLost; // Number of lost games for white int flags; // Value is<SUF> int nextMove; // First following move (by opposite color) int nextSibling; // Next alternative move (by same color) AbkBookEntry() { } void read(RandomAccessFile f, long entNo) throws IOException { f.seek(entNo * 28); f.readFully(data); from = data[0]; to = data[1]; promotion = data[2]; priority = data[3]; nGames = extractInt(4); nWon = extractInt(8); nLost = extractInt(12); flags = extractInt(16); nextMove = extractInt(20); nextSibling = extractInt(24); } Move getMove() { int prom; switch (promotion) { case 0: prom = Piece.EMPTY; break; case -1: prom = Piece.WROOK; break; case -2: prom = Piece.WKNIGHT; break; case -3: prom = Piece.WBISHOP; break; case -4: prom = Piece.WQUEEN; break; case 1: prom = Piece.BROOK; break; case 2: prom = Piece.BKNIGHT; break; case 3: prom = Piece.BBISHOP; break; case 4: prom = Piece.BQUEEN; break; default: prom = -1; break; } return new Move(from, to, prom); } boolean isValid() { return flags != 0x01000000; } private int extractInt(int offs) { return AbkBook.extractInt(data, offs); } } /** Convert 4 bytes starting at "offs" in buf[] to an integer. */ private static int extractInt(byte[] buf, int offs) { int ret = 0; for (int i = 3; i >= 0; i--) { int b = buf[offs + i]; if (b < 0) b += 256; ret = (ret << 8) + b; } return ret; } private static class BookSettings { private byte[] buf = new byte[256]; int minGames; int minWonGames; int minWinPercentWhite; // 0 - 100 int minWinPercentBlack; // 0 - 100 int prioImportance; // 0 - 15 int nGamesImportance; // 0 - 15 int scoreImportance; // 0 - 15 int maxPly; boolean skipPrio0Moves = false; // Not stored in abk file public BookSettings(RandomAccessFile abkF) throws IOException { abkF.seek(0); abkF.readFully(buf); minGames = getInt(0xde, Integer.MAX_VALUE); minWonGames = getInt(0xe2, Integer.MAX_VALUE); minWinPercentWhite = getInt(0xe6, 100); minWinPercentBlack = getInt(0xea, 100); prioImportance = getInt(0xee, 15); nGamesImportance = getInt(0xf2, 15); scoreImportance = getInt(0xf6, 15); maxPly = getInt(0xfa, 9999); if (prioImportance == 0 && nGamesImportance == 0 && scoreImportance == 0) { minGames = 0; minWonGames = 0; minWinPercentWhite = 0; minWinPercentBlack = 0; } } private int getInt(int offs, int maxVal) { int val = extractInt(buf, offs); return Math.min(Math.max(val, 0), maxVal); } } private static double scaleWeight(double w, int importance) { double e; switch (importance) { case 0: return 0; case 1: e = 0.66; break; case 2: e = 0.86; break; default: e = 1 + ((double)importance - 3) / 6; break; } return Math.pow(w, e); } }
46818_8
import java.util.concurrent.Semaphore; import java.util.logging.Level; import java.util.logging.Logger; public class Main implements Runnable { private final static Logger LOGGER = Logger.getLogger(Main.class.getName()); private final static Semaphore bridge = new Semaphore(1); private static String farmerNorthLocation = "north"; private static String farmerSouthLocation = "south"; private String farmer; private Main(String farmer) { this.farmer = farmer; } public static void main(String[] args) { Thread farmerNorth = new Thread(new Main("n")); Thread farmerSouth = new Thread(new Main("s")); farmerNorth.start(); // farmerNorth gaat naar de bridge toe farmerSouth.start(); // farmerSouth gaat naar de bridge toe // Thread[] threads = new Thread[100]; // for (int i = 0; i < threads.length ; i++) { // threads[i] = new Thread(new Main(i % 2 == 0 ? "n" : "s")); // threads[i].start(); // } } @Override public void run() { LOGGER.log(Level.WARNING, "Iemand is bij de bridge aangekomen. Aantal wachtende voor de bridge: "+Main.bridge.getQueueLength()); try { Main.bridge.acquire(); // vraag de bridge op if ("n".equals(this.farmer)) { // verander de locatie van farmer == "n" Main.farmerNorthLocation = Main.farmerNorthLocation.equals("north") ? "south" : "north"; LOGGER.log(Level.INFO, "Boer: "+this.farmer+", is de bridge over en in: "+Main.farmerNorthLocation); } if ("s".equals(this.farmer)) { // verander de locatie van farmer == "s" Main.farmerSouthLocation = Main.farmerSouthLocation.equals("north") ? "south" : "north"; LOGGER.log(Level.INFO, "Boer: "+this.farmer+", is de bridge over en in: "+Main.farmerSouthLocation); } Main.bridge.release(); // geef de bridge af LOGGER.log(Level.WARNING, "Iemand is over de bridge gereden. Aantal wachtende voor de bridge: "+Main.bridge.getQueueLength()); } catch (Exception e) { LOGGER.log(Level.INFO, e.getMessage()); } } }
peterschriever/os-concepts
week-3/src/Main.java
667
// geef de bridge af
line_comment
nl
import java.util.concurrent.Semaphore; import java.util.logging.Level; import java.util.logging.Logger; public class Main implements Runnable { private final static Logger LOGGER = Logger.getLogger(Main.class.getName()); private final static Semaphore bridge = new Semaphore(1); private static String farmerNorthLocation = "north"; private static String farmerSouthLocation = "south"; private String farmer; private Main(String farmer) { this.farmer = farmer; } public static void main(String[] args) { Thread farmerNorth = new Thread(new Main("n")); Thread farmerSouth = new Thread(new Main("s")); farmerNorth.start(); // farmerNorth gaat naar de bridge toe farmerSouth.start(); // farmerSouth gaat naar de bridge toe // Thread[] threads = new Thread[100]; // for (int i = 0; i < threads.length ; i++) { // threads[i] = new Thread(new Main(i % 2 == 0 ? "n" : "s")); // threads[i].start(); // } } @Override public void run() { LOGGER.log(Level.WARNING, "Iemand is bij de bridge aangekomen. Aantal wachtende voor de bridge: "+Main.bridge.getQueueLength()); try { Main.bridge.acquire(); // vraag de bridge op if ("n".equals(this.farmer)) { // verander de locatie van farmer == "n" Main.farmerNorthLocation = Main.farmerNorthLocation.equals("north") ? "south" : "north"; LOGGER.log(Level.INFO, "Boer: "+this.farmer+", is de bridge over en in: "+Main.farmerNorthLocation); } if ("s".equals(this.farmer)) { // verander de locatie van farmer == "s" Main.farmerSouthLocation = Main.farmerSouthLocation.equals("north") ? "south" : "north"; LOGGER.log(Level.INFO, "Boer: "+this.farmer+", is de bridge over en in: "+Main.farmerSouthLocation); } Main.bridge.release(); // geef de<SUF> LOGGER.log(Level.WARNING, "Iemand is over de bridge gereden. Aantal wachtende voor de bridge: "+Main.bridge.getQueueLength()); } catch (Exception e) { LOGGER.log(Level.INFO, e.getMessage()); } } }
201672_26
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo.recording.jibri; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import net.java.sip.communicator.service.protocol.*; import org.jetbrains.annotations.*; import org.jitsi.eventadmin.*; import org.jitsi.jicofo.*; import org.jitsi.osgi.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.utils.logging.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import java.util.*; import java.util.concurrent.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas */ public class JibriSession { /** * The class logger which can be used to override logging level inherited * from {@link JitsiMeetConference}. */ static private final Logger classLogger = Logger.getLogger(JibriSession.class); /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. */ private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for {@link JibriEvent}s in the OSGi context * obtained from the {@link FocusBundleActivator}. */ private final JibriEventHandler jibriEventHandler = new JibriEventHandler(); /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * The logger for this instance. Uses the logging level either of the * {@link #classLogger} or {@link JitsiMeetConference#getLogger()} * whichever is higher. */ private final Logger logger; /** * The owner which will be notified about status changes of this session. */ private final Owner owner; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link XmppConnection} instance used to send/listen for XMPP packets. */ private final XmppConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * Creates new {@link JibriSession} instance. * @param owner the session owner which will be notified about this session * state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param scheduledExecutor the executor service which will be used to * schedule pending timeout task execution. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( JibriSession.Owner owner, EntityBareJid roomName, long pendingTimeout, int maxNumRetries, XmppConnection connection, ScheduledExecutorService scheduledExecutor, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.owner = owner; this.roomName = roomName; this.scheduledExecutor = Objects.requireNonNull(scheduledExecutor, "scheduledExecutor"); this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; logger = Logger.getLogger(classLogger, logLevelDelegate); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @return true if the start is successful, false otherwise */ synchronized public boolean start() { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid != null) { try { jibriEventHandler.start(FocusBundleActivator.bundleContext); sendJibriStartIq(jibriJid); logger.info("Starting session with Jibri " + jibriJid); return true; } catch (Exception e) { logger.error("Failed to start Jibri event handler: " + e, e); } } else { logger.error("Unable to find an available Jibri, can't start"); } return false; } /** * Stops this session if it's not already stopped. */ synchronized public void stop() { if (currentJibriJid == null) { return; } JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(JibriIq.Action.STOP); logger.info("Trying to stop: " + stopRequest.toXML()); // When we send stop, we won't get an OFF presence back (just // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { JibriIq resp = (JibriIq)stanza; handleJibriStatusUpdate(resp.getFrom(), resp.getStatus(), resp.getFailureReason()); }, exception -> { logger.error("Error sending stop iq: " + exception.toString()); }, 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; try { jibriEventHandler.stop(FocusBundleActivator.bundleContext); } catch (Exception e) { logger.error("Failed to stop Jibri event handler: " + e, e); } } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } IQ processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { logger.info( "Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate(iq.getFrom(), status, iq.getFailureReason()); } else { logger.error("Received UNDEFINED status from jibri: " + iq.toString()); } return IQ.createResultIQ(iq); } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ JibriIq.RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. */ private void sendJibriStartIq(final Jid jibriJid) { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(JibriIq.Action.START); startIq.setSessionId(this.sessionId); logger.debug("Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); try { JibriIq result = (JibriIq)xmpp.sendPacketAndGetReply(startIq); handleJibriStatusUpdate(result.getFrom(), result.getStatus(), result.getFailureReason()); } catch (OperationFailedException e) { logger.error("Error sending Jibri start IQ: " + e.toString()); } } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will * clear recording state after * {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we should retry again, false otherwise */ private boolean shouldRetryRequest() { return (maxNumRetries < 0 || numRetries < maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @return true if we were able to find another Jibri to retry the request with, * false otherwise */ private boolean retryRequestWithAnotherJibri() { numRetries++; return start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully (or there was an error but we * have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, JibriIq.Status newStatus, @Nullable JibriIq.FailureReason failureReason) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's new state), make sure we stop // the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info("Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another Jibri to keep things going if (failureReason != null) { // There was an error with the current Jibri, see if we should retry if (shouldRetryRequest()) { logger.info("Jibri failed, trying to fall back to another Jibri"); if (retryRequestWithAnotherJibri()) { // The fallback to another Jibri succeeded. logger.info("Successfully resumed session with another Jibri"); } else { logger.info("Failed to fall back to another Jibri, this session has now failed"); // Propagate up that the session has failed entirely. We'll pass the original failure reason. owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } } else { // The Jibri we tried failed and we've reached the maxmium amount of retries we've been // configured to attempt, so we'll give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and cleaning up session"); // The Jibri stopped for some non-error reason owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); // The Jibri stopped for some non-error reason owner.onSessionStateChanged(this, newStatus, failureReason); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Helper class handles registration for the {@link JibriEvent}s. */ private class JibriEventHandler extends EventHandlerActivator { private JibriEventHandler() { super(new String[]{ JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE}); } @Override public void handleEvent(Event event) { if (!JibriEvent.isJibriEvent(event)) { logger.error("Invalid event: " + event); return; } final JibriEvent jibriEvent = (JibriEvent) event; final String topic = jibriEvent.getTopic(); final Jid jibriJid = jibriEvent.getJibriJid(); synchronized (JibriSession.this) { if (JibriEvent.WENT_OFFLINE.equals(topic) && jibriJid.equals(currentJibriJid)) { logger.error( nickname() + " went offline: " + jibriJid + " for room: " + roomName); handleJibriStatusUpdate(jibriJid, Status.OFF, FailureReason.ERROR); } } } } /** * Task scheduled after we have received RESULT response from Jibri and * entered PENDING state. Will abort the recording if we do not transit to * ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()} * limit is exceeded. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's likely hung or having // some issue. We'll send a stop (so if/when it does 'recover', it knows to // stop) and simulate an error status (like we do in JibriEventHandler#handleEvent // when a Jibri goes offline) to trigger the fallback logic. stop(); handleJibriStatusUpdate(currentJibriJid, Status.OFF, FailureReason.ERROR); } } } } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface Owner { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link JibriIq.Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, JibriIq.Status newStatus, JibriIq.FailureReason failureReason); } }
pfisher/jicofo
src/main/java/org/jitsi/jicofo/recording/jibri/JibriSession.java
6,455
// When we send stop, we won't get an OFF presence back (just
line_comment
nl
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo.recording.jibri; import org.jitsi.xmpp.extensions.jibri.*; import org.jitsi.xmpp.extensions.jibri.JibriIq.*; import net.java.sip.communicator.service.protocol.*; import org.jetbrains.annotations.*; import org.jitsi.eventadmin.*; import org.jitsi.jicofo.*; import org.jitsi.osgi.*; import org.jitsi.protocol.xmpp.*; import org.jitsi.utils.logging.*; import org.jivesoftware.smack.*; import org.jivesoftware.smack.packet.*; import org.jxmpp.jid.*; import java.util.*; import java.util.concurrent.*; /** * Class holds the information about Jibri session. It can be either live * streaming or SIP gateway session {@link #isSIP}. Encapsulates the retry logic * which is supposed to try another instance when the current one fails. To make * this happen it needs to cache all the information required to start new * session. It uses {@link JibriDetector} to select new Jibri. * * @author Pawel Domas */ public class JibriSession { /** * The class logger which can be used to override logging level inherited * from {@link JitsiMeetConference}. */ static private final Logger classLogger = Logger.getLogger(JibriSession.class); /** * Returns <tt>true</tt> if given <tt>status</tt> indicates that Jibri is in * the middle of starting of the recording process. */ static private boolean isStartingStatus(JibriIq.Status status) { return JibriIq.Status.PENDING.equals(status); } /** * The JID of the Jibri currently being used by this session or * <tt>null</tt> otherwise. */ private Jid currentJibriJid; /** * The display name Jibri attribute received from Jitsi Meet to be passed * further to Jibri instance that will be used. */ private final String displayName; /** * Indicates whether this session is for a SIP Jibri (<tt>true</tt>) or for * regular Jibri (<tt>false</tt>). */ private final boolean isSIP; /** * {@link JibriDetector} instance used to select a Jibri which will be used * by this session. */ private final JibriDetector jibriDetector; /** * Helper class that registers for {@link JibriEvent}s in the OSGi context * obtained from the {@link FocusBundleActivator}. */ private final JibriEventHandler jibriEventHandler = new JibriEventHandler(); /** * Current Jibri recording status. */ private JibriIq.Status jibriStatus = JibriIq.Status.UNDEFINED; /** * The logger for this instance. Uses the logging level either of the * {@link #classLogger} or {@link JitsiMeetConference#getLogger()} * whichever is higher. */ private final Logger logger; /** * The owner which will be notified about status changes of this session. */ private final Owner owner; /** * Reference to scheduled {@link PendingStatusTimeout} */ private ScheduledFuture<?> pendingTimeoutTask; /** * How long this session can stay in "pending" status, before retry is made * (given in seconds). */ private final long pendingTimeout; /** * The (bare) JID of the MUC room. */ private final EntityBareJid roomName; /** * Executor service for used to schedule pending timeout tasks. */ private final ScheduledExecutorService scheduledExecutor; /** * The SIP address attribute received from Jitsi Meet which is to be used to * start a SIP call. This field's used only if {@link #isSIP} is set to * <tt>true</tt>. */ private final String sipAddress; /** * The id of the live stream received from Jitsi Meet, which will be used to * start live streaming session (used only if {@link #isSIP is set to * <tt>true</tt>}. */ private final String streamID; private final String sessionId; /** * The broadcast id of the YouTube broadcast, if available. This is used * to generate and distribute the viewing url of the live stream */ private final String youTubeBroadcastId; /** * A JSON-encoded string containing arbitrary application data for Jibri */ private final String applicationData; /** * {@link XmppConnection} instance used to send/listen for XMPP packets. */ private final XmppConnection xmpp; /** * The maximum amount of retries we'll attempt */ private final int maxNumRetries; /** * How many times we've retried this request to another Jibri */ private int numRetries = 0; /** * Creates new {@link JibriSession} instance. * @param owner the session owner which will be notified about this session * state changes. * @param roomName the name if the XMPP MUC room (full address). * @param pendingTimeout how many seconds this session can wait in pending * state, before trying another Jibri instance or failing with an error. * @param connection the XMPP connection which will be used to send/listen * for packets. * @param scheduledExecutor the executor service which will be used to * schedule pending timeout task execution. * @param jibriDetector the Jibri detector which will be used to select * Jibri instance. * @param isSIP <tt>true</tt> if it's a SIP session or <tt>false</tt> for * a regular live streaming Jibri type of session. * @param sipAddress a SIP address if it's a SIP session * @param displayName a display name to be used by Jibri participant * entering the conference once the session starts. * @param streamID a live streaming ID if it's not a SIP session * @param youTubeBroadcastId the YouTube broadcast id (optional) * @param applicationData a JSON-encoded string containing application-specific * data for Jibri * @param logLevelDelegate logging level delegate which will be used to * select logging level for this instance {@link #logger}. */ JibriSession( JibriSession.Owner owner, EntityBareJid roomName, long pendingTimeout, int maxNumRetries, XmppConnection connection, ScheduledExecutorService scheduledExecutor, JibriDetector jibriDetector, boolean isSIP, String sipAddress, String displayName, String streamID, String youTubeBroadcastId, String sessionId, String applicationData, Logger logLevelDelegate) { this.owner = owner; this.roomName = roomName; this.scheduledExecutor = Objects.requireNonNull(scheduledExecutor, "scheduledExecutor"); this.pendingTimeout = pendingTimeout; this.maxNumRetries = maxNumRetries; this.isSIP = isSIP; this.jibriDetector = jibriDetector; this.sipAddress = sipAddress; this.displayName = displayName; this.streamID = streamID; this.youTubeBroadcastId = youTubeBroadcastId; this.sessionId = sessionId; this.applicationData = applicationData; this.xmpp = connection; logger = Logger.getLogger(classLogger, logLevelDelegate); } /** * Starts this session. A new Jibri instance will be selected and start * request will be sent (in non blocking mode). * @return true if the start is successful, false otherwise */ synchronized public boolean start() { final Jid jibriJid = jibriDetector.selectJibri(); if (jibriJid != null) { try { jibriEventHandler.start(FocusBundleActivator.bundleContext); sendJibriStartIq(jibriJid); logger.info("Starting session with Jibri " + jibriJid); return true; } catch (Exception e) { logger.error("Failed to start Jibri event handler: " + e, e); } } else { logger.error("Unable to find an available Jibri, can't start"); } return false; } /** * Stops this session if it's not already stopped. */ synchronized public void stop() { if (currentJibriJid == null) { return; } JibriIq stopRequest = new JibriIq(); stopRequest.setType(IQ.Type.set); stopRequest.setTo(currentJibriJid); stopRequest.setAction(JibriIq.Action.STOP); logger.info("Trying to stop: " + stopRequest.toXML()); // When we<SUF> // a response to this message) so clean up the session // in the processing of the response. try { xmpp.sendIqWithResponseCallback( stopRequest, stanza -> { JibriIq resp = (JibriIq)stanza; handleJibriStatusUpdate(resp.getFrom(), resp.getStatus(), resp.getFailureReason()); }, exception -> { logger.error("Error sending stop iq: " + exception.toString()); }, 60000); } catch (SmackException.NotConnectedException | InterruptedException e) { logger.error("Error sending stop iq: " + e.toString()); } } private void cleanupSession() { logger.info("Cleaning up current JibriSession"); currentJibriJid = null; numRetries = 0; try { jibriEventHandler.stop(FocusBundleActivator.bundleContext); } catch (Exception e) { logger.error("Failed to stop Jibri event handler: " + e, e); } } /** * Accept only XMPP packets which are coming from the Jibri currently used * by this session. * {@inheritDoc} */ public boolean accept(JibriIq packet) { return currentJibriJid != null && (packet.getFrom().equals(currentJibriJid)); } /** * @return a string describing this session instance, used for logging * purpose */ private String nickname() { return this.isSIP ? "SIP Jibri" : "Jibri"; } IQ processJibriIqFromJibri(JibriIq iq) { // We have something from Jibri - let's update recording status JibriIq.Status status = iq.getStatus(); if (!JibriIq.Status.UNDEFINED.equals(status)) { logger.info( "Updating status from JIBRI: " + iq.toXML() + " for " + roomName); handleJibriStatusUpdate(iq.getFrom(), status, iq.getFailureReason()); } else { logger.error("Received UNDEFINED status from jibri: " + iq.toString()); } return IQ.createResultIQ(iq); } /** * Gets the recording mode of this jibri session * @return the recording mode for this session (STREAM, FILE or UNDEFINED * in the case that this isn't a recording session but actually a SIP * session) */ JibriIq.RecordingMode getRecordingMode() { if (sipAddress != null) { return RecordingMode.UNDEFINED; } else if (streamID != null) { return RecordingMode.STREAM; } return RecordingMode.FILE; } /** * Sends an IQ to the given Jibri instance and asks it to start * recording/SIP call. */ private void sendJibriStartIq(final Jid jibriJid) { // Store Jibri JID to make the packet filter accept the response currentJibriJid = jibriJid; logger.info( "Starting Jibri " + jibriJid + (isSIP ? ("for SIP address: " + sipAddress) : (" for stream ID: " + streamID)) + " in room: " + roomName); final JibriIq startIq = new JibriIq(); startIq.setTo(jibriJid); startIq.setType(IQ.Type.set); startIq.setAction(JibriIq.Action.START); startIq.setSessionId(this.sessionId); logger.debug("Passing on jibri application data: " + this.applicationData); startIq.setAppData(this.applicationData); if (streamID != null) { startIq.setStreamId(streamID); startIq.setRecordingMode(RecordingMode.STREAM); if (youTubeBroadcastId != null) { startIq.setYouTubeBroadcastId(youTubeBroadcastId); } } else { startIq.setRecordingMode(RecordingMode.FILE); } startIq.setSipAddress(sipAddress); startIq.setDisplayName(displayName); // Insert name of the room into Jibri START IQ startIq.setRoom(roomName); // We will not wait forever for the Jibri to start. This method can be // run multiple times on retry, so we want to restart the pending // timeout each time. reschedulePendingTimeout(); try { JibriIq result = (JibriIq)xmpp.sendPacketAndGetReply(startIq); handleJibriStatusUpdate(result.getFrom(), result.getStatus(), result.getFailureReason()); } catch (OperationFailedException e) { logger.error("Error sending Jibri start IQ: " + e.toString()); } } /** * Method schedules/reschedules {@link PendingStatusTimeout} which will * clear recording state after * {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()}. */ private void reschedulePendingTimeout() { if (pendingTimeoutTask != null) { logger.info( "Rescheduling pending timeout task for room: " + roomName); pendingTimeoutTask.cancel(false); } if (pendingTimeout > 0) { pendingTimeoutTask = scheduledExecutor.schedule( new PendingStatusTimeout(), pendingTimeout, TimeUnit.SECONDS); } } /** * Check whether or not we should retry the current request to another Jibri * @return true if we should retry again, false otherwise */ private boolean shouldRetryRequest() { return (maxNumRetries < 0 || numRetries < maxNumRetries); } /** * Retry the current request with another Jibri (if one is available) * @return true if we were able to find another Jibri to retry the request with, * false otherwise */ private boolean retryRequestWithAnotherJibri() { numRetries++; return start(); } /** * Handle a Jibri status update (this could come from an IQ response, a new IQ from Jibri, an XMPP event, etc.). * This will handle: * 1) Retrying with a new Jibri in case of an error * 2) Cleaning up the session when the Jibri session finished successfully (or there was an error but we * have no more Jibris left to try) * @param jibriJid the jid of the jibri for which this status update applies * @param newStatus the jibri's new status * @param failureReason the jibri's failure reason, if any (otherwise null) */ private void handleJibriStatusUpdate( @NotNull Jid jibriJid, JibriIq.Status newStatus, @Nullable JibriIq.FailureReason failureReason) { jibriStatus = newStatus; logger.info("Got Jibri status update: Jibri " + jibriJid + " has status " + newStatus + " and failure reason " + failureReason + ", current Jibri jid is " + currentJibriJid); if (currentJibriJid == null) { logger.info("Current session has already been cleaned up, ignoring"); return; } if (jibriJid.compareTo(currentJibriJid) != 0) { logger.info("This status update is from " + jibriJid + " but the current Jibri is " + currentJibriJid + ", ignoring"); return; } // First: if we're no longer pending (regardless of the Jibri's new state), make sure we stop // the pending timeout task if (pendingTimeoutTask != null && !Status.PENDING.equals(newStatus)) { logger.info("Jibri is no longer pending, cancelling pending timeout task"); pendingTimeoutTask.cancel(false); pendingTimeoutTask = null; } // Now, if there was a failure of any kind we'll try and find another Jibri to keep things going if (failureReason != null) { // There was an error with the current Jibri, see if we should retry if (shouldRetryRequest()) { logger.info("Jibri failed, trying to fall back to another Jibri"); if (retryRequestWithAnotherJibri()) { // The fallback to another Jibri succeeded. logger.info("Successfully resumed session with another Jibri"); } else { logger.info("Failed to fall back to another Jibri, this session has now failed"); // Propagate up that the session has failed entirely. We'll pass the original failure reason. owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } } else { // The Jibri we tried failed and we've reached the maxmium amount of retries we've been // configured to attempt, so we'll give up trying to handle this request. logger.info("Jibri failed, but max amount of retries (" + maxNumRetries + ") reached, giving up"); owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } } else if (Status.OFF.equals(newStatus)) { logger.info("Jibri session ended cleanly, notifying owner and cleaning up session"); // The Jibri stopped for some non-error reason owner.onSessionStateChanged(this, newStatus, failureReason); cleanupSession(); } else if (Status.ON.equals(newStatus)) { logger.info("Jibri session started, notifying owner"); // The Jibri stopped for some non-error reason owner.onSessionStateChanged(this, newStatus, failureReason); } } /** * @return SIP address received from Jitsi Meet, which is used for SIP * gateway session (makes sense only for SIP sessions). */ String getSipAddress() { return sipAddress; } /** * Get the unique ID for this session. This is used to uniquely * identify a Jibri session instance, even of the same type (meaning, * for example, that two file recordings would have different session * IDs). It will be passed to Jibri and Jibri will put the session ID * in its presence, so the Jibri user for a particular session can * be identified by the clients. * @return the session ID */ public String getSessionId() { return this.sessionId; } /** * Helper class handles registration for the {@link JibriEvent}s. */ private class JibriEventHandler extends EventHandlerActivator { private JibriEventHandler() { super(new String[]{ JibriEvent.STATUS_CHANGED, JibriEvent.WENT_OFFLINE}); } @Override public void handleEvent(Event event) { if (!JibriEvent.isJibriEvent(event)) { logger.error("Invalid event: " + event); return; } final JibriEvent jibriEvent = (JibriEvent) event; final String topic = jibriEvent.getTopic(); final Jid jibriJid = jibriEvent.getJibriJid(); synchronized (JibriSession.this) { if (JibriEvent.WENT_OFFLINE.equals(topic) && jibriJid.equals(currentJibriJid)) { logger.error( nickname() + " went offline: " + jibriJid + " for room: " + roomName); handleJibriStatusUpdate(jibriJid, Status.OFF, FailureReason.ERROR); } } } } /** * Task scheduled after we have received RESULT response from Jibri and * entered PENDING state. Will abort the recording if we do not transit to * ON state, after {@link JitsiMeetGlobalConfig#getJibriPendingTimeout()} * limit is exceeded. */ private class PendingStatusTimeout implements Runnable { public void run() { synchronized (JibriSession.this) { // Clear this task reference, so it won't be // cancelling itself on status change from PENDING pendingTimeoutTask = null; if (isStartingStatus(jibriStatus)) { logger.error( nickname() + " pending timeout! " + roomName); // If a Jibri times out during the pending phase, it's likely hung or having // some issue. We'll send a stop (so if/when it does 'recover', it knows to // stop) and simulate an error status (like we do in JibriEventHandler#handleEvent // when a Jibri goes offline) to trigger the fallback logic. stop(); handleJibriStatusUpdate(currentJibriJid, Status.OFF, FailureReason.ERROR); } } } } /** * Interface instance passed to {@link JibriSession} constructor which * specifies the session owner which will be notified about any status * changes. */ public interface Owner { /** * Called on {@link JibriSession} status update. * @param jibriSession which status has changed * @param newStatus the new status * @param failureReason optional error for {@link JibriIq.Status#OFF}. */ void onSessionStateChanged( JibriSession jibriSession, JibriIq.Status newStatus, JibriIq.FailureReason failureReason); } }
208294_6
/** Copyright 2015 Fabian Bock, Fabian Bruckner, Christine Dahn, Amin Nirazi, Matthäus Poloczek, Kai Sauerwald, Michael Schultz, Shabnam Tabatabaian, Tim Tegeler und Marvin Wepner This file is part of pg-infoscreen. pg-infoscreen 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. pg-infoscreen 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 pg-infoscreen. If not, see <http://www.gnu.org/licenses/>. */ package controllers.lib; // Import java classes import java.net.InetAddress; import java.util.TimeZone; import play.libs.F; import play.libs.ws.WS; import play.libs.ws.WSResponse; // Import play classes import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class Localization { //Standard Zeitzone private static TimeZone timezone = TimeZone.getTimeZone("Europe/Berlin"); public static TimeZone locate(String ip){ String timezoneId; try { //InetAddress-Objekt mit Hilfe der ip erstellen InetAddress inet = InetAddress.getByName(ip); //Prüfen ob die InetAddresse eine lokale Adresse ist if (!(inet.isAnyLocalAddress() || inet.isLoopbackAddress())) { //Localization-Abfrage an API F.Promise<JsonNode> jsonPromise = WS.url("http://www.telize.com/geoip/" + ip).get().map( new F.Function<WSResponse, JsonNode>() { public JsonNode apply(WSResponse response) { return response.asJson(); } } ); // Convert jsonPromise to Object ObjectMapper mapper = new ObjectMapper(); JsonNode actualObj = mapper.readTree(jsonPromise.get(5000).toString()); timezoneId = actualObj.get("timezone").asText(); Localization.setTimezoneFromId(timezoneId); } } catch (Exception e) { } return Localization.getTimezone(); } public static TimeZone getTimezone(){ return Localization.timezone; } public static TimeZone setTimezoneFromId(String timezoneId){ Localization.timezone = TimeZone.getTimeZone(timezoneId); return Localization.getTimezone(); } }
pg-infoscreen/infoscreen-server
app/controllers/lib/Localization.java
775
//www.telize.com/geoip/" + ip).get().map(
line_comment
nl
/** Copyright 2015 Fabian Bock, Fabian Bruckner, Christine Dahn, Amin Nirazi, Matthäus Poloczek, Kai Sauerwald, Michael Schultz, Shabnam Tabatabaian, Tim Tegeler und Marvin Wepner This file is part of pg-infoscreen. pg-infoscreen 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. pg-infoscreen 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 pg-infoscreen. If not, see <http://www.gnu.org/licenses/>. */ package controllers.lib; // Import java classes import java.net.InetAddress; import java.util.TimeZone; import play.libs.F; import play.libs.ws.WS; import play.libs.ws.WSResponse; // Import play classes import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class Localization { //Standard Zeitzone private static TimeZone timezone = TimeZone.getTimeZone("Europe/Berlin"); public static TimeZone locate(String ip){ String timezoneId; try { //InetAddress-Objekt mit Hilfe der ip erstellen InetAddress inet = InetAddress.getByName(ip); //Prüfen ob die InetAddresse eine lokale Adresse ist if (!(inet.isAnyLocalAddress() || inet.isLoopbackAddress())) { //Localization-Abfrage an API F.Promise<JsonNode> jsonPromise = WS.url("http://www.telize.com/geoip/" +<SUF> new F.Function<WSResponse, JsonNode>() { public JsonNode apply(WSResponse response) { return response.asJson(); } } ); // Convert jsonPromise to Object ObjectMapper mapper = new ObjectMapper(); JsonNode actualObj = mapper.readTree(jsonPromise.get(5000).toString()); timezoneId = actualObj.get("timezone").asText(); Localization.setTimezoneFromId(timezoneId); } } catch (Exception e) { } return Localization.getTimezone(); } public static TimeZone getTimezone(){ return Localization.timezone; } public static TimeZone setTimezoneFromId(String timezoneId){ Localization.timezone = TimeZone.getTimeZone(timezoneId); return Localization.getTimezone(); } }
43049_18
/* * MegaMek - * Copyright (C) 2007 Ben Mazur ([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. */ package megamek.client.bot; import megamek.client.bot.princess.*; import megamek.codeUtilities.StringUtility; import megamek.common.Coords; import megamek.common.Game; import megamek.common.Player; import megamek.common.event.GamePlayerChatEvent; import megamek.common.util.StringUtil; import megamek.server.Server; import megamek.server.commands.DefeatCommand; import megamek.server.commands.GameMasterCommand; import megamek.server.commands.JoinTeamCommand; import org.apache.logging.log4j.LogManager; import java.util.Enumeration; import java.util.StringTokenizer; import java.util.stream.Collectors; public class ChatProcessor { boolean shouldBotAcknowledgeDefeat(String message, BotClient bot) { boolean result = false; if (!StringUtility.isNullOrBlank(message) && (message.contains("declares individual victory at the end of the turn.") || message.contains("declares team victory at the end of the turn."))) { String[] splitMessage = message.split(" "); int i = 1; String name = splitMessage[i]; while (!splitMessage[i + 1].equals("declares")) { name += " " + splitMessage[i + 1]; i++; } for (Player p : bot.getGame().getPlayersList()) { if (p.getName().equals(name)) { if (p.isEnemyOf(bot.getLocalPlayer())) { bot.sendChat("/defeat"); result = true; } break; } } } return result; } boolean shouldBotAcknowledgeVictory(String message, BotClient bot) { boolean result = false; if (!StringUtility.isNullOrBlank(message) && message.contains(DefeatCommand.wantsDefeat)) { String[] splitMessage = message.split(" "); int i = 1; String name = splitMessage[i]; while (!splitMessage[i + 1].equals("wants") && !splitMessage[i + 1].equals("admits")) { name += " " + splitMessage[i + 1]; i++; } for (Player p : bot.getGame().getPlayersVector()) { if (p.getName().equals(name)) { if (p.isEnemyOf(bot.getLocalPlayer())) { bot.sendChat("/victory"); result = true; } break; } } } return result; } public void processChat(GamePlayerChatEvent ge, BotClient bot) { if (bot.getLocalPlayer() == null) { return; } String message = ge.getMessage(); if (shouldBotAcknowledgeDefeat(message, bot)) { return; } if (shouldBotAcknowledgeVictory(message, bot)) { return; } // Check for end of message. StringTokenizer st = new StringTokenizer(ge.getMessage(), ":"); if (!st.hasMoreTokens()) { return; } String name = st.nextToken().trim(); // who is the message from? Enumeration<Player> e = bot.getGame().getPlayers(); Player p = null; while (e.hasMoreElements()) { p = e.nextElement(); if (name.equalsIgnoreCase(p.getName())) { break; } } if (name.equals(Server.ORIGIN)) { String msg = st.nextToken(); if (msg.contains(JoinTeamCommand.SERVER_VOTE_PROMPT_MSG)) { bot.sendChat("/allowTeamChange"); } else if (msg.contains(GameMasterCommand.SERVER_VOTE_PROMPT_MSG)) { bot.sendChat("/allowGM"); } return; } else if (p == null) { return; } additionalPrincessCommands(ge, (Princess) bot); } private Player getPlayer(Game game, String playerName) { Enumeration<Player> players = game.getPlayers(); while (players.hasMoreElements()) { Player testPlayer = players.nextElement(); if (playerName.equalsIgnoreCase(testPlayer.getName())) { return testPlayer; } } return null; } void additionalPrincessCommands(GamePlayerChatEvent chatEvent, Princess princess) { // Commands should be sent in this format: // <botName>: <command> : <arguments> StringTokenizer tokenizer = new StringTokenizer(chatEvent.getMessage(), ":"); if (tokenizer.countTokens() < 3) { return; } String msg = "Received message: \"" + chatEvent.getMessage() + "\".\tMessage Type: " + chatEvent.getEventName(); LogManager.getLogger().info(msg); // First token should be who sent the message. String from = tokenizer.nextToken().trim(); // Second token should be the player name the message is directed to. String sentTo = tokenizer.nextToken().trim(); Player princessPlayer = princess.getLocalPlayer(); if (princessPlayer == null) { LogManager.getLogger().error("Princess Player is NULL."); return; } String princessName = princessPlayer.getName(); // Make sure the command is directed at the Princess player. if (!princessName.equalsIgnoreCase(sentTo)) { return; } // The third token should be the actual command. String command = tokenizer.nextToken().trim(); if (command.length() < 2) { princess.sendChat("I do not recognize that command."); } // Any remaining tokens should be the command arguments. String[] arguments = null; if (tokenizer.hasMoreElements()) { arguments = tokenizer.nextToken().trim().split(" "); } // Make sure the speaker is a real player. Player speakerPlayer = chatEvent.getPlayer(); if (speakerPlayer == null) { speakerPlayer = getPlayer(princess.getGame(), from); if (speakerPlayer == null) { LogManager.getLogger().error("speakerPlayer is NULL."); return; } } // Tell me what behavior you are using. if (command.toLowerCase().startsWith(ChatCommands.SHOW_BEHAVIOR.getAbbreviation())) { msg = "Current Behavior: " + princess.getBehaviorSettings().toLog(); princess.sendChat(msg); LogManager.getLogger().info(msg); } // List the available commands. if (command.toLowerCase().startsWith(ChatCommands.LIST__COMMANDS.getAbbreviation())) { StringBuilder out = new StringBuilder("Princess Chat Commands"); for (ChatCommands cmd : ChatCommands.values()) { out.append("\n").append(cmd.getSyntax()).append(" :: ").append(cmd.getDescription()); } princess.sendChat(out.toString()); } if (command.toLowerCase().startsWith(ChatCommands.IGNORE_TARGET.getAbbreviation())) { if ((arguments == null) || (arguments.length == 0)) { msg = "Please specify entity ID to ignore."; princess.sendChat(msg); return; } Integer targetID = null; try { targetID = Integer.parseInt(arguments[0]); } catch (Exception ignored) { } if (targetID == null) { msg = "Please specify entity ID as an integer to ignore."; princess.sendChat(msg); return; } princess.getBehaviorSettings().addIgnoredUnitTarget(targetID); msg = "Ignoring target with ID " + targetID; princess.sendChat(msg); return; } // Make sure the command came from my team. int speakerTeam = speakerPlayer.getTeam(); int princessTeam = princessPlayer.getTeam(); if ((princessTeam != speakerTeam) && !speakerPlayer.getGameMaster()) { msg = "You are not my boss. [wrong team]"; princess.sendChat(msg); LogManager.getLogger().warn(msg); return; } // If instructed to, flee. if (command.toLowerCase().startsWith(ChatCommands.FLEE.getAbbreviation())) { if ((arguments == null) || (arguments.length == 0)) { msg = "Please specify retreat edge."; princess.sendChat(msg); return; } CardinalEdge edge = null; try { int edgeIndex = Integer.parseInt(arguments[0]); edge = CardinalEdge.getCardinalEdge(edgeIndex); } catch (Exception ignored) { } if (edge == null) { msg = "Please specify valid retreat edge, a number between 0 and 4 inclusive."; princess.sendChat(msg); return; } msg = "Received flee order - " + edge; LogManager.getLogger().debug(msg); princess.sendChat(msg); princess.getBehaviorSettings().setDestinationEdge(edge); princess.setFallBack(true, msg); return; } // Load a new behavior. if (command.toLowerCase().startsWith(ChatCommands.BEHAVIOR.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "No new behavior specified."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String behaviorName = arguments[0].trim(); BehaviorSettings newBehavior = BehaviorSettingsFactory.getInstance().getBehavior(behaviorName); if (newBehavior == null) { msg = "Behavior '" + behaviorName + "' does not exist."; LogManager.getLogger().warn(msg); princess.sendChat(msg); return; } princess.setBehaviorSettings(newBehavior); msg = "Behavior changed to " + princess.getBehaviorSettings().getDescription(); princess.sendChat(msg); return; } // Adjust fall shame. if (command.toLowerCase().startsWith(ChatCommands.CAUTION.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid Syntax. Should be 'princessName : caution : <+/->'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String adjustment = arguments[0]; int currentFallShame = princess.getBehaviorSettings().getFallShameIndex(); int newFallShame = currentFallShame; newFallShame += princess.calculateAdjustment(adjustment); princess.getBehaviorSettings().setFallShameIndex(newFallShame); msg = "Piloting Caution changed from " + currentFallShame + " to " + princess.getBehaviorSettings().getFallShameIndex(); princess.sendChat(msg); } // Adjust self preservation. if (command.toLowerCase().startsWith(ChatCommands.AVOID.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid Syntax. Should be 'princessName : avoid : <+/->'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String adjustment = arguments[0]; int currentSelfPreservation = princess.getBehaviorSettings().getSelfPreservationIndex(); int newSelfPreservation = currentSelfPreservation; newSelfPreservation += princess.calculateAdjustment(adjustment); princess.getBehaviorSettings().setSelfPreservationIndex(newSelfPreservation); msg = "Self Preservation changed from " + currentSelfPreservation + " to " + princess.getBehaviorSettings().getSelfPreservationIndex(); princess.sendChat(msg); } // Adjust aggression. if (command.toLowerCase().startsWith(ChatCommands.AGGRESSION.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid Syntax. Should be 'princessName : aggression : <+/->'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String adjustment = arguments[0]; int currentAggression = princess.getBehaviorSettings().getHyperAggressionIndex(); int newAggression = currentAggression; newAggression += princess.calculateAdjustment(adjustment); princess.getBehaviorSettings().setHyperAggressionIndex(newAggression); msg = "Aggression changed from " + currentAggression + " to " + princess.getBehaviorSettings().getHyperAggressionIndex(); princess.sendChat(msg); princess.resetSpinupThreshold(); } // Adjust herd mentality. if (command.toLowerCase().startsWith(ChatCommands.HERDING.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid Syntax. Should be 'princessName : herding : <+/->'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String adjustment = arguments[0]; int currentHerding = princess.getBehaviorSettings().getHerdMentalityIndex(); int newHerding = currentHerding; newHerding += princess.calculateAdjustment(adjustment); princess.getBehaviorSettings().setHerdMentalityIndex(newHerding); msg = "Herding changed from " + currentHerding + " to " + princess.getBehaviorSettings().getHerdMentalityIndex(); princess.sendChat(msg); } // Adjust bravery. if (command.toLowerCase().startsWith(ChatCommands.BRAVERY.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid Syntax. Should be 'princessName : brave : <+/->'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String adjustment = arguments[0]; int currentBravery = princess.getBehaviorSettings().getBraveryIndex(); int newBravery = currentBravery; newBravery += princess.calculateAdjustment(adjustment); princess.getBehaviorSettings().setBraveryIndex(newBravery); msg = "Bravery changed from " + currentBravery + " to " + princess.getBehaviorSettings().getBraveryIndex(); princess.sendChat(msg); } // Specify a "strategic" building target. if (command.toLowerCase().startsWith(ChatCommands.TARGET.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid syntax. Should be 'princessName : target : hexNumber'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String hex = arguments[0]; if (hex.length() != 4 || !StringUtil.isPositiveInteger(hex)) { msg = "Invalid hex number: " + hex; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } int x = Integer.parseInt(hex.substring(0, 2)) - 1; int y = Integer.parseInt(hex.substring(2, 4)) - 1; Coords coords = new Coords(x, y); if (!princess.getGame().getBoard().contains(coords)) { msg = "Board does not have hex " + hex; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } princess.addStrategicBuildingTarget(coords); msg = "Hex " + hex + " added to strategic targets list."; princess.sendChat(msg); } // Specify a priority unit target. if (command.toLowerCase().startsWith(ChatCommands.PRIORITIZE.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid syntax. Should be 'princessName : priority : unitId'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String id = arguments[0]; if (!StringUtil.isPositiveInteger(id)) { msg = "Invalid unit id number: " + id; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } princess.getBehaviorSettings().addPriorityUnit(id); msg = "Unit " + id + " added to priority unit targets list."; princess.sendChat(msg); } // Specify a priority unit target. if (command.toLowerCase().startsWith(ChatCommands.SHOW_DISHONORED.getAbbreviation())) { msg = "Dishonored Player ids: " + princess.getHonorUtil().getDishonoredEnemies().stream().map(Object::toString).collect(Collectors.joining(", ")); princess.sendChat(msg); LogManager.getLogger().info(msg); } } }
pheonixstorm/megamek
megamek/src/megamek/client/bot/ChatProcessor.java
4,985
// Adjust herd mentality.
line_comment
nl
/* * MegaMek - * Copyright (C) 2007 Ben Mazur ([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. */ package megamek.client.bot; import megamek.client.bot.princess.*; import megamek.codeUtilities.StringUtility; import megamek.common.Coords; import megamek.common.Game; import megamek.common.Player; import megamek.common.event.GamePlayerChatEvent; import megamek.common.util.StringUtil; import megamek.server.Server; import megamek.server.commands.DefeatCommand; import megamek.server.commands.GameMasterCommand; import megamek.server.commands.JoinTeamCommand; import org.apache.logging.log4j.LogManager; import java.util.Enumeration; import java.util.StringTokenizer; import java.util.stream.Collectors; public class ChatProcessor { boolean shouldBotAcknowledgeDefeat(String message, BotClient bot) { boolean result = false; if (!StringUtility.isNullOrBlank(message) && (message.contains("declares individual victory at the end of the turn.") || message.contains("declares team victory at the end of the turn."))) { String[] splitMessage = message.split(" "); int i = 1; String name = splitMessage[i]; while (!splitMessage[i + 1].equals("declares")) { name += " " + splitMessage[i + 1]; i++; } for (Player p : bot.getGame().getPlayersList()) { if (p.getName().equals(name)) { if (p.isEnemyOf(bot.getLocalPlayer())) { bot.sendChat("/defeat"); result = true; } break; } } } return result; } boolean shouldBotAcknowledgeVictory(String message, BotClient bot) { boolean result = false; if (!StringUtility.isNullOrBlank(message) && message.contains(DefeatCommand.wantsDefeat)) { String[] splitMessage = message.split(" "); int i = 1; String name = splitMessage[i]; while (!splitMessage[i + 1].equals("wants") && !splitMessage[i + 1].equals("admits")) { name += " " + splitMessage[i + 1]; i++; } for (Player p : bot.getGame().getPlayersVector()) { if (p.getName().equals(name)) { if (p.isEnemyOf(bot.getLocalPlayer())) { bot.sendChat("/victory"); result = true; } break; } } } return result; } public void processChat(GamePlayerChatEvent ge, BotClient bot) { if (bot.getLocalPlayer() == null) { return; } String message = ge.getMessage(); if (shouldBotAcknowledgeDefeat(message, bot)) { return; } if (shouldBotAcknowledgeVictory(message, bot)) { return; } // Check for end of message. StringTokenizer st = new StringTokenizer(ge.getMessage(), ":"); if (!st.hasMoreTokens()) { return; } String name = st.nextToken().trim(); // who is the message from? Enumeration<Player> e = bot.getGame().getPlayers(); Player p = null; while (e.hasMoreElements()) { p = e.nextElement(); if (name.equalsIgnoreCase(p.getName())) { break; } } if (name.equals(Server.ORIGIN)) { String msg = st.nextToken(); if (msg.contains(JoinTeamCommand.SERVER_VOTE_PROMPT_MSG)) { bot.sendChat("/allowTeamChange"); } else if (msg.contains(GameMasterCommand.SERVER_VOTE_PROMPT_MSG)) { bot.sendChat("/allowGM"); } return; } else if (p == null) { return; } additionalPrincessCommands(ge, (Princess) bot); } private Player getPlayer(Game game, String playerName) { Enumeration<Player> players = game.getPlayers(); while (players.hasMoreElements()) { Player testPlayer = players.nextElement(); if (playerName.equalsIgnoreCase(testPlayer.getName())) { return testPlayer; } } return null; } void additionalPrincessCommands(GamePlayerChatEvent chatEvent, Princess princess) { // Commands should be sent in this format: // <botName>: <command> : <arguments> StringTokenizer tokenizer = new StringTokenizer(chatEvent.getMessage(), ":"); if (tokenizer.countTokens() < 3) { return; } String msg = "Received message: \"" + chatEvent.getMessage() + "\".\tMessage Type: " + chatEvent.getEventName(); LogManager.getLogger().info(msg); // First token should be who sent the message. String from = tokenizer.nextToken().trim(); // Second token should be the player name the message is directed to. String sentTo = tokenizer.nextToken().trim(); Player princessPlayer = princess.getLocalPlayer(); if (princessPlayer == null) { LogManager.getLogger().error("Princess Player is NULL."); return; } String princessName = princessPlayer.getName(); // Make sure the command is directed at the Princess player. if (!princessName.equalsIgnoreCase(sentTo)) { return; } // The third token should be the actual command. String command = tokenizer.nextToken().trim(); if (command.length() < 2) { princess.sendChat("I do not recognize that command."); } // Any remaining tokens should be the command arguments. String[] arguments = null; if (tokenizer.hasMoreElements()) { arguments = tokenizer.nextToken().trim().split(" "); } // Make sure the speaker is a real player. Player speakerPlayer = chatEvent.getPlayer(); if (speakerPlayer == null) { speakerPlayer = getPlayer(princess.getGame(), from); if (speakerPlayer == null) { LogManager.getLogger().error("speakerPlayer is NULL."); return; } } // Tell me what behavior you are using. if (command.toLowerCase().startsWith(ChatCommands.SHOW_BEHAVIOR.getAbbreviation())) { msg = "Current Behavior: " + princess.getBehaviorSettings().toLog(); princess.sendChat(msg); LogManager.getLogger().info(msg); } // List the available commands. if (command.toLowerCase().startsWith(ChatCommands.LIST__COMMANDS.getAbbreviation())) { StringBuilder out = new StringBuilder("Princess Chat Commands"); for (ChatCommands cmd : ChatCommands.values()) { out.append("\n").append(cmd.getSyntax()).append(" :: ").append(cmd.getDescription()); } princess.sendChat(out.toString()); } if (command.toLowerCase().startsWith(ChatCommands.IGNORE_TARGET.getAbbreviation())) { if ((arguments == null) || (arguments.length == 0)) { msg = "Please specify entity ID to ignore."; princess.sendChat(msg); return; } Integer targetID = null; try { targetID = Integer.parseInt(arguments[0]); } catch (Exception ignored) { } if (targetID == null) { msg = "Please specify entity ID as an integer to ignore."; princess.sendChat(msg); return; } princess.getBehaviorSettings().addIgnoredUnitTarget(targetID); msg = "Ignoring target with ID " + targetID; princess.sendChat(msg); return; } // Make sure the command came from my team. int speakerTeam = speakerPlayer.getTeam(); int princessTeam = princessPlayer.getTeam(); if ((princessTeam != speakerTeam) && !speakerPlayer.getGameMaster()) { msg = "You are not my boss. [wrong team]"; princess.sendChat(msg); LogManager.getLogger().warn(msg); return; } // If instructed to, flee. if (command.toLowerCase().startsWith(ChatCommands.FLEE.getAbbreviation())) { if ((arguments == null) || (arguments.length == 0)) { msg = "Please specify retreat edge."; princess.sendChat(msg); return; } CardinalEdge edge = null; try { int edgeIndex = Integer.parseInt(arguments[0]); edge = CardinalEdge.getCardinalEdge(edgeIndex); } catch (Exception ignored) { } if (edge == null) { msg = "Please specify valid retreat edge, a number between 0 and 4 inclusive."; princess.sendChat(msg); return; } msg = "Received flee order - " + edge; LogManager.getLogger().debug(msg); princess.sendChat(msg); princess.getBehaviorSettings().setDestinationEdge(edge); princess.setFallBack(true, msg); return; } // Load a new behavior. if (command.toLowerCase().startsWith(ChatCommands.BEHAVIOR.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "No new behavior specified."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String behaviorName = arguments[0].trim(); BehaviorSettings newBehavior = BehaviorSettingsFactory.getInstance().getBehavior(behaviorName); if (newBehavior == null) { msg = "Behavior '" + behaviorName + "' does not exist."; LogManager.getLogger().warn(msg); princess.sendChat(msg); return; } princess.setBehaviorSettings(newBehavior); msg = "Behavior changed to " + princess.getBehaviorSettings().getDescription(); princess.sendChat(msg); return; } // Adjust fall shame. if (command.toLowerCase().startsWith(ChatCommands.CAUTION.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid Syntax. Should be 'princessName : caution : <+/->'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String adjustment = arguments[0]; int currentFallShame = princess.getBehaviorSettings().getFallShameIndex(); int newFallShame = currentFallShame; newFallShame += princess.calculateAdjustment(adjustment); princess.getBehaviorSettings().setFallShameIndex(newFallShame); msg = "Piloting Caution changed from " + currentFallShame + " to " + princess.getBehaviorSettings().getFallShameIndex(); princess.sendChat(msg); } // Adjust self preservation. if (command.toLowerCase().startsWith(ChatCommands.AVOID.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid Syntax. Should be 'princessName : avoid : <+/->'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String adjustment = arguments[0]; int currentSelfPreservation = princess.getBehaviorSettings().getSelfPreservationIndex(); int newSelfPreservation = currentSelfPreservation; newSelfPreservation += princess.calculateAdjustment(adjustment); princess.getBehaviorSettings().setSelfPreservationIndex(newSelfPreservation); msg = "Self Preservation changed from " + currentSelfPreservation + " to " + princess.getBehaviorSettings().getSelfPreservationIndex(); princess.sendChat(msg); } // Adjust aggression. if (command.toLowerCase().startsWith(ChatCommands.AGGRESSION.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid Syntax. Should be 'princessName : aggression : <+/->'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String adjustment = arguments[0]; int currentAggression = princess.getBehaviorSettings().getHyperAggressionIndex(); int newAggression = currentAggression; newAggression += princess.calculateAdjustment(adjustment); princess.getBehaviorSettings().setHyperAggressionIndex(newAggression); msg = "Aggression changed from " + currentAggression + " to " + princess.getBehaviorSettings().getHyperAggressionIndex(); princess.sendChat(msg); princess.resetSpinupThreshold(); } // Adjust herd<SUF> if (command.toLowerCase().startsWith(ChatCommands.HERDING.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid Syntax. Should be 'princessName : herding : <+/->'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String adjustment = arguments[0]; int currentHerding = princess.getBehaviorSettings().getHerdMentalityIndex(); int newHerding = currentHerding; newHerding += princess.calculateAdjustment(adjustment); princess.getBehaviorSettings().setHerdMentalityIndex(newHerding); msg = "Herding changed from " + currentHerding + " to " + princess.getBehaviorSettings().getHerdMentalityIndex(); princess.sendChat(msg); } // Adjust bravery. if (command.toLowerCase().startsWith(ChatCommands.BRAVERY.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid Syntax. Should be 'princessName : brave : <+/->'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String adjustment = arguments[0]; int currentBravery = princess.getBehaviorSettings().getBraveryIndex(); int newBravery = currentBravery; newBravery += princess.calculateAdjustment(adjustment); princess.getBehaviorSettings().setBraveryIndex(newBravery); msg = "Bravery changed from " + currentBravery + " to " + princess.getBehaviorSettings().getBraveryIndex(); princess.sendChat(msg); } // Specify a "strategic" building target. if (command.toLowerCase().startsWith(ChatCommands.TARGET.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid syntax. Should be 'princessName : target : hexNumber'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String hex = arguments[0]; if (hex.length() != 4 || !StringUtil.isPositiveInteger(hex)) { msg = "Invalid hex number: " + hex; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } int x = Integer.parseInt(hex.substring(0, 2)) - 1; int y = Integer.parseInt(hex.substring(2, 4)) - 1; Coords coords = new Coords(x, y); if (!princess.getGame().getBoard().contains(coords)) { msg = "Board does not have hex " + hex; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } princess.addStrategicBuildingTarget(coords); msg = "Hex " + hex + " added to strategic targets list."; princess.sendChat(msg); } // Specify a priority unit target. if (command.toLowerCase().startsWith(ChatCommands.PRIORITIZE.getAbbreviation())) { if (arguments == null || arguments.length == 0) { msg = "Invalid syntax. Should be 'princessName : priority : unitId'."; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } String id = arguments[0]; if (!StringUtil.isPositiveInteger(id)) { msg = "Invalid unit id number: " + id; LogManager.getLogger().warn(msg + "\n" + chatEvent.getMessage()); princess.sendChat(msg); return; } princess.getBehaviorSettings().addPriorityUnit(id); msg = "Unit " + id + " added to priority unit targets list."; princess.sendChat(msg); } // Specify a priority unit target. if (command.toLowerCase().startsWith(ChatCommands.SHOW_DISHONORED.getAbbreviation())) { msg = "Dishonored Player ids: " + princess.getHonorUtil().getDishonoredEnemies().stream().map(Object::toString).collect(Collectors.joining(", ")); princess.sendChat(msg); LogManager.getLogger().info(msg); } } }
204960_25
/* * Copyright 2009 Phil Burk, Mobileer Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jsyn.engine; /* * Multiple tables of sawtooth data. * organized by octaves below the Nyquist Rate. * used to generate band-limited Sawtooth, Impulse, Pulse, Square and Triangle BL waveforms * <pre> Analysis of octave requirements for tables. OctavesIndex Frequency Partials 0 N/2 11025 1 1 N/4 5512 2 2 N/8 2756 4 3 N/16 1378 8 4 N/32 689 16 5 N/64 344 32 6 N/128 172 64 7 N/256 86 128 </pre> * * @author Phil Burk (C) 2009 Mobileer Inc */ public class MultiTable { public final static int NUM_TABLES = 8; public final static int CYCLE_SIZE = (1 << 10); private static MultiTable instance = new MultiTable(NUM_TABLES, CYCLE_SIZE); private double phaseScalar; private float[][] tables; // array of array of tables /************************************************************************** * Initialize sawtooth wavetables. Table[0] should contain a pure sine wave. Succeeding tables * should have increasing numbers of partials. */ public MultiTable(int numTables, int cycleSize) { int tableSize = cycleSize + 1; // Allocate array of arrays. tables = new float[numTables][tableSize]; float[] sineTable = tables[0]; phaseScalar = (float) (cycleSize * 0.5); /* Fill initial sine table with values for -PI to PI. */ for (int j = 0; j < tableSize; j++) { sineTable[j] = (float) Math.sin(((((double) j) / (double) cycleSize) * Math.PI * 2.0) - Math.PI); } /* * Build each table from scratch and scale partials by raised cosine* to eliminate Gibbs * effect. */ for (int i = 1; i < numTables; i++) { int numPartials; double kGibbs; float[] table = tables[i]; /* Add together partials for this table. */ numPartials = 1 << i; kGibbs = Math.PI / (2 * numPartials); for (int k = 0; k < numPartials; k++) { double ampl, cGibbs; int sineIndex = 0; int partial = k + 1; cGibbs = Math.cos(k * kGibbs); /* Calculate amplitude for Nth partial */ ampl = cGibbs * cGibbs / partial; for (int j = 0; j < tableSize; j++) { table[j] += (float) ampl * sineTable[sineIndex]; sineIndex += partial; /* Wrap index at end of table.. */ if (sineIndex >= cycleSize) { sineIndex -= cycleSize; } } } } /* Normalize after */ for (int i = 1; i < numTables; i++) { normalizeArray(tables[i]); } } /**************************************************************************/ public static float normalizeArray(float[] fdata) { float max, val, gain; int i; // determine maximum value. max = 0.0f; for (i = 0; i < fdata.length; i++) { val = Math.abs(fdata[i]); if (val > max) max = val; } if (max < 0.0000001f) max = 0.0000001f; // scale array gain = 1.0f / max; for (i = 0; i < fdata.length; i++) fdata[i] *= gain; return gain; } /***************************************************************************** * When the phaseInc maps to the highest level table, then we start interpolating between the * highest table and the raw sawtooth value (phase). When phaseInc points to highest table: * flevel = NUM_TABLES - 1 = -1 - log2(pInc); log2(pInc) = - NUM_TABLES pInc = 2**(-NUM_TABLES) */ private final static double LOWEST_PHASE_INC_INV = (1 << NUM_TABLES); /**************************************************************************/ /* Phase ranges from -1.0 to +1.0 */ public double calculateSawtooth(double currentPhase, double positivePhaseIncrement, double flevel) { float[] tableBase; double val; double hiSam; /* Use when verticalFraction is 1.0 */ double loSam; /* Use when verticalFraction is 0.0 */ double sam1, sam2; /* Use Phase to determine sampleIndex into table. */ double findex = ((phaseScalar * currentPhase) + phaseScalar); // findex is > 0 so we do not need to call floor(). int sampleIndex = (int) findex; double horizontalFraction = findex - sampleIndex; int tableIndex = (int) flevel; if (tableIndex > (NUM_TABLES - 2)) { /* * Just use top table and mix with arithmetic sawtooth if below lowest frequency. * Generate new fraction for interpolating between 0.0 and lowest table frequency. */ double fraction = positivePhaseIncrement * LOWEST_PHASE_INC_INV; tableBase = tables[(NUM_TABLES - 1)]; /* Get adjacent samples. Assume guard point present. */ sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent samples. */ loSam = sam1 + (horizontalFraction * (sam2 - sam1)); /* Use arithmetic version for low frequencies. */ /* fraction is 0.0 at 0 Hz */ val = currentPhase + (fraction * (loSam - currentPhase)); } else { double verticalFraction = flevel - tableIndex; if (tableIndex < 0) { if (tableIndex < -1) // above Nyquist! { val = 0.0; } else { /* * At top of supported range, interpolate between 0.0 and first partial. */ tableBase = tables[0]; /* Sine wave table. */ /* Get adjacent samples. Assume guard point present. */ sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent samples. */ hiSam = sam1 + (horizontalFraction * (sam2 - sam1)); /* loSam = 0.0 */ // verticalFraction is 0.0 at Nyquist val = verticalFraction * hiSam; } } else { /* * Interpolate between adjacent levels to prevent harmonics from popping. */ tableBase = tables[tableIndex + 1]; /* Get adjacent samples. Assume guard point present. */ sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent samples. */ hiSam = sam1 + (horizontalFraction * (sam2 - sam1)); /* Get adjacent samples. Assume guard point present. */ tableBase = tables[tableIndex]; sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent samples. */ loSam = sam1 + (horizontalFraction * (sam2 - sam1)); val = loSam + (verticalFraction * (hiSam - loSam)); } } return val; } public double convertPhaseIncrementToLevel(double positivePhaseIncrement) { if (positivePhaseIncrement < 1.0e-30) { positivePhaseIncrement = 1.0e-30; } return -1.0 - (Math.log(positivePhaseIncrement) / Math.log(2.0)); } public static MultiTable getInstance() { return instance; } }
philburk/jsyn
src/main/java/com/jsyn/engine/MultiTable.java
2,361
/* Interpolate between adjacent samples. */
block_comment
nl
/* * Copyright 2009 Phil Burk, Mobileer Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jsyn.engine; /* * Multiple tables of sawtooth data. * organized by octaves below the Nyquist Rate. * used to generate band-limited Sawtooth, Impulse, Pulse, Square and Triangle BL waveforms * <pre> Analysis of octave requirements for tables. OctavesIndex Frequency Partials 0 N/2 11025 1 1 N/4 5512 2 2 N/8 2756 4 3 N/16 1378 8 4 N/32 689 16 5 N/64 344 32 6 N/128 172 64 7 N/256 86 128 </pre> * * @author Phil Burk (C) 2009 Mobileer Inc */ public class MultiTable { public final static int NUM_TABLES = 8; public final static int CYCLE_SIZE = (1 << 10); private static MultiTable instance = new MultiTable(NUM_TABLES, CYCLE_SIZE); private double phaseScalar; private float[][] tables; // array of array of tables /************************************************************************** * Initialize sawtooth wavetables. Table[0] should contain a pure sine wave. Succeeding tables * should have increasing numbers of partials. */ public MultiTable(int numTables, int cycleSize) { int tableSize = cycleSize + 1; // Allocate array of arrays. tables = new float[numTables][tableSize]; float[] sineTable = tables[0]; phaseScalar = (float) (cycleSize * 0.5); /* Fill initial sine table with values for -PI to PI. */ for (int j = 0; j < tableSize; j++) { sineTable[j] = (float) Math.sin(((((double) j) / (double) cycleSize) * Math.PI * 2.0) - Math.PI); } /* * Build each table from scratch and scale partials by raised cosine* to eliminate Gibbs * effect. */ for (int i = 1; i < numTables; i++) { int numPartials; double kGibbs; float[] table = tables[i]; /* Add together partials for this table. */ numPartials = 1 << i; kGibbs = Math.PI / (2 * numPartials); for (int k = 0; k < numPartials; k++) { double ampl, cGibbs; int sineIndex = 0; int partial = k + 1; cGibbs = Math.cos(k * kGibbs); /* Calculate amplitude for Nth partial */ ampl = cGibbs * cGibbs / partial; for (int j = 0; j < tableSize; j++) { table[j] += (float) ampl * sineTable[sineIndex]; sineIndex += partial; /* Wrap index at end of table.. */ if (sineIndex >= cycleSize) { sineIndex -= cycleSize; } } } } /* Normalize after */ for (int i = 1; i < numTables; i++) { normalizeArray(tables[i]); } } /**************************************************************************/ public static float normalizeArray(float[] fdata) { float max, val, gain; int i; // determine maximum value. max = 0.0f; for (i = 0; i < fdata.length; i++) { val = Math.abs(fdata[i]); if (val > max) max = val; } if (max < 0.0000001f) max = 0.0000001f; // scale array gain = 1.0f / max; for (i = 0; i < fdata.length; i++) fdata[i] *= gain; return gain; } /***************************************************************************** * When the phaseInc maps to the highest level table, then we start interpolating between the * highest table and the raw sawtooth value (phase). When phaseInc points to highest table: * flevel = NUM_TABLES - 1 = -1 - log2(pInc); log2(pInc) = - NUM_TABLES pInc = 2**(-NUM_TABLES) */ private final static double LOWEST_PHASE_INC_INV = (1 << NUM_TABLES); /**************************************************************************/ /* Phase ranges from -1.0 to +1.0 */ public double calculateSawtooth(double currentPhase, double positivePhaseIncrement, double flevel) { float[] tableBase; double val; double hiSam; /* Use when verticalFraction is 1.0 */ double loSam; /* Use when verticalFraction is 0.0 */ double sam1, sam2; /* Use Phase to determine sampleIndex into table. */ double findex = ((phaseScalar * currentPhase) + phaseScalar); // findex is > 0 so we do not need to call floor(). int sampleIndex = (int) findex; double horizontalFraction = findex - sampleIndex; int tableIndex = (int) flevel; if (tableIndex > (NUM_TABLES - 2)) { /* * Just use top table and mix with arithmetic sawtooth if below lowest frequency. * Generate new fraction for interpolating between 0.0 and lowest table frequency. */ double fraction = positivePhaseIncrement * LOWEST_PHASE_INC_INV; tableBase = tables[(NUM_TABLES - 1)]; /* Get adjacent samples. Assume guard point present. */ sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent samples. */ loSam = sam1 + (horizontalFraction * (sam2 - sam1)); /* Use arithmetic version for low frequencies. */ /* fraction is 0.0 at 0 Hz */ val = currentPhase + (fraction * (loSam - currentPhase)); } else { double verticalFraction = flevel - tableIndex; if (tableIndex < 0) { if (tableIndex < -1) // above Nyquist! { val = 0.0; } else { /* * At top of supported range, interpolate between 0.0 and first partial. */ tableBase = tables[0]; /* Sine wave table. */ /* Get adjacent samples. Assume guard point present. */ sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent<SUF>*/ hiSam = sam1 + (horizontalFraction * (sam2 - sam1)); /* loSam = 0.0 */ // verticalFraction is 0.0 at Nyquist val = verticalFraction * hiSam; } } else { /* * Interpolate between adjacent levels to prevent harmonics from popping. */ tableBase = tables[tableIndex + 1]; /* Get adjacent samples. Assume guard point present. */ sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent samples. */ hiSam = sam1 + (horizontalFraction * (sam2 - sam1)); /* Get adjacent samples. Assume guard point present. */ tableBase = tables[tableIndex]; sam1 = tableBase[sampleIndex]; sam2 = tableBase[sampleIndex + 1]; /* Interpolate between adjacent samples. */ loSam = sam1 + (horizontalFraction * (sam2 - sam1)); val = loSam + (verticalFraction * (hiSam - loSam)); } } return val; } public double convertPhaseIncrementToLevel(double positivePhaseIncrement) { if (positivePhaseIncrement < 1.0e-30) { positivePhaseIncrement = 1.0e-30; } return -1.0 - (Math.log(positivePhaseIncrement) / Math.log(2.0)); } public static MultiTable getInstance() { return instance; } }
74188_2
package com.beaconapp; import android.os.StrictMode; import androidx.appcompat.app.AppCompatActivity; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.ScrollView; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; public class ScanActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener { private final static String TAG = MainActivity.class.getSimpleName(); public static final int REQUEST_ENABLE_BT = 1; private static final int PERMISSION_REQUEST_COARSE_LOCATION = 456; private HashMap<String, BLE_Device> mBTDeviceHashMap; private ArrayList<BLE_Device> mBTDeviceArrayList; private ListAdapter_BLE_Devices adapter; private ArrayList<BLE_Device> filterBleArrayList; private HashMap<String, Integer> filterRSSIHashMap; private Button btn_Scan; private Button btn_Settings; private BroadcastReceiver_BTState mBTStateUpdateReceiver; private Scanner_BLE mBLEScanner; boolean PausedOnStartUp = false; CallAPI callAPI; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan); //Check om te controleren of BLE is supported op het apparaat. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Utils.toast(getApplicationContext(), "BLE not supported"); finish(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION); } mBTStateUpdateReceiver = new BroadcastReceiver_BTState(getApplicationContext()); mBLEScanner = new Scanner_BLE(this, 7500, -75); mBTDeviceHashMap = new HashMap<>(); mBTDeviceArrayList = new ArrayList<>(); filterBleArrayList = new ArrayList<>(); filterRSSIHashMap = new HashMap<>(); adapter = new ListAdapter_BLE_Devices(this, R.layout.device_list_item, filterBleArrayList); ListView listView = new ListView(this); listView.setAdapter(adapter); listView.setOnItemClickListener(this); ((ScrollView) findViewById(R.id.scrollView)).addView(listView); btn_Scan = (Button) findViewById(R.id.btn_scan); findViewById(R.id.btn_scan).setOnClickListener(this); btn_Settings = (Button) findViewById(R.id.btn_Settings); findViewById(R.id.btn_Settings).setOnClickListener(this); callAPI = new CallAPI(getApplicationContext()); } @Override protected void onStart() { super.onStart(); registerReceiver(mBTStateUpdateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); //For some reason onPause gets called after onCreate if (!PausedOnStartUp) { PausedOnStartUp = true; startScan(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); callAPI.feedAPI(); } else { stopScan(); } } @Override protected void onStop() { super.onStop(); unregisterReceiver(mBTStateUpdateReceiver); } @Override public void onDestroy() { if (callAPI != null) { callAPI.cancel(true); } super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Controleren of we op de goeie request reageren if (requestCode == REQUEST_ENABLE_BT) { // Zeker weten dat de aanvraag succesvol was if (resultCode == RESULT_OK) { // Utils.toast(getApplicationContext(), "Thank you for turning on Bluetooth"); } else if (resultCode == RESULT_CANCELED) { Utils.toast(getApplicationContext(), "Please turn on Bluetooth"); } } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Voor later } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_scan: Utils.toast(getApplicationContext(), "Scan Button Pressed"); if (!mBLEScanner.isScanning()) { startScan(); } else { stopScan(); } break; case R.id.btn_Settings: openSettingsActivity(); break; default: break; } } public void addDevice(BluetoothDevice device, int new_rssi) { String address = device.getAddress(); if (!mBTDeviceHashMap.containsKey(address)) { BLE_Device ble_device = new BLE_Device(device); ble_device.setRSSI(new_rssi); mBTDeviceHashMap.put(address, ble_device); mBTDeviceArrayList.add(ble_device); } else { mBTDeviceHashMap.get(address).setRSSI(new_rssi); } filter3ClosestDevices(); adapter.notifyDataSetChanged(); } private void filter3ClosestDevices () { //Putting the RSSI in a different HashMap with as key the address for (String key: mBTDeviceHashMap.keySet()) { filterRSSIHashMap.put(key, mBTDeviceHashMap.get(key).getRSSI()); } //Log.d("FILTER", filterRSSIHashMap.toString()); //Check if there are even 3 devices in range int count = 3; if (filterRSSIHashMap.size() == 1) { count = 1; } else if (filterRSSIHashMap.size() == 2) { count = 2; } //Clear list filterBleArrayList.clear(); //Get 3 lowest RSSI's for (int i = 0; i < count; i++) { String key = getMinKey(filterRSSIHashMap, filterRSSIHashMap.keySet()); filterBleArrayList.add(mBTDeviceHashMap.get(key)); filterRSSIHashMap.remove(key); } //Log.d("HASHMAP", filterRSSIHashMap.toString()); //Log.d("ARRAYLIST", filterBleArrayList.toString()); callAPI.updateDevices(filterBleArrayList); filterRSSIHashMap.clear(); } public String getMinKey(HashMap<String, Integer> map, Set<String> keys) { String minKey = null; int minValue = Integer.MAX_VALUE; for(String key : keys) { int value = map.get(key); if(value < minValue) { minValue = value; minKey = key; } } return minKey; } public void clearList() { filterBleArrayList.clear(); } public void startScan() { btn_Scan.setText("Scanning..."); mBTDeviceArrayList.clear(); mBTDeviceHashMap.clear(); filterRSSIHashMap.clear(); filterBleArrayList.clear(); adapter.notifyDataSetChanged(); mBLEScanner.start(); } public void stopScan() { btn_Scan.setText("Scan Again"); mBLEScanner.stop(); } public void openSettingsActivity() { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } }
philips-labs/fontys-2020-team-guidance
Software/BeaconAndroid/BeaconApp/android/app/src/main/java/com/beaconapp/ScanActivity.java
2,293
// Controleren of we op de goeie request reageren
line_comment
nl
package com.beaconapp; import android.os.StrictMode; import androidx.appcompat.app.AppCompatActivity; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.ScrollView; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; public class ScanActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener { private final static String TAG = MainActivity.class.getSimpleName(); public static final int REQUEST_ENABLE_BT = 1; private static final int PERMISSION_REQUEST_COARSE_LOCATION = 456; private HashMap<String, BLE_Device> mBTDeviceHashMap; private ArrayList<BLE_Device> mBTDeviceArrayList; private ListAdapter_BLE_Devices adapter; private ArrayList<BLE_Device> filterBleArrayList; private HashMap<String, Integer> filterRSSIHashMap; private Button btn_Scan; private Button btn_Settings; private BroadcastReceiver_BTState mBTStateUpdateReceiver; private Scanner_BLE mBLEScanner; boolean PausedOnStartUp = false; CallAPI callAPI; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan); //Check om te controleren of BLE is supported op het apparaat. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Utils.toast(getApplicationContext(), "BLE not supported"); finish(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION); } mBTStateUpdateReceiver = new BroadcastReceiver_BTState(getApplicationContext()); mBLEScanner = new Scanner_BLE(this, 7500, -75); mBTDeviceHashMap = new HashMap<>(); mBTDeviceArrayList = new ArrayList<>(); filterBleArrayList = new ArrayList<>(); filterRSSIHashMap = new HashMap<>(); adapter = new ListAdapter_BLE_Devices(this, R.layout.device_list_item, filterBleArrayList); ListView listView = new ListView(this); listView.setAdapter(adapter); listView.setOnItemClickListener(this); ((ScrollView) findViewById(R.id.scrollView)).addView(listView); btn_Scan = (Button) findViewById(R.id.btn_scan); findViewById(R.id.btn_scan).setOnClickListener(this); btn_Settings = (Button) findViewById(R.id.btn_Settings); findViewById(R.id.btn_Settings).setOnClickListener(this); callAPI = new CallAPI(getApplicationContext()); } @Override protected void onStart() { super.onStart(); registerReceiver(mBTStateUpdateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); //For some reason onPause gets called after onCreate if (!PausedOnStartUp) { PausedOnStartUp = true; startScan(); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); callAPI.feedAPI(); } else { stopScan(); } } @Override protected void onStop() { super.onStop(); unregisterReceiver(mBTStateUpdateReceiver); } @Override public void onDestroy() { if (callAPI != null) { callAPI.cancel(true); } super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Controleren of<SUF> if (requestCode == REQUEST_ENABLE_BT) { // Zeker weten dat de aanvraag succesvol was if (resultCode == RESULT_OK) { // Utils.toast(getApplicationContext(), "Thank you for turning on Bluetooth"); } else if (resultCode == RESULT_CANCELED) { Utils.toast(getApplicationContext(), "Please turn on Bluetooth"); } } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Voor later } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_scan: Utils.toast(getApplicationContext(), "Scan Button Pressed"); if (!mBLEScanner.isScanning()) { startScan(); } else { stopScan(); } break; case R.id.btn_Settings: openSettingsActivity(); break; default: break; } } public void addDevice(BluetoothDevice device, int new_rssi) { String address = device.getAddress(); if (!mBTDeviceHashMap.containsKey(address)) { BLE_Device ble_device = new BLE_Device(device); ble_device.setRSSI(new_rssi); mBTDeviceHashMap.put(address, ble_device); mBTDeviceArrayList.add(ble_device); } else { mBTDeviceHashMap.get(address).setRSSI(new_rssi); } filter3ClosestDevices(); adapter.notifyDataSetChanged(); } private void filter3ClosestDevices () { //Putting the RSSI in a different HashMap with as key the address for (String key: mBTDeviceHashMap.keySet()) { filterRSSIHashMap.put(key, mBTDeviceHashMap.get(key).getRSSI()); } //Log.d("FILTER", filterRSSIHashMap.toString()); //Check if there are even 3 devices in range int count = 3; if (filterRSSIHashMap.size() == 1) { count = 1; } else if (filterRSSIHashMap.size() == 2) { count = 2; } //Clear list filterBleArrayList.clear(); //Get 3 lowest RSSI's for (int i = 0; i < count; i++) { String key = getMinKey(filterRSSIHashMap, filterRSSIHashMap.keySet()); filterBleArrayList.add(mBTDeviceHashMap.get(key)); filterRSSIHashMap.remove(key); } //Log.d("HASHMAP", filterRSSIHashMap.toString()); //Log.d("ARRAYLIST", filterBleArrayList.toString()); callAPI.updateDevices(filterBleArrayList); filterRSSIHashMap.clear(); } public String getMinKey(HashMap<String, Integer> map, Set<String> keys) { String minKey = null; int minValue = Integer.MAX_VALUE; for(String key : keys) { int value = map.get(key); if(value < minValue) { minValue = value; minKey = key; } } return minKey; } public void clearList() { filterBleArrayList.clear(); } public void startScan() { btn_Scan.setText("Scanning..."); mBTDeviceArrayList.clear(); mBTDeviceHashMap.clear(); filterRSSIHashMap.clear(); filterBleArrayList.clear(); adapter.notifyDataSetChanged(); mBLEScanner.start(); } public void stopScan() { btn_Scan.setText("Scan Again"); mBLEScanner.stop(); } public void openSettingsActivity() { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } }
115383_0
/* * Copyright 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 nl.reproducer.vertx; import javax.enterprise.context.Dependent; import javax.inject.Inject; import io.quarkus.vertx.web.RouteFilter; import io.vertx.ext.web.RoutingContext; import org.eclipse.microprofile.config.inject.ConfigProperty; public class ApiVersionResponseFilter { private static final String API_VERSION_HEADER = "API-Version"; //CHECKSTYLE:OFF @Inject ConfigProvider provider; //CHECKSTYLE:ON @RouteFilter public void addResponse(RoutingContext rc) { rc.response().headers().set( API_VERSION_HEADER, provider.version ); rc.next(); } @Dependent public static class ConfigProvider { //CHECKSTYLE:OFF @ConfigProperty( name = "application.version" ) String version; //CHECKSTYLE:ON } }
phillip-kruger/reproducer_corrs
src/main/java/nl/reproducer/vertx/ApiVersionResponseFilter.java
414
/* * Copyright 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 TNO Geologische<SUF>*/ package nl.reproducer.vertx; import javax.enterprise.context.Dependent; import javax.inject.Inject; import io.quarkus.vertx.web.RouteFilter; import io.vertx.ext.web.RoutingContext; import org.eclipse.microprofile.config.inject.ConfigProperty; public class ApiVersionResponseFilter { private static final String API_VERSION_HEADER = "API-Version"; //CHECKSTYLE:OFF @Inject ConfigProvider provider; //CHECKSTYLE:ON @RouteFilter public void addResponse(RoutingContext rc) { rc.response().headers().set( API_VERSION_HEADER, provider.version ); rc.next(); } @Dependent public static class ConfigProvider { //CHECKSTYLE:OFF @ConfigProperty( name = "application.version" ) String version; //CHECKSTYLE:ON } }
68755_19
package arc.audio; /** JNI bindings for the Soloud library. */ public class Soloud{ /*JNI #include "soloud.h" #include "soloud_file.h" #include "soloud_wav.h" #include "soloud_wavstream.h" #include "soloud_bus.h" #include "soloud_thread.h" #include "soloud_filter.h" #include "soloud_biquadresonantfilter.h" #include "soloud_echofilter.h" #include "soloud_lofifilter.h" #include "soloud_flangerfilter.h" #include "soloud_waveshaperfilter.h" #include "soloud_bassboostfilter.h" #include "soloud_robotizefilter.h" #include "soloud_freeverbfilter.h" #include <stdio.h> using namespace SoLoud; Soloud soloud; void throwError(JNIEnv* env, int result){ jclass excClass = env->FindClass("arc/util/ArcRuntimeException"); env->ThrowNew(excClass, soloud.getErrorString(result)); } */ static native void init(); /* int result = soloud.init(); if(result != 0) throwError(env, result); */ static native void deinit(); /* soloud.deinit(); */ static native String backendString(); /* return env->NewStringUTF(soloud.getBackendString()); */ static native int backendId(); /* return soloud.getBackendId(); */ static native int backendChannels(); /* return soloud.getBackendChannels(); */ static native int backendSamplerate(); /* return soloud.getBackendSamplerate(); */ static native int backendBufferSize(); /* return soloud.getBackendBufferSize(); */ static native int version(); /* return soloud.getVersion(); */ static native void stopAll(); /* soloud.stopAll(); */ static native void pauseAll(boolean paused); /* soloud.setPauseAll(paused); */ static native void biquadSet(long handle, int type, float frequency, float resonance); /* ((BiquadResonantFilter*)handle)->setParams(type, frequency, resonance); */ static native void echoSet(long handle, float delay, float decay, float filter); /* ((EchoFilter*)handle)->setParams(delay, decay, filter); */ static native void lofiSet(long handle, float sampleRate, float bitDepth); /* ((LofiFilter*)handle)->setParams(sampleRate, bitDepth); */ static native void flangerSet(long handle, float delay, float frequency); /* ((FlangerFilter*)handle)->setParams(delay, frequency); */ static native void waveShaperSet(long handle, float amount); /* ((WaveShaperFilter*)handle)->setParams(amount); */ static native void bassBoostSet(long handle, float amount); /* ((BassboostFilter*)handle)->setParams( amount); */ static native void robotizeSet(long handle, float freq, int waveform); /* ((RobotizeFilter*)handle)->setParams(freq, waveform); */ static native void freeverbSet(long handle, float mode, float roomSize, float damp, float width); /* ((FreeverbFilter*)handle)->setParams(mode, roomSize, damp, width); */ static native long filterBiquad(); /* return (jlong)(new BiquadResonantFilter()); */ static native long filterEcho(); /* return (jlong)(new EchoFilter()); */ static native long filterLofi(); /* return (jlong)(new LofiFilter()); */ static native long filterFlanger(); /* return (jlong)(new FlangerFilter()); */ static native long filterBassBoost(); /* return (jlong)(new BassboostFilter()); */ static native long filterWaveShaper(); /* return (jlong)(new WaveShaperFilter()); */ static native long filterRobotize(); /* return (jlong)(new RobotizeFilter()); */ static native long filterFreeverb(); /* return (jlong)(new FreeverbFilter()); */ static native void setGlobalFilter(int index, long handle); /* soloud.setGlobalFilter(index, ((Filter*)handle)); */ static native void filterFade(int voice, int filter, int attribute, float value, float timeSec); /* soloud.fadeFilterParameter(voice, filter, attribute, value, timeSec); */ static native void filterSet(int voice, int filter, int attribute, float value); /* soloud.setFilterParameter(voice, filter, attribute, value); */ static native long busNew(); /* return (jlong)(new Bus()); */ static native long wavLoad(byte[] bytes, int length); /* Wav* wav = new Wav(); int result = wav->loadMem((unsigned char*)bytes, length, true, true); if(result != 0) throwError(env, result); return (jlong)wav; */ static native void idSeek(int id, float seconds); /* soloud.seek(id, seconds); */ static native void idVolume(int id, float volume); /* soloud.setVolume(id, volume); */ static native float idGetVolume(int id); /* return soloud.getVolume(id); */ static native void idPan(int id, float pan); /* soloud.setPan(id, pan); */ static native void idPitch(int id, float pitch); /* soloud.setRelativePlaySpeed(id, pitch); */ static native void idPause(int id, boolean pause); /* soloud.setPause(id, pause); */ static native boolean idGetPause(int voice); /* return soloud.getPause(voice); */ static native void idProtected(int id, boolean protect); /* soloud.setProtectVoice(id, protect); */ static native void idStop(int voice); /* soloud.stop(voice); */ static native void idLooping(int voice, boolean looping); /* soloud.setLooping(voice, looping); */ static native boolean idGetLooping(int voice); /* return soloud.getLooping(voice); */ static native float idPosition(int voice); /* return (jfloat)soloud.getStreamPosition(voice); */ static native boolean idValid(int voice); /* return soloud.isValidVoiceHandle(voice); */ static native long streamLoad(String path); /* WavStream* stream = new WavStream(); int result = stream->load(path); if(result != 0) throwError(env, result); return (jlong)stream; */ static native double streamLength(long handle); /* WavStream* source = (WavStream*)handle; return (jdouble)source->getLength(); */ static native void sourceDestroy(long handle); /* AudioSource* source = (AudioSource*)handle; delete source; */ static native void sourceInaudible(long handle, boolean tick, boolean play); /* AudioSource* wav = (AudioSource*)handle; wav->setInaudibleBehavior(tick, play); */ static native int sourcePlay(long handle); /* AudioSource* wav = (AudioSource*)handle; return soloud.play(*wav); */ static native int sourceCount(long handle); /* AudioSource* wav = (AudioSource*)handle; return soloud.countAudioSource(*wav); */ static native int sourcePlay(long handle, float volume, float pitch, float pan, boolean loop); /* AudioSource* wav = (AudioSource*)handle; int voice = soloud.play(*wav, volume, pan, false); soloud.setLooping(voice, loop); soloud.setRelativePlaySpeed(voice, pitch); return voice; */ static native int sourcePlayBus(long handle, long busHandle, float volume, float pitch, float pan, boolean loop); /* AudioSource* wav = (AudioSource*)handle; Bus* bus = (Bus*)busHandle; int voice = bus->play(*wav, volume, pan, false); soloud.setLooping(voice, loop); soloud.setRelativePlaySpeed(voice, pitch); return voice; */ static native void sourceLoop(long handle, boolean loop); /* AudioSource* source = (AudioSource*)handle; source->setLooping(loop); */ static native void sourceStop(long handle); /* AudioSource* source = (AudioSource*)handle; source->stop(); */ static native void sourceFilter(long handle, int index, long filter); /* ((AudioSource*)handle)->setFilter(index, ((Filter*)filter)); */ }
phinner/arc
arc-core/src/arc/audio/Soloud.java
2,319
/* ((FreeverbFilter*)handle)->setParams(mode, roomSize, damp, width); */
block_comment
nl
package arc.audio; /** JNI bindings for the Soloud library. */ public class Soloud{ /*JNI #include "soloud.h" #include "soloud_file.h" #include "soloud_wav.h" #include "soloud_wavstream.h" #include "soloud_bus.h" #include "soloud_thread.h" #include "soloud_filter.h" #include "soloud_biquadresonantfilter.h" #include "soloud_echofilter.h" #include "soloud_lofifilter.h" #include "soloud_flangerfilter.h" #include "soloud_waveshaperfilter.h" #include "soloud_bassboostfilter.h" #include "soloud_robotizefilter.h" #include "soloud_freeverbfilter.h" #include <stdio.h> using namespace SoLoud; Soloud soloud; void throwError(JNIEnv* env, int result){ jclass excClass = env->FindClass("arc/util/ArcRuntimeException"); env->ThrowNew(excClass, soloud.getErrorString(result)); } */ static native void init(); /* int result = soloud.init(); if(result != 0) throwError(env, result); */ static native void deinit(); /* soloud.deinit(); */ static native String backendString(); /* return env->NewStringUTF(soloud.getBackendString()); */ static native int backendId(); /* return soloud.getBackendId(); */ static native int backendChannels(); /* return soloud.getBackendChannels(); */ static native int backendSamplerate(); /* return soloud.getBackendSamplerate(); */ static native int backendBufferSize(); /* return soloud.getBackendBufferSize(); */ static native int version(); /* return soloud.getVersion(); */ static native void stopAll(); /* soloud.stopAll(); */ static native void pauseAll(boolean paused); /* soloud.setPauseAll(paused); */ static native void biquadSet(long handle, int type, float frequency, float resonance); /* ((BiquadResonantFilter*)handle)->setParams(type, frequency, resonance); */ static native void echoSet(long handle, float delay, float decay, float filter); /* ((EchoFilter*)handle)->setParams(delay, decay, filter); */ static native void lofiSet(long handle, float sampleRate, float bitDepth); /* ((LofiFilter*)handle)->setParams(sampleRate, bitDepth); */ static native void flangerSet(long handle, float delay, float frequency); /* ((FlangerFilter*)handle)->setParams(delay, frequency); */ static native void waveShaperSet(long handle, float amount); /* ((WaveShaperFilter*)handle)->setParams(amount); */ static native void bassBoostSet(long handle, float amount); /* ((BassboostFilter*)handle)->setParams( amount); */ static native void robotizeSet(long handle, float freq, int waveform); /* ((RobotizeFilter*)handle)->setParams(freq, waveform); */ static native void freeverbSet(long handle, float mode, float roomSize, float damp, float width); /* ((FreeverbFilter*)handle)->setParams(mode, roomSize, damp,<SUF>*/ static native long filterBiquad(); /* return (jlong)(new BiquadResonantFilter()); */ static native long filterEcho(); /* return (jlong)(new EchoFilter()); */ static native long filterLofi(); /* return (jlong)(new LofiFilter()); */ static native long filterFlanger(); /* return (jlong)(new FlangerFilter()); */ static native long filterBassBoost(); /* return (jlong)(new BassboostFilter()); */ static native long filterWaveShaper(); /* return (jlong)(new WaveShaperFilter()); */ static native long filterRobotize(); /* return (jlong)(new RobotizeFilter()); */ static native long filterFreeverb(); /* return (jlong)(new FreeverbFilter()); */ static native void setGlobalFilter(int index, long handle); /* soloud.setGlobalFilter(index, ((Filter*)handle)); */ static native void filterFade(int voice, int filter, int attribute, float value, float timeSec); /* soloud.fadeFilterParameter(voice, filter, attribute, value, timeSec); */ static native void filterSet(int voice, int filter, int attribute, float value); /* soloud.setFilterParameter(voice, filter, attribute, value); */ static native long busNew(); /* return (jlong)(new Bus()); */ static native long wavLoad(byte[] bytes, int length); /* Wav* wav = new Wav(); int result = wav->loadMem((unsigned char*)bytes, length, true, true); if(result != 0) throwError(env, result); return (jlong)wav; */ static native void idSeek(int id, float seconds); /* soloud.seek(id, seconds); */ static native void idVolume(int id, float volume); /* soloud.setVolume(id, volume); */ static native float idGetVolume(int id); /* return soloud.getVolume(id); */ static native void idPan(int id, float pan); /* soloud.setPan(id, pan); */ static native void idPitch(int id, float pitch); /* soloud.setRelativePlaySpeed(id, pitch); */ static native void idPause(int id, boolean pause); /* soloud.setPause(id, pause); */ static native boolean idGetPause(int voice); /* return soloud.getPause(voice); */ static native void idProtected(int id, boolean protect); /* soloud.setProtectVoice(id, protect); */ static native void idStop(int voice); /* soloud.stop(voice); */ static native void idLooping(int voice, boolean looping); /* soloud.setLooping(voice, looping); */ static native boolean idGetLooping(int voice); /* return soloud.getLooping(voice); */ static native float idPosition(int voice); /* return (jfloat)soloud.getStreamPosition(voice); */ static native boolean idValid(int voice); /* return soloud.isValidVoiceHandle(voice); */ static native long streamLoad(String path); /* WavStream* stream = new WavStream(); int result = stream->load(path); if(result != 0) throwError(env, result); return (jlong)stream; */ static native double streamLength(long handle); /* WavStream* source = (WavStream*)handle; return (jdouble)source->getLength(); */ static native void sourceDestroy(long handle); /* AudioSource* source = (AudioSource*)handle; delete source; */ static native void sourceInaudible(long handle, boolean tick, boolean play); /* AudioSource* wav = (AudioSource*)handle; wav->setInaudibleBehavior(tick, play); */ static native int sourcePlay(long handle); /* AudioSource* wav = (AudioSource*)handle; return soloud.play(*wav); */ static native int sourceCount(long handle); /* AudioSource* wav = (AudioSource*)handle; return soloud.countAudioSource(*wav); */ static native int sourcePlay(long handle, float volume, float pitch, float pan, boolean loop); /* AudioSource* wav = (AudioSource*)handle; int voice = soloud.play(*wav, volume, pan, false); soloud.setLooping(voice, loop); soloud.setRelativePlaySpeed(voice, pitch); return voice; */ static native int sourcePlayBus(long handle, long busHandle, float volume, float pitch, float pan, boolean loop); /* AudioSource* wav = (AudioSource*)handle; Bus* bus = (Bus*)busHandle; int voice = bus->play(*wav, volume, pan, false); soloud.setLooping(voice, loop); soloud.setRelativePlaySpeed(voice, pitch); return voice; */ static native void sourceLoop(long handle, boolean loop); /* AudioSource* source = (AudioSource*)handle; source->setLooping(loop); */ static native void sourceStop(long handle); /* AudioSource* source = (AudioSource*)handle; source->stop(); */ static native void sourceFilter(long handle, int index, long filter); /* ((AudioSource*)handle)->setFilter(index, ((Filter*)filter)); */ }
66305_1
// Generated by: hibernate/SpringHibernateDaoImpl.vsl in andromda-spring-cartridge. // license-header java merge-point /** * This is only generated once! It will never be overwritten. * You can (and have to!) safely modify it by hand. */ package org.phoenixctms.ctsms.domain; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hibernate.Transaction; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.phoenixctms.ctsms.compare.FieldComparator; import org.phoenixctms.ctsms.util.CommonUtil; import org.phoenixctms.ctsms.vo.OpsSystBlockVO; import org.phoenixctms.ctsms.vo.OpsSystCategoryVO; import org.phoenixctms.ctsms.vo.OpsSystVO; /** * @see OpsSyst */ public class OpsSystDaoImpl extends OpsSystDaoBase { // Notation: erste drei Stellen numerisch, 4. Stelle alphanumerisch, 5./6. Stelle numerisch oder: x - sonstige Prozeduren, y - nicht naeher bezeichnet private final static Pattern OPS_CODE_PATTERN_REGEXP = Pattern.compile("^(\\d-)(\\d{2,2}[\\da-z])((\\.[\\da-z])([\\da-z])?)?(#)?$"); private org.hibernate.Criteria createOpsSystCriteria() { org.hibernate.Criteria opsSystCriteria = this.getSession().createCriteria(OpsSyst.class); return opsSystCriteria; } /** * @inheritDoc */ @Override protected OpsSyst handleFindByOpsCode(String firstCode, String secondCode, String revision) { String code = CommonUtil.isEmptyString(firstCode) ? secondCode : firstCode; if (!CommonUtil.isEmptyString(code)) { Matcher matcher = OPS_CODE_PATTERN_REGEXP.matcher(code); if (matcher.find()) { StringBuilder search = new StringBuilder(matcher.group(1)); search.append(matcher.group(2)); String detail = matcher.group(3); if (detail != null && detail.length() > 0) { search.append(detail); } org.hibernate.Criteria opsSystCriteria = createOpsSystCriteria(); opsSystCriteria.setCacheable(true); opsSystCriteria.add(Restrictions.eq("revision", revision)); org.hibernate.Criteria categoriesCriteria = opsSystCriteria.createCriteria("categories"); categoriesCriteria.add(Restrictions.eq("code", search.toString())); categoriesCriteria.add(Restrictions.eq("last", true)); opsSystCriteria.setMaxResults(1); return (OpsSyst) opsSystCriteria.uniqueResult(); } } return null; } @Override protected long handleGetProcedureCount(String revision) throws Exception { org.hibernate.Criteria opsSystCriteria = createOpsSystCriteria(); opsSystCriteria.add(Restrictions.eq("revision", revision)); opsSystCriteria.createCriteria("codes", CriteriaSpecification.INNER_JOIN) .createCriteria("procedures", CriteriaSpecification.INNER_JOIN); return (Long) opsSystCriteria.setProjection(Projections.rowCount()).uniqueResult(); } @Override public void handleRemoveAllTxn(Set<OpsSyst> opsSysts) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { Iterator<OpsSyst> it = opsSysts.iterator(); while (it.hasNext()) { removeOpsSyst(it.next().getId()); } transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } @Override public void handleRemoveTxn(Long opsSystId) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { removeOpsSyst(opsSystId); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } @Override public void handleRemoveTxn(OpsSyst opsSyst) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { removeOpsSyst(opsSyst.getId()); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } /** * Retrieves the entity object that is associated with the specified value object * from the object store. If no such entity object exists in the object store, * a new, blank entity is created */ private OpsSyst loadOpsSystFromOpsSystVO(OpsSystVO opsSystVO) { Long id = opsSystVO.getId(); OpsSyst opsSyst = null; if (id != null) { opsSyst = this.load(id); } if (opsSyst == null) { opsSyst = OpsSyst.Factory.newInstance(); } return opsSyst; } /** * @inheritDoc */ @Override public OpsSyst opsSystVOToEntity(OpsSystVO opsSystVO) { OpsSyst entity = this.loadOpsSystFromOpsSystVO(opsSystVO); this.opsSystVOToEntity(opsSystVO, entity, true); return entity; } /** * @inheritDoc */ @Override public void opsSystVOToEntity( OpsSystVO source, OpsSyst target, boolean copyIfNull) { super.opsSystVOToEntity(source, target, copyIfNull); Collection blocks = source.getBlocks(); if (blocks.size() > 0) { blocks = new ArrayList(blocks); //prevent changing VO this.getOpsSystBlockDao().opsSystBlockVOToEntityCollection(blocks); target.setBlocks(blocks); } else if (copyIfNull) { target.getBlocks().clear(); } Collection categories = source.getCategories(); if (categories.size() > 0) { categories = new ArrayList(categories); //prevent changing VO this.getOpsSystCategoryDao().opsSystCategoryVOToEntityCollection(categories); target.setCategories(categories); } else if (copyIfNull) { target.getCategories().clear(); } } private void removeOpsSyst(Long opsSystId) { OpsSyst opsSyst = get(opsSystId); this.getHibernateTemplate().deleteAll(opsSyst.getCodes()); // constraint error if used by procedure opsSyst.getCodes().clear(); Iterator<OpsSystCategory> it = opsSyst.getCategories().iterator(); while (it.hasNext()) { this.getHibernateTemplate().deleteAll(it.next().getModifiers()); } this.getHibernateTemplate().deleteAll(opsSyst.getCategories()); this.getHibernateTemplate().deleteAll(opsSyst.getBlocks()); this.getHibernateTemplate().delete(opsSyst); } private ArrayList<OpsSystBlockVO> toOpsSystBlockVOCollection(Collection<OpsSystBlock> blocks) { // related to http://forum.andromda.org/viewtopic.php?t=4288 OpsSystBlockDao opsSystBlockDao = this.getOpsSystBlockDao(); ArrayList<OpsSystBlockVO> result = new ArrayList<OpsSystBlockVO>(blocks.size()); Iterator<OpsSystBlock> it = blocks.iterator(); while (it.hasNext()) { result.add(opsSystBlockDao.toOpsSystBlockVO(it.next())); } Collections.sort(result, new FieldComparator(false, "getLevel")); return result; } private ArrayList<OpsSystCategoryVO> toOpsSystCategoryVOCollection(Collection<OpsSystCategory> categories) { // related to http://forum.andromda.org/viewtopic.php?t=4288 OpsSystCategoryDao opsSystCategoryDao = this.getOpsSystCategoryDao(); ArrayList<OpsSystCategoryVO> result = new ArrayList<OpsSystCategoryVO>(categories.size()); Iterator<OpsSystCategory> it = categories.iterator(); while (it.hasNext()) { result.add(opsSystCategoryDao.toOpsSystCategoryVO(it.next())); } Collections.sort(result, new FieldComparator(false, "getLevel")); return result; } /** * @inheritDoc */ @Override public OpsSystVO toOpsSystVO(final OpsSyst entity) { return super.toOpsSystVO(entity); } /** * @inheritDoc */ @Override public void toOpsSystVO( OpsSyst source, OpsSystVO target) { super.toOpsSystVO(source, target); target.setBlocks(toOpsSystBlockVOCollection(source.getBlocks())); target.setCategories(toOpsSystCategoryVOCollection(source.getCategories())); } }
phoenixctms/ctsms
core/src/main/java/org/phoenixctms/ctsms/domain/OpsSystDaoImpl.java
2,678
// license-header java merge-point
line_comment
nl
// Generated by: hibernate/SpringHibernateDaoImpl.vsl in andromda-spring-cartridge. // license-header java<SUF> /** * This is only generated once! It will never be overwritten. * You can (and have to!) safely modify it by hand. */ package org.phoenixctms.ctsms.domain; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.hibernate.Transaction; import org.hibernate.criterion.CriteriaSpecification; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.phoenixctms.ctsms.compare.FieldComparator; import org.phoenixctms.ctsms.util.CommonUtil; import org.phoenixctms.ctsms.vo.OpsSystBlockVO; import org.phoenixctms.ctsms.vo.OpsSystCategoryVO; import org.phoenixctms.ctsms.vo.OpsSystVO; /** * @see OpsSyst */ public class OpsSystDaoImpl extends OpsSystDaoBase { // Notation: erste drei Stellen numerisch, 4. Stelle alphanumerisch, 5./6. Stelle numerisch oder: x - sonstige Prozeduren, y - nicht naeher bezeichnet private final static Pattern OPS_CODE_PATTERN_REGEXP = Pattern.compile("^(\\d-)(\\d{2,2}[\\da-z])((\\.[\\da-z])([\\da-z])?)?(#)?$"); private org.hibernate.Criteria createOpsSystCriteria() { org.hibernate.Criteria opsSystCriteria = this.getSession().createCriteria(OpsSyst.class); return opsSystCriteria; } /** * @inheritDoc */ @Override protected OpsSyst handleFindByOpsCode(String firstCode, String secondCode, String revision) { String code = CommonUtil.isEmptyString(firstCode) ? secondCode : firstCode; if (!CommonUtil.isEmptyString(code)) { Matcher matcher = OPS_CODE_PATTERN_REGEXP.matcher(code); if (matcher.find()) { StringBuilder search = new StringBuilder(matcher.group(1)); search.append(matcher.group(2)); String detail = matcher.group(3); if (detail != null && detail.length() > 0) { search.append(detail); } org.hibernate.Criteria opsSystCriteria = createOpsSystCriteria(); opsSystCriteria.setCacheable(true); opsSystCriteria.add(Restrictions.eq("revision", revision)); org.hibernate.Criteria categoriesCriteria = opsSystCriteria.createCriteria("categories"); categoriesCriteria.add(Restrictions.eq("code", search.toString())); categoriesCriteria.add(Restrictions.eq("last", true)); opsSystCriteria.setMaxResults(1); return (OpsSyst) opsSystCriteria.uniqueResult(); } } return null; } @Override protected long handleGetProcedureCount(String revision) throws Exception { org.hibernate.Criteria opsSystCriteria = createOpsSystCriteria(); opsSystCriteria.add(Restrictions.eq("revision", revision)); opsSystCriteria.createCriteria("codes", CriteriaSpecification.INNER_JOIN) .createCriteria("procedures", CriteriaSpecification.INNER_JOIN); return (Long) opsSystCriteria.setProjection(Projections.rowCount()).uniqueResult(); } @Override public void handleRemoveAllTxn(Set<OpsSyst> opsSysts) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { Iterator<OpsSyst> it = opsSysts.iterator(); while (it.hasNext()) { removeOpsSyst(it.next().getId()); } transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } @Override public void handleRemoveTxn(Long opsSystId) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { removeOpsSyst(opsSystId); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } @Override public void handleRemoveTxn(OpsSyst opsSyst) throws Exception { Transaction transaction = this.getSession(true).beginTransaction(); try { removeOpsSyst(opsSyst.getId()); transaction.commit(); } catch (Exception e) { transaction.rollback(); throw e; } } /** * Retrieves the entity object that is associated with the specified value object * from the object store. If no such entity object exists in the object store, * a new, blank entity is created */ private OpsSyst loadOpsSystFromOpsSystVO(OpsSystVO opsSystVO) { Long id = opsSystVO.getId(); OpsSyst opsSyst = null; if (id != null) { opsSyst = this.load(id); } if (opsSyst == null) { opsSyst = OpsSyst.Factory.newInstance(); } return opsSyst; } /** * @inheritDoc */ @Override public OpsSyst opsSystVOToEntity(OpsSystVO opsSystVO) { OpsSyst entity = this.loadOpsSystFromOpsSystVO(opsSystVO); this.opsSystVOToEntity(opsSystVO, entity, true); return entity; } /** * @inheritDoc */ @Override public void opsSystVOToEntity( OpsSystVO source, OpsSyst target, boolean copyIfNull) { super.opsSystVOToEntity(source, target, copyIfNull); Collection blocks = source.getBlocks(); if (blocks.size() > 0) { blocks = new ArrayList(blocks); //prevent changing VO this.getOpsSystBlockDao().opsSystBlockVOToEntityCollection(blocks); target.setBlocks(blocks); } else if (copyIfNull) { target.getBlocks().clear(); } Collection categories = source.getCategories(); if (categories.size() > 0) { categories = new ArrayList(categories); //prevent changing VO this.getOpsSystCategoryDao().opsSystCategoryVOToEntityCollection(categories); target.setCategories(categories); } else if (copyIfNull) { target.getCategories().clear(); } } private void removeOpsSyst(Long opsSystId) { OpsSyst opsSyst = get(opsSystId); this.getHibernateTemplate().deleteAll(opsSyst.getCodes()); // constraint error if used by procedure opsSyst.getCodes().clear(); Iterator<OpsSystCategory> it = opsSyst.getCategories().iterator(); while (it.hasNext()) { this.getHibernateTemplate().deleteAll(it.next().getModifiers()); } this.getHibernateTemplate().deleteAll(opsSyst.getCategories()); this.getHibernateTemplate().deleteAll(opsSyst.getBlocks()); this.getHibernateTemplate().delete(opsSyst); } private ArrayList<OpsSystBlockVO> toOpsSystBlockVOCollection(Collection<OpsSystBlock> blocks) { // related to http://forum.andromda.org/viewtopic.php?t=4288 OpsSystBlockDao opsSystBlockDao = this.getOpsSystBlockDao(); ArrayList<OpsSystBlockVO> result = new ArrayList<OpsSystBlockVO>(blocks.size()); Iterator<OpsSystBlock> it = blocks.iterator(); while (it.hasNext()) { result.add(opsSystBlockDao.toOpsSystBlockVO(it.next())); } Collections.sort(result, new FieldComparator(false, "getLevel")); return result; } private ArrayList<OpsSystCategoryVO> toOpsSystCategoryVOCollection(Collection<OpsSystCategory> categories) { // related to http://forum.andromda.org/viewtopic.php?t=4288 OpsSystCategoryDao opsSystCategoryDao = this.getOpsSystCategoryDao(); ArrayList<OpsSystCategoryVO> result = new ArrayList<OpsSystCategoryVO>(categories.size()); Iterator<OpsSystCategory> it = categories.iterator(); while (it.hasNext()) { result.add(opsSystCategoryDao.toOpsSystCategoryVO(it.next())); } Collections.sort(result, new FieldComparator(false, "getLevel")); return result; } /** * @inheritDoc */ @Override public OpsSystVO toOpsSystVO(final OpsSyst entity) { return super.toOpsSystVO(entity); } /** * @inheritDoc */ @Override public void toOpsSystVO( OpsSyst source, OpsSystVO target) { super.toOpsSystVO(source, target); target.setBlocks(toOpsSystBlockVOCollection(source.getBlocks())); target.setCategories(toOpsSystCategoryVOCollection(source.getCategories())); } }
30819_11
package dynProg.solvers; import dynProg.Solver; public class BottomUpSolver implements Solver{ private int[][] matrix; public BottomUpSolver(){ } public static void main(String[] args){ BottomUpSolver s = new BottomUpSolver(); s.solve(new int[]{3,5,7,9,11}, 17); } public boolean solve(int[] numbers, int sum){ matrix = new int[numbers.length][sum]; // Elke rij bijlangs gaan //M(i,j) //row == i //answer == j int totaal=0; for(int p=0;p<numbers.length;p++){ totaal += numbers[p]; } for(int i = 0; i<numbers.length; i++){ int somB = 0; for(int j = 0; j<=i; j++){ // Plaats de huidige // Als numbers j is 3 dan wordt er een 1 geplaatst op M(0,2) matrix[i][numbers[j]-1] = numbers[j]; // De som uitvoeren // Zolang de som van B kleiner is dan 17 zal hij toegevoegd worden aan de matrix // Als {3,5} aan de beurt is wordt er dus 8 uitgerekend // Gekeken of het kleiner is dan 17 // en vervolgens in dit geval op {1,7} geplaatst somB += numbers[j]; if(somB<=sum){ matrix[i][somB - 1] = somB; } // De som van de vorige // Totaal is gelijk aan de som van B - het getal voor de huidige // Dit moet eigenlijk vaker om alle antwoorden te krijgen maar is op dit moment niet nodig om te doen if (j > 0) { totaal = somB - numbers[j - 1]; if(totaal-1<=sum){ matrix[i][totaal - 1] = totaal; } } } } return solved(sum); } /** * * @param sum * @return */ private boolean solved(int sum){ if(sum<= matrix[0].length){ //Kijken of er een antwoord staat in de laatste kolom //Elke rij bijlangs gaan en kijken in de laatste kolom of er een antwoord staat for(int i = 0; i<matrix.length; i++){ if(matrix[i][sum-1] != 0){ System.out.println("true"); return true; } } } return false; } }
phoenixz0024/OGGG_2.3
DynamicProgramming/src/dynProg/solvers/BottomUpSolver.java
911
// Totaal is gelijk aan de som van B - het getal voor de huidige
line_comment
nl
package dynProg.solvers; import dynProg.Solver; public class BottomUpSolver implements Solver{ private int[][] matrix; public BottomUpSolver(){ } public static void main(String[] args){ BottomUpSolver s = new BottomUpSolver(); s.solve(new int[]{3,5,7,9,11}, 17); } public boolean solve(int[] numbers, int sum){ matrix = new int[numbers.length][sum]; // Elke rij bijlangs gaan //M(i,j) //row == i //answer == j int totaal=0; for(int p=0;p<numbers.length;p++){ totaal += numbers[p]; } for(int i = 0; i<numbers.length; i++){ int somB = 0; for(int j = 0; j<=i; j++){ // Plaats de huidige // Als numbers j is 3 dan wordt er een 1 geplaatst op M(0,2) matrix[i][numbers[j]-1] = numbers[j]; // De som uitvoeren // Zolang de som van B kleiner is dan 17 zal hij toegevoegd worden aan de matrix // Als {3,5} aan de beurt is wordt er dus 8 uitgerekend // Gekeken of het kleiner is dan 17 // en vervolgens in dit geval op {1,7} geplaatst somB += numbers[j]; if(somB<=sum){ matrix[i][somB - 1] = somB; } // De som van de vorige // Totaal is<SUF> // Dit moet eigenlijk vaker om alle antwoorden te krijgen maar is op dit moment niet nodig om te doen if (j > 0) { totaal = somB - numbers[j - 1]; if(totaal-1<=sum){ matrix[i][totaal - 1] = totaal; } } } } return solved(sum); } /** * * @param sum * @return */ private boolean solved(int sum){ if(sum<= matrix[0].length){ //Kijken of er een antwoord staat in de laatste kolom //Elke rij bijlangs gaan en kijken in de laatste kolom of er een antwoord staat for(int i = 0; i<matrix.length; i++){ if(matrix[i][sum-1] != 0){ System.out.println("true"); return true; } } } return false; } }
42087_5
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; // NOTA BENE: Deze code is niet thread-safe omdat jullie dat in de 1e week nog niet kennen. // Zie paragraaf 30.2 voor de thread-safe implementatie. public class DobbelsteenModel { private int waarde; private ArrayList<ActionListener> actionListenerList = new ArrayList<ActionListener>(); public DobbelsteenModel() { waarde= (int)(Math.random()*6+1); } public int getWaarde() { return waarde; } public void verhoog() { waarde++; if (waarde>6) waarde=1; // Merk op dat we de 3e String-parameter van de constructor van de ActionEvent niet invullen. // In dit geval zou je die kunnen gebruiken om de nieuwe dobbelsteenwaarde mee te geven // aan de ActionListener. Dan hoeft de ActionListener niet met e.getSource() weer naar // het model toe te gaan. processEvent( new ActionEvent( this, ActionEvent.ACTION_PERFORMED, null)); } public void verlaag() { waarde--; if (waarde<1) waarde=6; processEvent( new ActionEvent( this, ActionEvent.ACTION_PERFORMED, null)); } public void gooi(){ waarde= (int)(Math.random()*6+1); processEvent( new ActionEvent( this, ActionEvent.ACTION_PERFORMED, null)); } public void addActionListener( ActionListener l){ actionListenerList.add( l ); } public void removeActionListener( ActionListener l){ if ( actionListenerList.contains( l ) ) actionListenerList.remove( l ); } private void processEvent(ActionEvent e){ // Hieronder gebruiken we het nieuwe Java "foreach" statement. // Lees het als: "for each ActionListener in actionListenerList do ..." // Je kunt ook een for-lus of een iterator gebruiken, maar foreach is het elegantste. for( ActionListener l : actionListenerList) l.actionPerformed( e ); } }
phoenixz0024/OG_2.3
Opdracht8_Leertaak1/src/DobbelsteenModel.java
611
// het model toe te gaan.
line_comment
nl
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; // NOTA BENE: Deze code is niet thread-safe omdat jullie dat in de 1e week nog niet kennen. // Zie paragraaf 30.2 voor de thread-safe implementatie. public class DobbelsteenModel { private int waarde; private ArrayList<ActionListener> actionListenerList = new ArrayList<ActionListener>(); public DobbelsteenModel() { waarde= (int)(Math.random()*6+1); } public int getWaarde() { return waarde; } public void verhoog() { waarde++; if (waarde>6) waarde=1; // Merk op dat we de 3e String-parameter van de constructor van de ActionEvent niet invullen. // In dit geval zou je die kunnen gebruiken om de nieuwe dobbelsteenwaarde mee te geven // aan de ActionListener. Dan hoeft de ActionListener niet met e.getSource() weer naar // het model<SUF> processEvent( new ActionEvent( this, ActionEvent.ACTION_PERFORMED, null)); } public void verlaag() { waarde--; if (waarde<1) waarde=6; processEvent( new ActionEvent( this, ActionEvent.ACTION_PERFORMED, null)); } public void gooi(){ waarde= (int)(Math.random()*6+1); processEvent( new ActionEvent( this, ActionEvent.ACTION_PERFORMED, null)); } public void addActionListener( ActionListener l){ actionListenerList.add( l ); } public void removeActionListener( ActionListener l){ if ( actionListenerList.contains( l ) ) actionListenerList.remove( l ); } private void processEvent(ActionEvent e){ // Hieronder gebruiken we het nieuwe Java "foreach" statement. // Lees het als: "for each ActionListener in actionListenerList do ..." // Je kunt ook een for-lus of een iterator gebruiken, maar foreach is het elegantste. for( ActionListener l : actionListenerList) l.actionPerformed( e ); } }
14944_1
package inleidingJava; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class EindSpelServlet extends HttpServlet { String boodschap = ""; int aantalLucifers = 0; String eindeSpelImage = ""; boolean gewonnen = false; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { if (req.getParameter("nieuw_spel") != null) { eindeSpelImage = ""; aantalLucifers = 23; boodschap = "<p>Aantal smileys: " + aantalLucifers + ". Jouw beurt.</p>"; gewonnen = false; this.printHtml(resp); } else { aantalLucifers = Integer.parseInt(req.getParameter("aantal_lucifers")); try { int aantalVerminderen = Integer.parseInt(req.getParameter("aantal_verminderen")); if (aantalVerminderen < 1 || aantalVerminderen > 3) { boodschap = "<p class=\"spel_foutmelding\">Onjuiste invoer</p>"; this.printHtml(resp); } else { aantalLucifers -= aantalVerminderen; //mens heeft gewonnen if (aantalLucifers == 1) { boodschap = "<p>Hmmm... je hebt gewonnen</p>"; aantalLucifers = 0; eindeSpelImage = "<img src=\"/AO/InlJava/H14/images/sad_face.png\" id=\"einde_spel\">"; this.printHtml(resp); //computer heeft gewonnen } else if (aantalLucifers <= 0) { boodschap = "<p>Ha!!! Je hebt verloren.</p>"; eindeSpelImage = "<img src=\"/AO/InlJava/H14/images/evil-smiley-face.png\" id=\"einde_spel\">"; this.printHtml(resp); // computer aan zet } else { int beurtComputer; int modulo = aantalLucifers % 4; if (modulo == 0) { beurtComputer = 3; gewonnen = true; } else if (modulo == 1) { beurtComputer = new Random().nextInt(3) + 1; gewonnen = false; } else if (modulo == 2) { beurtComputer = 1; gewonnen = true; } else { beurtComputer = 2; gewonnen = true; } aantalLucifers -= beurtComputer; boodschap = "<p>De computer heeft " + beurtComputer + " smileys weggehaald.<br> " + "Aantal resterende smileys: " + aantalLucifers + ". Jouw beurt</p>"; this.printHtml(resp); } } } catch (NumberFormatException e) { boodschap = "<p class=\"spel_foutmelding\">Voer een geheel getal in</p>"; this.printHtml(resp); } } } private void printHtml(HttpServletResponse resp) { PrintWriter out = null; try { out = resp.getWriter(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (eindeSpelImage.equals("")) { out.println("<label>Hoeveel smileys neem je (&eacute;&eacute;n, twee of drie)?</label>"); out.println("<input type=\"number\" id=\"invoer_spel\">"); out.println("<button type=\"button\" id=\"speel_knop\">Speel</button>"); out.println(boodschap); out.println("<input type=\"hidden\" id=\"aantal_lucifers\" value=\"" + aantalLucifers + "\">"); out.println("<div id=\"inl_java_spel_plaatjes\">"); for (int i = 0; i < aantalLucifers; i++) { if (gewonnen) { out.println("<img src=\"/AO/InlJava/H14/images/surely_winning_40px.png\" class=\"lucifer\">"); } else { out.println("<img src=\"/AO/InlJava/H14/images/basic1-119_smiley_neutral-512_40px.png\" class=\"lucifer\">"); } } out.println("</div>"); } else { out.println(boodschap); out.println(eindeSpelImage); out.println("<button type=\"button\" class=\"btn btn-danger\" id=\"nieuw_spel_knop\">Nieuw spel</button>"); } out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
pieeet/ao-roc-dev
rocdevcursussen/src/main/java/inleidingJava/EindSpelServlet.java
1,465
//computer heeft gewonnen
line_comment
nl
package inleidingJava; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class EindSpelServlet extends HttpServlet { String boodschap = ""; int aantalLucifers = 0; String eindeSpelImage = ""; boolean gewonnen = false; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { if (req.getParameter("nieuw_spel") != null) { eindeSpelImage = ""; aantalLucifers = 23; boodschap = "<p>Aantal smileys: " + aantalLucifers + ". Jouw beurt.</p>"; gewonnen = false; this.printHtml(resp); } else { aantalLucifers = Integer.parseInt(req.getParameter("aantal_lucifers")); try { int aantalVerminderen = Integer.parseInt(req.getParameter("aantal_verminderen")); if (aantalVerminderen < 1 || aantalVerminderen > 3) { boodschap = "<p class=\"spel_foutmelding\">Onjuiste invoer</p>"; this.printHtml(resp); } else { aantalLucifers -= aantalVerminderen; //mens heeft gewonnen if (aantalLucifers == 1) { boodschap = "<p>Hmmm... je hebt gewonnen</p>"; aantalLucifers = 0; eindeSpelImage = "<img src=\"/AO/InlJava/H14/images/sad_face.png\" id=\"einde_spel\">"; this.printHtml(resp); //computer heeft<SUF> } else if (aantalLucifers <= 0) { boodschap = "<p>Ha!!! Je hebt verloren.</p>"; eindeSpelImage = "<img src=\"/AO/InlJava/H14/images/evil-smiley-face.png\" id=\"einde_spel\">"; this.printHtml(resp); // computer aan zet } else { int beurtComputer; int modulo = aantalLucifers % 4; if (modulo == 0) { beurtComputer = 3; gewonnen = true; } else if (modulo == 1) { beurtComputer = new Random().nextInt(3) + 1; gewonnen = false; } else if (modulo == 2) { beurtComputer = 1; gewonnen = true; } else { beurtComputer = 2; gewonnen = true; } aantalLucifers -= beurtComputer; boodschap = "<p>De computer heeft " + beurtComputer + " smileys weggehaald.<br> " + "Aantal resterende smileys: " + aantalLucifers + ". Jouw beurt</p>"; this.printHtml(resp); } } } catch (NumberFormatException e) { boodschap = "<p class=\"spel_foutmelding\">Voer een geheel getal in</p>"; this.printHtml(resp); } } } private void printHtml(HttpServletResponse resp) { PrintWriter out = null; try { out = resp.getWriter(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (eindeSpelImage.equals("")) { out.println("<label>Hoeveel smileys neem je (&eacute;&eacute;n, twee of drie)?</label>"); out.println("<input type=\"number\" id=\"invoer_spel\">"); out.println("<button type=\"button\" id=\"speel_knop\">Speel</button>"); out.println(boodschap); out.println("<input type=\"hidden\" id=\"aantal_lucifers\" value=\"" + aantalLucifers + "\">"); out.println("<div id=\"inl_java_spel_plaatjes\">"); for (int i = 0; i < aantalLucifers; i++) { if (gewonnen) { out.println("<img src=\"/AO/InlJava/H14/images/surely_winning_40px.png\" class=\"lucifer\">"); } else { out.println("<img src=\"/AO/InlJava/H14/images/basic1-119_smiley_neutral-512_40px.png\" class=\"lucifer\">"); } } out.println("</div>"); } else { out.println(boodschap); out.println(eindeSpelImage); out.println("<button type=\"button\" class=\"btn btn-danger\" id=\"nieuw_spel_knop\">Nieuw spel</button>"); } out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
161610_1
/* * This file is part of ekmeans. * * ekmeans 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. * * ekmeans 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 * Foobar. If not, see <http://www.gnu.org/licenses/>. * * ekmeans Copyright (C) 2012 Pierre-David Belanger <[email protected]> * * Contributor(s): Pierre-David Belanger <[email protected]> */ package ca.pjer.ekmeans; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Locale; import java.util.Random; public class EKmeansGUI { private class DoubleEKmeansExt extends DoubleEKmeans { public DoubleEKmeansExt(double[][] centroids, double[][] points, boolean equal, DoubleDistanceFunction doubleDistanceFunction, Listener listener) { super(centroids, points, equal, doubleDistanceFunction, listener); } public int[] getAssignments() { return assignments; } public int[] getCounts() { return counts; } } private static final int MIN = 0; private static final int MAX = 1; private static final int LEN = 2; private static final int X = 0; private static final int Y = 1; private static final int RESOLUTION = 300; private static final Random RANDOM = new Random(System.currentTimeMillis()); private JToolBar toolBar; private JTextField nTextField; private JTextField kTextField; private JCheckBox equalCheckBox; private JTextField debugTextField; private JPanel canvaPanel; private JLabel statusBar; private double[][] centroids = null; private double[][] points = null; private double[][] minmaxlens = null; private DoubleEKmeansExt eKmeans = null; private String[] lines = null; public EKmeansGUI() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setMinimumSize(new Dimension(RESOLUTION + 100, RESOLUTION + 100)); frame.setPreferredSize(new Dimension(RESOLUTION * 2, RESOLUTION * 2)); JPanel contentPanel = new JPanel(); contentPanel.setLayout(new BorderLayout()); frame.setContentPane(contentPanel); toolBar = new JToolBar(); toolBar.setFloatable(false); contentPanel.add(toolBar, BorderLayout.NORTH); JButton csvImportButton = new JButton(); csvImportButton.setAction(new AbstractAction(" Import CSV ") { public void actionPerformed(ActionEvent ae) { csvImport(); } }); toolBar.add(csvImportButton); JButton csvExportButton = new JButton(); csvExportButton.setAction(new AbstractAction(" Export CSV ") { public void actionPerformed(ActionEvent ae) { csvExport(); } }); toolBar.add(csvExportButton); JLabel nLabel = new JLabel("n:"); toolBar.add(nLabel); nTextField = new JTextField("1000"); toolBar.add(nTextField); JButton randomButton = new JButton(); randomButton.setAction(new AbstractAction(" Random ") { public void actionPerformed(ActionEvent ae) { random(); } }); toolBar.add(randomButton); JLabel kLabel = new JLabel("k:"); toolBar.add(kLabel); kTextField = new JTextField("5"); toolBar.add(kTextField); JLabel equalLabel = new JLabel("equal:"); toolBar.add(equalLabel); equalCheckBox = new JCheckBox(""); toolBar.add(equalCheckBox); JLabel debugLabel = new JLabel("debug:"); toolBar.add(debugLabel); debugTextField = new JTextField("0"); toolBar.add(debugTextField); JButton runButton = new JButton(); runButton.setAction(new AbstractAction(" Start ") { public void actionPerformed(ActionEvent ae) { start(); } }); toolBar.add(runButton); canvaPanel = new JPanel() { @Override public void paint(Graphics g) { EKmeansGUI.this.paint(g, getWidth(), getHeight()); } }; contentPanel.add(canvaPanel, BorderLayout.CENTER); statusBar = new JLabel(" "); contentPanel.add(statusBar, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } private void enableToolBar(boolean enabled) { for (Component c : toolBar.getComponents()) { c.setEnabled(enabled); } } private void csvImport() { enableToolBar(false); eKmeans = null; lines = null; try { JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showOpenDialog(toolBar); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } minmaxlens = new double[][]{ {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}, {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY}, {0d, 0d} }; java.util.List points = new ArrayList(); java.util.List lines = new ArrayList(); BufferedReader reader = new BufferedReader(new FileReader(chooser.getSelectedFile())); String line; while ((line = reader.readLine()) != null) { lines.add(line); String[] pointString = line.split(","); double[] point = new double[2]; point[X] = Double.parseDouble(pointString[X].trim()); point[Y] = Double.parseDouble(pointString[Y].trim()); System.out.println(point[X] + ", " + point[Y]); points.add(point); if (point[X] < minmaxlens[MIN][X]) { minmaxlens[MIN][X] = point[X]; } if (point[Y] < minmaxlens[MIN][Y]) { minmaxlens[MIN][Y] = point[Y]; } if (point[X] > minmaxlens[MAX][X]) { minmaxlens[MAX][X] = point[X]; } if (point[Y] > minmaxlens[MAX][Y]) { minmaxlens[MAX][Y] = point[Y]; } } minmaxlens[LEN][X] = minmaxlens[MAX][X] - minmaxlens[MIN][X]; minmaxlens[LEN][Y] = minmaxlens[MAX][Y] - minmaxlens[MIN][Y]; reader.close(); this.points = (double[][]) points.toArray(new double[points.size()][]); nTextField.setText(String.valueOf(this.points.length)); this.lines = (String[]) lines.toArray(new String[lines.size()]); } catch (Exception e) { e.printStackTrace(System.err); } finally { canvaPanel.repaint(); enableToolBar(true); } } private void csvExport() { if (eKmeans == null) { return; } enableToolBar(false); try { JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showSaveDialog(toolBar); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(chooser.getSelectedFile()))); double[][] points = this.points; int[] assignments = eKmeans.getAssignments(); if (lines != null) { for (int i = 0; i < points.length; i++) { writer.printf(Locale.ENGLISH, "%d,%s%n", assignments[i], lines[i]); } } else { for (int i = 0; i < points.length; i++) { writer.printf(Locale.ENGLISH, "%d,%f,%f%n", assignments[i], points[i][X], points[i][Y]); } } writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(System.err); } finally { canvaPanel.repaint(); enableToolBar(true); } } private void random() { enableToolBar(false); eKmeans = null; lines = null; int n = Integer.parseInt(nTextField.getText()); points = new double[n][2]; minmaxlens = new double[][]{ {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}, {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY}, {0d, 0d} }; for (int i = 0; i < n; i++) { points[i][X] = RANDOM.nextDouble(); points[i][Y] = RANDOM.nextDouble(); if (points[i][X] < minmaxlens[MIN][X]) { minmaxlens[MIN][X] = points[i][X]; } if (points[i][Y] < minmaxlens[MIN][Y]) { minmaxlens[MIN][Y] = points[i][Y]; } if (points[i][X] > minmaxlens[MAX][X]) { minmaxlens[MAX][X] = points[i][X]; } if (points[i][Y] > minmaxlens[MAX][Y]) { minmaxlens[MAX][Y] = points[i][Y]; } } minmaxlens[LEN][X] = minmaxlens[MAX][X] - minmaxlens[MIN][X]; minmaxlens[LEN][Y] = minmaxlens[MAX][Y] - minmaxlens[MIN][Y]; canvaPanel.repaint(); enableToolBar(true); } private void start() { if (points == null) { random(); } new Thread(new Runnable() { public void run() { enableToolBar(false); try { EKmeansGUI.this.run(); } finally { enableToolBar(true); } } }).start(); } private void run() { try { URL url = new URL("http://staticmap.openstreetmap.de/staticmap.php?center=" + (minmaxlens[MIN][X] + (minmaxlens[LEN][X] / 2d)) + "," + (minmaxlens[MIN][Y] + (minmaxlens[LEN][Y] / 2d)) + "&zoom=14&size=" + canvaPanel.getWidth() + "x" + canvaPanel.getHeight() + "&maptype=mapnik"); System.out.println("url:" + url); } catch (MalformedURLException e) { e.printStackTrace(); } int k = Integer.parseInt(kTextField.getText()); boolean equal = equalCheckBox.isSelected(); int debugTmp = 0; try { debugTmp = Integer.parseInt(debugTextField.getText()); } catch (NumberFormatException ignore) { } final int debug = debugTmp; centroids = new double[k][2]; for (int i = 0; i < k; i++) { // centroids[i][X] = minmaxlens[MIN][X] + (minmaxlens[LEN][X] * RANDOM.nextDouble()); // centroids[i][Y] = minmaxlens[MIN][Y] + (minmaxlens[LEN][Y] * RANDOM.nextDouble()); centroids[i][X] = minmaxlens[MIN][X] + (minmaxlens[LEN][X] / 2d); centroids[i][Y] = minmaxlens[MIN][Y] + (minmaxlens[LEN][Y] / 2d); } AbstractEKmeans.Listener listener = null; if (debug > 0) { listener = new AbstractEKmeans.Listener() { public void iteration(int iteration, int move) { statusBar.setText(MessageFormat.format("iteration {0} move {1}", iteration, move)); canvaPanel.repaint(); try { Thread.sleep(debug); } catch (InterruptedException e) { throw new RuntimeException(e); } } }; } eKmeans = new DoubleEKmeansExt(centroids, points, equal, DoubleEKmeans.EUCLIDEAN_DISTANCE_FUNCTION, listener); long time = System.currentTimeMillis(); eKmeans.run(); time = System.currentTimeMillis() - time; statusBar.setText(MessageFormat.format("EKmeans run in {0}ms", time)); canvaPanel.repaint(); } private void paint(Graphics g, int width, int height) { g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); if (minmaxlens == null) { return; } double widthRatio = (width - 6d) / minmaxlens[LEN][X]; double heightRatio = (height - 6d) / minmaxlens[LEN][Y]; if (points == null) { return; } g.setColor(Color.BLACK); for (int i = 0; i < points.length; i++) { int px = 3 + (int) (widthRatio * (points[i][X] - minmaxlens[MIN][X])); int py = 3 + (int) (heightRatio * (points[i][Y] - minmaxlens[MIN][Y])); g.drawRect(px - 2, py - 2, 4, 4); } if (eKmeans == null) { return; } int[] assignments = eKmeans.getAssignments(); int[] counts = eKmeans.getCounts(); int s = 225 / centroids.length; for (int i = 0; i < points.length; i++) { int assignment = assignments[i]; if (assignment == -1) { continue; } int cx = 3 + (int) (widthRatio * (centroids[assignment][X] - minmaxlens[MIN][X])); int cy = 3 + (int) (heightRatio * (centroids[assignment][Y] - minmaxlens[MIN][Y])); int px = 3 + (int) (widthRatio * (points[i][X] - minmaxlens[MIN][X])); int py = 3 + (int) (heightRatio * (points[i][Y] - minmaxlens[MIN][Y])); int c = assignment * s; g.setColor(new Color(c, c, c)); g.drawLine(cx, cy, px, py); } g.setColor(Color.GREEN); for (int i = 0; i < centroids.length; i++) { int cx = 3 + (int) (widthRatio * (centroids[i][X] - minmaxlens[MIN][X])); int cy = 3 + (int) (heightRatio * (centroids[i][Y] - minmaxlens[MIN][Y])); g.drawLine(cx, cy - 2, cx, cy + 2); g.drawLine(cx - 2, cy, cx + 2, cy); int count = counts[i]; g.drawString(String.valueOf(count), cx, cy); } } public static void main(String[] args) { new EKmeansGUI(); } }
pierredavidbelanger/ekmeans
src/main/java/ca/pjer/ekmeans/EKmeansGUI.java
4,548
//staticmap.openstreetmap.de/staticmap.php?center=" + (minmaxlens[MIN][X] + (minmaxlens[LEN][X] / 2d)) + "," + (minmaxlens[MIN][Y] + (minmaxlens[LEN][Y] / 2d)) + "&zoom=14&size=" + canvaPanel.getWidth() + "x" + canvaPanel.getHeight() + "&maptype=mapnik");
line_comment
nl
/* * This file is part of ekmeans. * * ekmeans 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. * * ekmeans 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 * Foobar. If not, see <http://www.gnu.org/licenses/>. * * ekmeans Copyright (C) 2012 Pierre-David Belanger <[email protected]> * * Contributor(s): Pierre-David Belanger <[email protected]> */ package ca.pjer.ekmeans; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Locale; import java.util.Random; public class EKmeansGUI { private class DoubleEKmeansExt extends DoubleEKmeans { public DoubleEKmeansExt(double[][] centroids, double[][] points, boolean equal, DoubleDistanceFunction doubleDistanceFunction, Listener listener) { super(centroids, points, equal, doubleDistanceFunction, listener); } public int[] getAssignments() { return assignments; } public int[] getCounts() { return counts; } } private static final int MIN = 0; private static final int MAX = 1; private static final int LEN = 2; private static final int X = 0; private static final int Y = 1; private static final int RESOLUTION = 300; private static final Random RANDOM = new Random(System.currentTimeMillis()); private JToolBar toolBar; private JTextField nTextField; private JTextField kTextField; private JCheckBox equalCheckBox; private JTextField debugTextField; private JPanel canvaPanel; private JLabel statusBar; private double[][] centroids = null; private double[][] points = null; private double[][] minmaxlens = null; private DoubleEKmeansExt eKmeans = null; private String[] lines = null; public EKmeansGUI() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setMinimumSize(new Dimension(RESOLUTION + 100, RESOLUTION + 100)); frame.setPreferredSize(new Dimension(RESOLUTION * 2, RESOLUTION * 2)); JPanel contentPanel = new JPanel(); contentPanel.setLayout(new BorderLayout()); frame.setContentPane(contentPanel); toolBar = new JToolBar(); toolBar.setFloatable(false); contentPanel.add(toolBar, BorderLayout.NORTH); JButton csvImportButton = new JButton(); csvImportButton.setAction(new AbstractAction(" Import CSV ") { public void actionPerformed(ActionEvent ae) { csvImport(); } }); toolBar.add(csvImportButton); JButton csvExportButton = new JButton(); csvExportButton.setAction(new AbstractAction(" Export CSV ") { public void actionPerformed(ActionEvent ae) { csvExport(); } }); toolBar.add(csvExportButton); JLabel nLabel = new JLabel("n:"); toolBar.add(nLabel); nTextField = new JTextField("1000"); toolBar.add(nTextField); JButton randomButton = new JButton(); randomButton.setAction(new AbstractAction(" Random ") { public void actionPerformed(ActionEvent ae) { random(); } }); toolBar.add(randomButton); JLabel kLabel = new JLabel("k:"); toolBar.add(kLabel); kTextField = new JTextField("5"); toolBar.add(kTextField); JLabel equalLabel = new JLabel("equal:"); toolBar.add(equalLabel); equalCheckBox = new JCheckBox(""); toolBar.add(equalCheckBox); JLabel debugLabel = new JLabel("debug:"); toolBar.add(debugLabel); debugTextField = new JTextField("0"); toolBar.add(debugTextField); JButton runButton = new JButton(); runButton.setAction(new AbstractAction(" Start ") { public void actionPerformed(ActionEvent ae) { start(); } }); toolBar.add(runButton); canvaPanel = new JPanel() { @Override public void paint(Graphics g) { EKmeansGUI.this.paint(g, getWidth(), getHeight()); } }; contentPanel.add(canvaPanel, BorderLayout.CENTER); statusBar = new JLabel(" "); contentPanel.add(statusBar, BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } private void enableToolBar(boolean enabled) { for (Component c : toolBar.getComponents()) { c.setEnabled(enabled); } } private void csvImport() { enableToolBar(false); eKmeans = null; lines = null; try { JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showOpenDialog(toolBar); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } minmaxlens = new double[][]{ {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}, {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY}, {0d, 0d} }; java.util.List points = new ArrayList(); java.util.List lines = new ArrayList(); BufferedReader reader = new BufferedReader(new FileReader(chooser.getSelectedFile())); String line; while ((line = reader.readLine()) != null) { lines.add(line); String[] pointString = line.split(","); double[] point = new double[2]; point[X] = Double.parseDouble(pointString[X].trim()); point[Y] = Double.parseDouble(pointString[Y].trim()); System.out.println(point[X] + ", " + point[Y]); points.add(point); if (point[X] < minmaxlens[MIN][X]) { minmaxlens[MIN][X] = point[X]; } if (point[Y] < minmaxlens[MIN][Y]) { minmaxlens[MIN][Y] = point[Y]; } if (point[X] > minmaxlens[MAX][X]) { minmaxlens[MAX][X] = point[X]; } if (point[Y] > minmaxlens[MAX][Y]) { minmaxlens[MAX][Y] = point[Y]; } } minmaxlens[LEN][X] = minmaxlens[MAX][X] - minmaxlens[MIN][X]; minmaxlens[LEN][Y] = minmaxlens[MAX][Y] - minmaxlens[MIN][Y]; reader.close(); this.points = (double[][]) points.toArray(new double[points.size()][]); nTextField.setText(String.valueOf(this.points.length)); this.lines = (String[]) lines.toArray(new String[lines.size()]); } catch (Exception e) { e.printStackTrace(System.err); } finally { canvaPanel.repaint(); enableToolBar(true); } } private void csvExport() { if (eKmeans == null) { return; } enableToolBar(false); try { JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showSaveDialog(toolBar); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(chooser.getSelectedFile()))); double[][] points = this.points; int[] assignments = eKmeans.getAssignments(); if (lines != null) { for (int i = 0; i < points.length; i++) { writer.printf(Locale.ENGLISH, "%d,%s%n", assignments[i], lines[i]); } } else { for (int i = 0; i < points.length; i++) { writer.printf(Locale.ENGLISH, "%d,%f,%f%n", assignments[i], points[i][X], points[i][Y]); } } writer.flush(); writer.close(); } catch (Exception e) { e.printStackTrace(System.err); } finally { canvaPanel.repaint(); enableToolBar(true); } } private void random() { enableToolBar(false); eKmeans = null; lines = null; int n = Integer.parseInt(nTextField.getText()); points = new double[n][2]; minmaxlens = new double[][]{ {Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY}, {Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY}, {0d, 0d} }; for (int i = 0; i < n; i++) { points[i][X] = RANDOM.nextDouble(); points[i][Y] = RANDOM.nextDouble(); if (points[i][X] < minmaxlens[MIN][X]) { minmaxlens[MIN][X] = points[i][X]; } if (points[i][Y] < minmaxlens[MIN][Y]) { minmaxlens[MIN][Y] = points[i][Y]; } if (points[i][X] > minmaxlens[MAX][X]) { minmaxlens[MAX][X] = points[i][X]; } if (points[i][Y] > minmaxlens[MAX][Y]) { minmaxlens[MAX][Y] = points[i][Y]; } } minmaxlens[LEN][X] = minmaxlens[MAX][X] - minmaxlens[MIN][X]; minmaxlens[LEN][Y] = minmaxlens[MAX][Y] - minmaxlens[MIN][Y]; canvaPanel.repaint(); enableToolBar(true); } private void start() { if (points == null) { random(); } new Thread(new Runnable() { public void run() { enableToolBar(false); try { EKmeansGUI.this.run(); } finally { enableToolBar(true); } } }).start(); } private void run() { try { URL url = new URL("http://staticmap.openstreetmap.de/staticmap.php?center=" +<SUF> System.out.println("url:" + url); } catch (MalformedURLException e) { e.printStackTrace(); } int k = Integer.parseInt(kTextField.getText()); boolean equal = equalCheckBox.isSelected(); int debugTmp = 0; try { debugTmp = Integer.parseInt(debugTextField.getText()); } catch (NumberFormatException ignore) { } final int debug = debugTmp; centroids = new double[k][2]; for (int i = 0; i < k; i++) { // centroids[i][X] = minmaxlens[MIN][X] + (minmaxlens[LEN][X] * RANDOM.nextDouble()); // centroids[i][Y] = minmaxlens[MIN][Y] + (minmaxlens[LEN][Y] * RANDOM.nextDouble()); centroids[i][X] = minmaxlens[MIN][X] + (minmaxlens[LEN][X] / 2d); centroids[i][Y] = minmaxlens[MIN][Y] + (minmaxlens[LEN][Y] / 2d); } AbstractEKmeans.Listener listener = null; if (debug > 0) { listener = new AbstractEKmeans.Listener() { public void iteration(int iteration, int move) { statusBar.setText(MessageFormat.format("iteration {0} move {1}", iteration, move)); canvaPanel.repaint(); try { Thread.sleep(debug); } catch (InterruptedException e) { throw new RuntimeException(e); } } }; } eKmeans = new DoubleEKmeansExt(centroids, points, equal, DoubleEKmeans.EUCLIDEAN_DISTANCE_FUNCTION, listener); long time = System.currentTimeMillis(); eKmeans.run(); time = System.currentTimeMillis() - time; statusBar.setText(MessageFormat.format("EKmeans run in {0}ms", time)); canvaPanel.repaint(); } private void paint(Graphics g, int width, int height) { g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); if (minmaxlens == null) { return; } double widthRatio = (width - 6d) / minmaxlens[LEN][X]; double heightRatio = (height - 6d) / minmaxlens[LEN][Y]; if (points == null) { return; } g.setColor(Color.BLACK); for (int i = 0; i < points.length; i++) { int px = 3 + (int) (widthRatio * (points[i][X] - minmaxlens[MIN][X])); int py = 3 + (int) (heightRatio * (points[i][Y] - minmaxlens[MIN][Y])); g.drawRect(px - 2, py - 2, 4, 4); } if (eKmeans == null) { return; } int[] assignments = eKmeans.getAssignments(); int[] counts = eKmeans.getCounts(); int s = 225 / centroids.length; for (int i = 0; i < points.length; i++) { int assignment = assignments[i]; if (assignment == -1) { continue; } int cx = 3 + (int) (widthRatio * (centroids[assignment][X] - minmaxlens[MIN][X])); int cy = 3 + (int) (heightRatio * (centroids[assignment][Y] - minmaxlens[MIN][Y])); int px = 3 + (int) (widthRatio * (points[i][X] - minmaxlens[MIN][X])); int py = 3 + (int) (heightRatio * (points[i][Y] - minmaxlens[MIN][Y])); int c = assignment * s; g.setColor(new Color(c, c, c)); g.drawLine(cx, cy, px, py); } g.setColor(Color.GREEN); for (int i = 0; i < centroids.length; i++) { int cx = 3 + (int) (widthRatio * (centroids[i][X] - minmaxlens[MIN][X])); int cy = 3 + (int) (heightRatio * (centroids[i][Y] - minmaxlens[MIN][Y])); g.drawLine(cx, cy - 2, cx, cy + 2); g.drawLine(cx - 2, cy, cx + 2, cy); int count = counts[i]; g.drawString(String.valueOf(count), cx, cy); } } public static void main(String[] args) { new EKmeansGUI(); } }
73622_1
package bank.bankieren; import centralebank.ICentraleBank; import fontys.observer.Publisher; import fontys.observer.RemotePropertyListener; import fontys.util.*; import java.rmi.RemoteException; /** * @author 871059 * */ public interface IBank extends Publisher, RemotePropertyListener { /** * creatie van een nieuwe bankrekening; het gegenereerde bankrekeningnummer * is identificerend voor de nieuwe bankrekening; als de klant * geidentificeerd door naam en plaats nog niet bestaat wordt er ook een * nieuwe klant aangemaakt * * @param naam * van de eigenaar van de nieuwe bankrekening * @param plaats * de woonplaats van de eigenaar van de nieuwe bankrekening * @return -1 zodra naam of plaats een lege string of rekeningnummer niet * door centrale kon worden vrijgegeven en anders het nummer van de * gecreeerde bankrekening */ int openRekening(String naam, String plaats) throws RemoteException; /** * er wordt bedrag overgemaakt van de bankrekening met nummer bron naar de * bankrekening met nummer bestemming * * @param bron * @param bestemming * ongelijk aan bron * @param bedrag * is groter dan 0 * @return <b>true</b> als de overmaking is gelukt, anders <b>false</b> * @throws NumberDoesntExistException * als een van de twee bankrekeningnummers onbekend is */ boolean maakOver(int bron, int bestemming, Money bedrag) throws NumberDoesntExistException, RemoteException; /** * @param nr * @return de bankrekening met nummer nr mits bij deze bank bekend, anders null */ IRekening getRekening(int nr) throws RemoteException; /** * @return de naam van deze bank */ String getName() throws RemoteException; /** * Methode om de centrale bank te wijzigen * @throws RemoteException */ void setCentraleBank(ICentraleBank centraleBank) throws RemoteException; /** * @return Centrale bank die bij de bank hoort * @throws RemoteException */ public ICentraleBank getCentraleBank() throws RemoteException; /** * Voeg listener aan publisher * @param listener * @param property * @throws RemoteException * Als server niet kan worden gevonden */ public void addListener(RemotePropertyListener listener, String property) throws RemoteException; /** * Voeg listener aan publisher * @param listener * @param property * @throws RemoteException * Als server niet kan worden gevonden */ public void removeListener(RemotePropertyListener listener, String property) throws RemoteException; public void muteerCentraal(int reknr, Money money) throws RemoteException; }
pieter888/fontys-gso-32
BankierenNoObserver/src/bank/bankieren/IBank.java
876
/** * creatie van een nieuwe bankrekening; het gegenereerde bankrekeningnummer * is identificerend voor de nieuwe bankrekening; als de klant * geidentificeerd door naam en plaats nog niet bestaat wordt er ook een * nieuwe klant aangemaakt * * @param naam * van de eigenaar van de nieuwe bankrekening * @param plaats * de woonplaats van de eigenaar van de nieuwe bankrekening * @return -1 zodra naam of plaats een lege string of rekeningnummer niet * door centrale kon worden vrijgegeven en anders het nummer van de * gecreeerde bankrekening */
block_comment
nl
package bank.bankieren; import centralebank.ICentraleBank; import fontys.observer.Publisher; import fontys.observer.RemotePropertyListener; import fontys.util.*; import java.rmi.RemoteException; /** * @author 871059 * */ public interface IBank extends Publisher, RemotePropertyListener { /** * creatie van een<SUF>*/ int openRekening(String naam, String plaats) throws RemoteException; /** * er wordt bedrag overgemaakt van de bankrekening met nummer bron naar de * bankrekening met nummer bestemming * * @param bron * @param bestemming * ongelijk aan bron * @param bedrag * is groter dan 0 * @return <b>true</b> als de overmaking is gelukt, anders <b>false</b> * @throws NumberDoesntExistException * als een van de twee bankrekeningnummers onbekend is */ boolean maakOver(int bron, int bestemming, Money bedrag) throws NumberDoesntExistException, RemoteException; /** * @param nr * @return de bankrekening met nummer nr mits bij deze bank bekend, anders null */ IRekening getRekening(int nr) throws RemoteException; /** * @return de naam van deze bank */ String getName() throws RemoteException; /** * Methode om de centrale bank te wijzigen * @throws RemoteException */ void setCentraleBank(ICentraleBank centraleBank) throws RemoteException; /** * @return Centrale bank die bij de bank hoort * @throws RemoteException */ public ICentraleBank getCentraleBank() throws RemoteException; /** * Voeg listener aan publisher * @param listener * @param property * @throws RemoteException * Als server niet kan worden gevonden */ public void addListener(RemotePropertyListener listener, String property) throws RemoteException; /** * Voeg listener aan publisher * @param listener * @param property * @throws RemoteException * Als server niet kan worden gevonden */ public void removeListener(RemotePropertyListener listener, String property) throws RemoteException; public void muteerCentraal(int reknr, Money money) throws RemoteException; }
19056_6
package bozels.gui.panels; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.GroupLayout.ParallelGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import bozels.gui.actions.BooleanValueSelectAction; import bozels.gui.basicComponents.AutoJLabel; import bozels.gui.basicComponents.ColorButton; import bozels.gui.basicComponents.coloringTextField.DoubleValueTextField; import bozels.gui.resourceModel.ResourceTracker; import bozels.gui.resourceModel.guiColorModel.GUIColorModel; import bozels.gui.resourceModel.localeConstant.LocaleConstant; import bozels.physicsModel.material.Material; import bozels.superModel.SuperModel; import bozels.valueWrappers.Value; import bozels.visualisatie.gameColorModel.GameColorModel; /** * Bozels * * Door: * Pieter Vander Vennet * 1ste Bachelor Informatica * Universiteit Gent * */ public class OneMaterialEditorPanel extends JPanel { private static final long serialVersionUID = 1L; private final GUIColorModel colorSettings; public OneMaterialEditorPanel(final SuperModel supM, final Material mat, boolean showBreakable) { final ResourceTracker tracker = supM.getResourceModel(); colorSettings = supM.getResourceModel().getGuiColorModel(); // \\//\\//\\//\\ LABELS //\\//\\//\\//\\ JLabel density = new AutoJLabel(tracker, LocaleConstant.DENSITY); JLabel restit = new AutoJLabel(tracker, LocaleConstant.RESTITUTION); JLabel friction = new AutoJLabel(tracker, LocaleConstant.FRICTION); JLabel color = new AutoJLabel(tracker, LocaleConstant.COLOR); JLabel empty = new JLabel(); JLabel powerThrs = new AutoJLabel(tracker, LocaleConstant.POWER_THRESHOLD); JLabel strength = new AutoJLabel(tracker, LocaleConstant.STRENGTH); JLabel sleepingColor = new AutoJLabel(tracker, LocaleConstant.SLEEPING_COLOR); // \\//\\//\\//\\ COlor chooser //\\//\\//\\//\\ GameColorModel cm = supM.getGameColorModel(); LocaleConstant name = mat.getMaterialName(); int key = mat.getColorKey(); JButton colorPicker = new ColorButton(supM, name, null, cm.getColorValue(key)); JButton sleepingColorPicker = new ColorButton(supM, name, null , cm.getSleepingColorValue(key)); // \\//\\//\\//\\ FIELDS //\\//\\//\\//\\ JTextField dens = createField(mat.getDensitValue()); JTextField rest = createField(mat.getRestitutionValue()); JTextField frict = createField(mat.getFrictionValue()); JTextField powThr = createField(mat.getPowerThresholdValue()); JTextField str = createField(mat.getStrengthValue()); // \\//\\//\\//\\ Checkbox //\\//\\//\\//\\ BooleanValueSelectAction sw = new BooleanValueSelectAction(mat.getCanBreak(), LocaleConstant.BREAKABLE, tracker); sw.getSwitchesWith().add(powThr); sw.getSwitchesWith().add(str); sw.revalidate(); JCheckBox breakable = new JCheckBox(sw); // \\//\\//\\//\\ LAYOUT //\\//\\//\\//\\ GroupLayout l = new GroupLayout(this); this.setLayout(l); /* * VERANTWOORDING: * * Hier een if-else voor de layout is inderdaad lelijk. * Ik heb echter gekozen om deze hier te gebruiken, * omdat op deze manier de layout van het linker- en rechterstuk dezelfde layout kunnen gebruiken. * * Op deze manier zullen de layouts altijd mooi samenblijven, hoewel dit minder elegant is naar * klassenstructuur toe. * */ if(showBreakable){ l.setHorizontalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.TRAILING, density,restit, friction, color)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, dens, rest, frict, colorPicker)) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(createPar(l, Alignment.TRAILING, empty, powerThrs, strength, sleepingColor)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, breakable, powThr, str, sleepingColorPicker)) ); l.setVerticalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.BASELINE, density, dens, empty, breakable)) .addGroup(createPar(l, Alignment.BASELINE, restit, rest, powerThrs, powThr)) .addGroup(createPar(l, Alignment.BASELINE, friction, frict, strength, str)) .addGroup(createPar(l, Alignment.BASELINE, color, colorPicker, sleepingColor, sleepingColorPicker) ) .addContainerGap() ); }else{ l.setHorizontalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.TRAILING, density,restit, friction, color)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, dens, rest, frict, colorPicker)) ); l.setVerticalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.BASELINE, density, dens)) .addGroup(createPar(l, Alignment.BASELINE, restit, rest)) .addGroup(createPar(l, Alignment.BASELINE, friction, frict)) .addGroup(createPar(l, Alignment.BASELINE, color, colorPicker)) .addContainerGap()); } } private ParallelGroup createPar(GroupLayout l, Alignment al, JComponent... components){ ParallelGroup group = l.createParallelGroup(al); for (JComponent jComponent : components) { group.addComponent(jComponent); } return group; } private DoubleValueTextField createField(Value<Double> val){ return new DoubleValueTextField(colorSettings, val, 0, 10000, 10000); } }
pietervdvn/Bozels
src/bozels/gui/panels/OneMaterialEditorPanel.java
1,960
/* * VERANTWOORDING: * * Hier een if-else voor de layout is inderdaad lelijk. * Ik heb echter gekozen om deze hier te gebruiken, * omdat op deze manier de layout van het linker- en rechterstuk dezelfde layout kunnen gebruiken. * * Op deze manier zullen de layouts altijd mooi samenblijven, hoewel dit minder elegant is naar * klassenstructuur toe. * */
block_comment
nl
package bozels.gui.panels; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.GroupLayout.ParallelGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import bozels.gui.actions.BooleanValueSelectAction; import bozels.gui.basicComponents.AutoJLabel; import bozels.gui.basicComponents.ColorButton; import bozels.gui.basicComponents.coloringTextField.DoubleValueTextField; import bozels.gui.resourceModel.ResourceTracker; import bozels.gui.resourceModel.guiColorModel.GUIColorModel; import bozels.gui.resourceModel.localeConstant.LocaleConstant; import bozels.physicsModel.material.Material; import bozels.superModel.SuperModel; import bozels.valueWrappers.Value; import bozels.visualisatie.gameColorModel.GameColorModel; /** * Bozels * * Door: * Pieter Vander Vennet * 1ste Bachelor Informatica * Universiteit Gent * */ public class OneMaterialEditorPanel extends JPanel { private static final long serialVersionUID = 1L; private final GUIColorModel colorSettings; public OneMaterialEditorPanel(final SuperModel supM, final Material mat, boolean showBreakable) { final ResourceTracker tracker = supM.getResourceModel(); colorSettings = supM.getResourceModel().getGuiColorModel(); // \\//\\//\\//\\ LABELS //\\//\\//\\//\\ JLabel density = new AutoJLabel(tracker, LocaleConstant.DENSITY); JLabel restit = new AutoJLabel(tracker, LocaleConstant.RESTITUTION); JLabel friction = new AutoJLabel(tracker, LocaleConstant.FRICTION); JLabel color = new AutoJLabel(tracker, LocaleConstant.COLOR); JLabel empty = new JLabel(); JLabel powerThrs = new AutoJLabel(tracker, LocaleConstant.POWER_THRESHOLD); JLabel strength = new AutoJLabel(tracker, LocaleConstant.STRENGTH); JLabel sleepingColor = new AutoJLabel(tracker, LocaleConstant.SLEEPING_COLOR); // \\//\\//\\//\\ COlor chooser //\\//\\//\\//\\ GameColorModel cm = supM.getGameColorModel(); LocaleConstant name = mat.getMaterialName(); int key = mat.getColorKey(); JButton colorPicker = new ColorButton(supM, name, null, cm.getColorValue(key)); JButton sleepingColorPicker = new ColorButton(supM, name, null , cm.getSleepingColorValue(key)); // \\//\\//\\//\\ FIELDS //\\//\\//\\//\\ JTextField dens = createField(mat.getDensitValue()); JTextField rest = createField(mat.getRestitutionValue()); JTextField frict = createField(mat.getFrictionValue()); JTextField powThr = createField(mat.getPowerThresholdValue()); JTextField str = createField(mat.getStrengthValue()); // \\//\\//\\//\\ Checkbox //\\//\\//\\//\\ BooleanValueSelectAction sw = new BooleanValueSelectAction(mat.getCanBreak(), LocaleConstant.BREAKABLE, tracker); sw.getSwitchesWith().add(powThr); sw.getSwitchesWith().add(str); sw.revalidate(); JCheckBox breakable = new JCheckBox(sw); // \\//\\//\\//\\ LAYOUT //\\//\\//\\//\\ GroupLayout l = new GroupLayout(this); this.setLayout(l); /* * VERANTWOORDING: <SUF>*/ if(showBreakable){ l.setHorizontalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.TRAILING, density,restit, friction, color)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, dens, rest, frict, colorPicker)) .addPreferredGap(ComponentPlacement.UNRELATED) .addGroup(createPar(l, Alignment.TRAILING, empty, powerThrs, strength, sleepingColor)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, breakable, powThr, str, sleepingColorPicker)) ); l.setVerticalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.BASELINE, density, dens, empty, breakable)) .addGroup(createPar(l, Alignment.BASELINE, restit, rest, powerThrs, powThr)) .addGroup(createPar(l, Alignment.BASELINE, friction, frict, strength, str)) .addGroup(createPar(l, Alignment.BASELINE, color, colorPicker, sleepingColor, sleepingColorPicker) ) .addContainerGap() ); }else{ l.setHorizontalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.TRAILING, density,restit, friction, color)) .addPreferredGap(ComponentPlacement.RELATED) .addGroup(createPar(l, Alignment.LEADING, dens, rest, frict, colorPicker)) ); l.setVerticalGroup(l.createSequentialGroup() .addGroup(createPar(l, Alignment.BASELINE, density, dens)) .addGroup(createPar(l, Alignment.BASELINE, restit, rest)) .addGroup(createPar(l, Alignment.BASELINE, friction, frict)) .addGroup(createPar(l, Alignment.BASELINE, color, colorPicker)) .addContainerGap()); } } private ParallelGroup createPar(GroupLayout l, Alignment al, JComponent... components){ ParallelGroup group = l.createParallelGroup(al); for (JComponent jComponent : components) { group.addComponent(jComponent); } return group; } private DoubleValueTextField createField(Value<Double> val){ return new DoubleValueTextField(colorSettings, val, 0, 10000, 10000); } }
190670_19
package objprosjekt; import javafx.fxml.FXML; import javafx.scene.paint.Color; import javafx.scene.shape.Ellipse; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ToggleButton; import java.util.Hashtable; public class JourneyPlanController { @FXML private Ellipse NewYork, Oslo, CapeTown, Mumbai, Paris, London, Madrid, LosAngeles, Toronto, Rio, Reykjavik, Moscow, BuenosAires, Beijing, MexicoCity, Bogota, Sydney; @FXML private AnchorPane anker; @FXML private Canvas panel; @FXML private Button btnBack, btnNext, btnAdd, btnDelete, btnSave, btnLoad; @FXML private Label txtCurrentJourney, txtIndex; @FXML private ToggleButton autoToggle, btnSorted; private JourneyPlan travelPlan; private Hashtable<String, Ellipse> knapper; @FXML public void initialize() { // hva som skjer når man åpner applikasjnen openHash(); // åpner hashtable travelPlan = new JourneyPlan(knapper); // oppretter travelPlan med en ny JourneyPlan og tar inn valgte // destinasjoner travelPlan.setSorted(btnSorted.isSelected()); // legger inn i reiseplan om sortering er av eller på write(); buttonCheck(); draw(); } public void openHash() { knapper = new Hashtable<>(); knapper.put("NewYork", NewYork); knapper.put("Oslo", Oslo); knapper.put("CapeTown", CapeTown); knapper.put("Mumbai", Mumbai); knapper.put("Paris", Paris); knapper.put("London", London); knapper.put("Madrid", Madrid); knapper.put("LosAngeles", LosAngeles); knapper.put("Toronto", Toronto); knapper.put("Rio", Rio); knapper.put("Reykjavik", Reykjavik); knapper.put("Moscow", Moscow); knapper.put("BuenosAires", BuenosAires); knapper.put("Beijing", Beijing); knapper.put("MexicoCity", MexicoCity); knapper.put("Bogota", Bogota); knapper.put("Sydney", Sydney); } @FXML private void nextJourney() { // blar til neste reise travelPlan.next(); refresh(); // oppdater brukergrensesnitt } @FXML private void lastJourney() { // blar tilbake til forrige travelPlan.last(); refresh(); // oppdater brukergrensesnitt } @FXML private void newJourney() { travelPlan.setSorted(btnSorted.isSelected()); // setter sorteringsveri, true/false travelPlan.addJourney(); // lager ny reise refresh(); // oppdater brukergrensesnitt } @FXML private void deleteJourney() { travelPlan.setSorted(btnSorted.isSelected()); travelPlan.removeJourney(); refresh(); // oppdater brukergrensesnitt } @FXML private void pinEvent(MouseEvent e) { // ved trykk på knapp travelPlan.manageDestination(((Ellipse) e.getSource()).getId(), knapper); // kjører pinPressed i journey plan, henter // objektet og legger inn id til knapp og // knappehashtable refresh(); // oppdater brukergrensesnitt } private void refresh() { // oppdater brukergrensesnittet travelPlan.sort(btnSorted.isSelected()); write(); buttonCheck(); draw(); if (autoToggle.isSelected()) { // hvis automatisk lagring er aktivert travelPlan.save(); // vil lagring skje automatisk } } private void buttonCheck() { Ellipse[] btnArray = { NewYork, Oslo, CapeTown, Mumbai, Paris, London, Madrid, LosAngeles, Toronto, Rio, Reykjavik, Moscow, BuenosAires, Beijing, MexicoCity, Bogota, Sydney }; for (Ellipse k : btnArray) { if (travelPlan.getCurrentJourney().isIn(k.getId())) { // itererer over knapper inkludert i currentJourney // for å k.setFill(Color.GREEN); // markere de som er inkludert grønn } else { k.setFill(Color.RED); // resten er ubrukt, og røde } } if (travelPlan.getIndex(travelPlan.getCurrentJourney()) == 0) { // sjekker om indeks på currentJourney er første // element i reiseplan for å btnBack.setVisible(false); // fjerne 'back' på første journey } else { btnBack.setVisible(true); // vise ellers } if (travelPlan.getIndex(travelPlan.getCurrentJourney()) == travelPlan.getSize() - 1) { // sjekker om indeks på // currentJourney er // siste element i // reiseplan for å btnNext.setVisible(false); // fjerne 'next' på siste journey } else { btnNext.setVisible(true); // vise ellers } } private void write() { // oppretter String String tekst = "Reise: " + (travelPlan.getIndex(travelPlan.getCurrentJourney()) + 1) + "\nByer:\n"; // legger til alle byene etter rekkefølge for (int k = 0; k < travelPlan.getCurrentJourney().getSize(); k++) { tekst += (k + 1) + ": " + travelPlan.getCurrentJourney().getCity(k) + "\n"; } // sjekker at reisen har en distanse (slipper å regne avstand hvis den uansett // er 0) if (travelPlan.getCurrentJourney().getSize() > 1) { // hvis to eller flere byer tekst += "Total Reiseavstand " + travelPlan.getCurrentJourney().distance() + "Km"; } else {// hvis mindre enn to byer tekst += "Total Reiseavstand " + 0 + "Km"; } // setter label med String txtCurrentJourney.setText(tekst); txtIndex.setText(Integer.toString(travelPlan.getIndex(travelPlan.getCurrentJourney()) + 1)); } private void draw() { // lager GraphicContext GraphicsContext mal = panel.getGraphicsContext2D(); // clearer et rektangel like stort som hele canvas mal.clearRect(0, 0, panel.getWidth(), panel.getHeight()); // starter path mal.beginPath(); // seter linje mal.setLineWidth(3); mal.setStroke(Color.RED); // skriver linge for alle byer i den viste reisen for (int k = 0; k < travelPlan.getCurrentJourney().getSize() - 1; k++) { mal.moveTo(toEllipse(travelPlan.getCurrentJourney().getCity(k)).getLayoutX() - 6, // for å flytte penselen // til første destinasjon, // ikke (0,0) toEllipse(travelPlan.getCurrentJourney().getCity(k)).getLayoutY() + 25); mal.lineTo(toEllipse(travelPlan.getCurrentJourney().getCity(k + 1)).getLayoutX() - 6, // tegne fra forrige // til neste // destinasjon toEllipse(travelPlan.getCurrentJourney().getCity(k + 1)).getLayoutY() + 25); } mal.stroke(); } // tar inn string og returnerer tilsvarende ellipse // kunne brukt intern Journey toEllipse-funksjon, men da hadde koden over blitt // veldig // rotete private Ellipse toEllipse(String navn) throws NullPointerException { if (knapper.get(navn) != null) { return (knapper.get(navn)); } else { throw new IllegalArgumentException("den knappen finnes ikke (controller toEllipse)"); } } @FXML private void save() { // binder 'save' knapp med save funksjon travelPlan.save(); } @FXML private void load() { // binder 'load' knapp med initialize funksjon initialize(); refresh(); } @FXML private void btnSorterPressed() {// sorterer reiseplanen utifra om den skal være sortert eller ikke refresh(); } }
pilotCapp/object_oriented_project
src/main/java/objprosjekt/JourneyPlanController.java
2,614
// siste element i
line_comment
nl
package objprosjekt; import javafx.fxml.FXML; import javafx.scene.paint.Color; import javafx.scene.shape.Ellipse; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ToggleButton; import java.util.Hashtable; public class JourneyPlanController { @FXML private Ellipse NewYork, Oslo, CapeTown, Mumbai, Paris, London, Madrid, LosAngeles, Toronto, Rio, Reykjavik, Moscow, BuenosAires, Beijing, MexicoCity, Bogota, Sydney; @FXML private AnchorPane anker; @FXML private Canvas panel; @FXML private Button btnBack, btnNext, btnAdd, btnDelete, btnSave, btnLoad; @FXML private Label txtCurrentJourney, txtIndex; @FXML private ToggleButton autoToggle, btnSorted; private JourneyPlan travelPlan; private Hashtable<String, Ellipse> knapper; @FXML public void initialize() { // hva som skjer når man åpner applikasjnen openHash(); // åpner hashtable travelPlan = new JourneyPlan(knapper); // oppretter travelPlan med en ny JourneyPlan og tar inn valgte // destinasjoner travelPlan.setSorted(btnSorted.isSelected()); // legger inn i reiseplan om sortering er av eller på write(); buttonCheck(); draw(); } public void openHash() { knapper = new Hashtable<>(); knapper.put("NewYork", NewYork); knapper.put("Oslo", Oslo); knapper.put("CapeTown", CapeTown); knapper.put("Mumbai", Mumbai); knapper.put("Paris", Paris); knapper.put("London", London); knapper.put("Madrid", Madrid); knapper.put("LosAngeles", LosAngeles); knapper.put("Toronto", Toronto); knapper.put("Rio", Rio); knapper.put("Reykjavik", Reykjavik); knapper.put("Moscow", Moscow); knapper.put("BuenosAires", BuenosAires); knapper.put("Beijing", Beijing); knapper.put("MexicoCity", MexicoCity); knapper.put("Bogota", Bogota); knapper.put("Sydney", Sydney); } @FXML private void nextJourney() { // blar til neste reise travelPlan.next(); refresh(); // oppdater brukergrensesnitt } @FXML private void lastJourney() { // blar tilbake til forrige travelPlan.last(); refresh(); // oppdater brukergrensesnitt } @FXML private void newJourney() { travelPlan.setSorted(btnSorted.isSelected()); // setter sorteringsveri, true/false travelPlan.addJourney(); // lager ny reise refresh(); // oppdater brukergrensesnitt } @FXML private void deleteJourney() { travelPlan.setSorted(btnSorted.isSelected()); travelPlan.removeJourney(); refresh(); // oppdater brukergrensesnitt } @FXML private void pinEvent(MouseEvent e) { // ved trykk på knapp travelPlan.manageDestination(((Ellipse) e.getSource()).getId(), knapper); // kjører pinPressed i journey plan, henter // objektet og legger inn id til knapp og // knappehashtable refresh(); // oppdater brukergrensesnitt } private void refresh() { // oppdater brukergrensesnittet travelPlan.sort(btnSorted.isSelected()); write(); buttonCheck(); draw(); if (autoToggle.isSelected()) { // hvis automatisk lagring er aktivert travelPlan.save(); // vil lagring skje automatisk } } private void buttonCheck() { Ellipse[] btnArray = { NewYork, Oslo, CapeTown, Mumbai, Paris, London, Madrid, LosAngeles, Toronto, Rio, Reykjavik, Moscow, BuenosAires, Beijing, MexicoCity, Bogota, Sydney }; for (Ellipse k : btnArray) { if (travelPlan.getCurrentJourney().isIn(k.getId())) { // itererer over knapper inkludert i currentJourney // for å k.setFill(Color.GREEN); // markere de som er inkludert grønn } else { k.setFill(Color.RED); // resten er ubrukt, og røde } } if (travelPlan.getIndex(travelPlan.getCurrentJourney()) == 0) { // sjekker om indeks på currentJourney er første // element i reiseplan for å btnBack.setVisible(false); // fjerne 'back' på første journey } else { btnBack.setVisible(true); // vise ellers } if (travelPlan.getIndex(travelPlan.getCurrentJourney()) == travelPlan.getSize() - 1) { // sjekker om indeks på // currentJourney er // siste element<SUF> // reiseplan for å btnNext.setVisible(false); // fjerne 'next' på siste journey } else { btnNext.setVisible(true); // vise ellers } } private void write() { // oppretter String String tekst = "Reise: " + (travelPlan.getIndex(travelPlan.getCurrentJourney()) + 1) + "\nByer:\n"; // legger til alle byene etter rekkefølge for (int k = 0; k < travelPlan.getCurrentJourney().getSize(); k++) { tekst += (k + 1) + ": " + travelPlan.getCurrentJourney().getCity(k) + "\n"; } // sjekker at reisen har en distanse (slipper å regne avstand hvis den uansett // er 0) if (travelPlan.getCurrentJourney().getSize() > 1) { // hvis to eller flere byer tekst += "Total Reiseavstand " + travelPlan.getCurrentJourney().distance() + "Km"; } else {// hvis mindre enn to byer tekst += "Total Reiseavstand " + 0 + "Km"; } // setter label med String txtCurrentJourney.setText(tekst); txtIndex.setText(Integer.toString(travelPlan.getIndex(travelPlan.getCurrentJourney()) + 1)); } private void draw() { // lager GraphicContext GraphicsContext mal = panel.getGraphicsContext2D(); // clearer et rektangel like stort som hele canvas mal.clearRect(0, 0, panel.getWidth(), panel.getHeight()); // starter path mal.beginPath(); // seter linje mal.setLineWidth(3); mal.setStroke(Color.RED); // skriver linge for alle byer i den viste reisen for (int k = 0; k < travelPlan.getCurrentJourney().getSize() - 1; k++) { mal.moveTo(toEllipse(travelPlan.getCurrentJourney().getCity(k)).getLayoutX() - 6, // for å flytte penselen // til første destinasjon, // ikke (0,0) toEllipse(travelPlan.getCurrentJourney().getCity(k)).getLayoutY() + 25); mal.lineTo(toEllipse(travelPlan.getCurrentJourney().getCity(k + 1)).getLayoutX() - 6, // tegne fra forrige // til neste // destinasjon toEllipse(travelPlan.getCurrentJourney().getCity(k + 1)).getLayoutY() + 25); } mal.stroke(); } // tar inn string og returnerer tilsvarende ellipse // kunne brukt intern Journey toEllipse-funksjon, men da hadde koden over blitt // veldig // rotete private Ellipse toEllipse(String navn) throws NullPointerException { if (knapper.get(navn) != null) { return (knapper.get(navn)); } else { throw new IllegalArgumentException("den knappen finnes ikke (controller toEllipse)"); } } @FXML private void save() { // binder 'save' knapp med save funksjon travelPlan.save(); } @FXML private void load() { // binder 'load' knapp med initialize funksjon initialize(); refresh(); } @FXML private void btnSorterPressed() {// sorterer reiseplanen utifra om den skal være sortert eller ikke refresh(); } }
66474_39
package osbot_scripts.qp7.progress; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.osbot.rs07.api.map.Area; import org.osbot.rs07.api.map.Position; import osbot_scripts.framework.AccountStage; import osbot_scripts.framework.ClickObjectTask; import osbot_scripts.framework.DialogueTask; import osbot_scripts.framework.ItemOnObjectTask; import osbot_scripts.framework.PickupItemTask; import osbot_scripts.framework.WalkTask; import osbot_scripts.sections.total.progress.MainState; import osbot_scripts.task.Task; import osbot_scripts.taskhandling.TaskHandler; public class CookingsAssistant extends QuestStep { private List<Task> cookingAssistantTask = new ArrayList<Task>(); private Task currentTask; private static final List<Position> PATH_TO_COOK = new ArrayList<Position>( Arrays.asList(new Position(3235, 3218, 0), new Position(3227, 3218, 0), new Position(3217, 3218, 0), new Position(3214, 3218, 0), new Position(3214, 3210, 0), new Position(3208, 3210, 0), new Position(3210, 3213, 0))); private static final List<Position> PATH_TO_MILKING_COW = new ArrayList<Position>( Arrays.asList(new Position(3208, 3212, 0), new Position(3214, 3210, 0), new Position(3214, 3219, 0), new Position(3224, 3219, 0), new Position(3234, 3219, 0), new Position(3235, 3218, 0), new Position(3236, 3225, 0), new Position(3246, 3226, 0), new Position(3256, 3227, 0), new Position(3258, 3227, 0), new Position(3255, 3237, 0), new Position(3252, 3247, 0), new Position(3249, 3257, 0), new Position(3250, 3257, 0), new Position(3249, 3266, 0), new Position(3256, 3269, 0))); private static final Area MILKING_AREA = new Area(new int[][] { { 3253, 3255 }, { 3266, 3255 }, { 3266, 3297 }, { 3264, 3299 }, { 3262, 3299 }, { 3261, 3300 }, { 3257, 3300 }, { 3256, 3299 }, { 3241, 3299 }, { 3240, 3298 }, { 3240, 3296 }, { 3241, 3295 }, { 3241, 3294 }, { 3242, 3293 }, { 3242, 3290 }, { 3241, 3289 }, { 3241, 3288 }, { 3240, 3287 }, { 3240, 3285 }, { 3244, 3281 }, { 3244, 3280 }, { 3246, 3278 }, { 3249, 3278 }, { 3251, 3276 }, { 3251, 3274 }, { 3253, 3272 } }); private static final List<Position> PATH_TO_CHICKENS = new ArrayList<Position>( Arrays.asList(new Position(3255, 3266, 0), new Position(3249, 3267, 0), new Position(3244, 3274, 0), new Position(3239, 3283, 0), new Position(3238, 3285, 0), new Position(3239, 3294, 0), new Position(3230, 3299, 0), new Position(3230, 3299, 0))); private static final List<Position> PATH_TO_WHEAT_FIELD = new ArrayList<Position>( Arrays.asList(new Position(3233, 3293, 0), new Position(3238, 3296, 0), new Position(3239, 3286, 0), new Position(3240, 3276, 0), new Position(3240, 3276, 0), new Position(3242, 3266, 0), new Position(3243, 3260, 0), new Position(3233, 3260, 0), new Position(3223, 3260, 0), new Position(3215, 3260, 0), new Position(3214, 3270, 0), new Position(3213, 3280, 0), new Position(3213, 3280, 0), new Position(3203, 3281, 0), new Position(3193, 3282, 0), new Position(3184, 3284, 0), new Position(3174, 3285, 0), new Position(3164, 3286, 0), new Position(3162, 3287, 0), new Position(3159, 3296, 0), new Position(3158, 3299, 0))); private static final List<Position> PATH_TO_WINDMILL = new ArrayList<Position>( Arrays.asList(new Position(3162, 3287, 0), new Position(3166, 3291, 0), new Position(3167, 3300, 0), new Position(3169, 3307, 0))); private static final Area CHICKENS_AREA = new Area( new int[][] { { 3226, 3302 }, { 3225, 3301 }, { 3225, 3295 }, { 3231, 3295 }, { 3231, 3287 }, { 3237, 3287 }, { 3237, 3290 }, { 3238, 3291 }, { 3238, 3293 }, { 3237, 3294 }, { 3237, 3297 }, { 3238, 3298 }, { 3238, 3299 }, { 3238, 3300 }, { 3235, 3302 }, { 3226, 3302 } }); private static final Area COOKS_AREA = new Area(new int[][] { { 3205, 3217 }, { 3205, 3209 }, { 3215, 3209 }, { 3217, 3211 }, { 3217, 3212 }, { 3213, 3212 }, { 3213, 3218 }, { 3205, 3218 } }); private static final Area WHEAT_AREA = new Area( new int[][] { { 3153, 3305 }, { 3153, 3297 }, { 3155, 3295 }, { 3157, 3295 }, { 3162, 3290 }, { 3164, 3290 }, { 3165, 3291 }, { 3165, 3292 }, { 3164, 3293 }, { 3164, 3296 }, { 3165, 3297 }, { 3165, 3299 }, { 3162, 3302 }, { 3162, 3303 }, { 3160, 3305 }, { 3160, 3306 }, { 3159, 3307 }, { 3158, 3307 }, { 3157, 3308 }, { 3155, 3308 }, { 3153, 3306 }, { 3153, 3305 } }); private static final Position FLOWER_POSITION = new Position(3165, 3308, 2); private static final Area FLOWER_AREA = new Area(new int[][] { { 3164, 3308 }, { 3166, 3310 }, { 3168, 3310 }, { 3170, 3308 }, { 3170, 3306 }, { 3168, 3304 }, { 3166, 3304 }, { 3164, 3306 }, { 3164, 3308 } }) .setPlane(2); private static final Area WHEAT_FLOOR_1 = new Area(new int[][] { { 3166, 3310 }, { 3168, 3310 }, { 3170, 3308 }, { 3170, 3306 }, { 3168, 3304 }, { 3165, 3304 }, { 3164, 3306 }, { 3164, 3308 } }).setPlane(1); private static final Area WHEAT_FLOOR_2 = new Area(new int[][] { { 3166, 3310 }, { 3168, 3310 }, { 3170, 3308 }, { 3170, 3306 }, { 3168, 3304 }, { 3165, 3304 }, { 3164, 3306 }, { 3164, 3308 } }).setPlane(2); private static final Area WHEAT_FLOOR_0 = new Area(new int[][] { { 3166, 3310 }, { 3168, 3310 }, { 3170, 3308 }, { 3170, 3306 }, { 3168, 3304 }, { 3165, 3304 }, { 3164, 3306 }, { 3164, 3308 } }).setPlane(0); private static final Area BASEMENT_AREA = new Area( new int[][] { { 3207, 9614 }, { 3207, 9627 }, { 3221, 9627 }, { 3221, 9614 } }); private static final List<Position> PATH_TO_COOK_FROM_MILL = new ArrayList<Position>( Arrays.asList(new Position(3166, 3301, 0), new Position(3166, 3291, 0), new Position(3166, 3287, 0), new Position(3176, 3285, 0), new Position(3186, 3283, 0), new Position(3186, 3283, 0), new Position(3196, 3281, 0), new Position(3206, 3279, 0), new Position(3208, 3278, 0), new Position(3214, 3270, 0), new Position(3216, 3268, 0), new Position(3216, 3258, 0), new Position(3216, 3250, 0), new Position(3222, 3242, 0), new Position(3227, 3234, 0), new Position(3231, 3225, 0), new Position(3235, 3216, 0), new Position(3225, 3217, 0), new Position(3218, 3218, 0), new Position(3215, 3219, 0), new Position(3214, 3213, 0), new Position(3214, 3209, 0), new Position(3209, 3209, 0), new Position(3208, 3214, 0))); private static final Position POT_ON_MACHINE = new Position(3167, 3305, 0); private static final Position BUCKET_POSITION_IN_BASEMENT = new Position(3215, 9624, 0); private static final int QUEST_CONFIG = 29; public CookingsAssistant(int questStartNpc, int configQuestId) { super(questStartNpc, configQuestId, AccountStage.QUEST_COOK_ASSISTANT); // TODO Auto-generated constructor stub } private String scriptName = this.getClass().getSimpleName(); /** */ public void decideOnStartTask() { if (getCurrentTask() != null) { return; } // The task system for (Task task : getCookingAssistantTask()) { if (getCurrentTask() == null && getQuestProgress() == task.requiredConfigQuestStep()) { setCurrentTask(task); log("set task to: " + getCurrentTask()); } else { log("is not in quest step for: " + task.getClass().getSimpleName() + " step: " + task.requiredConfigQuestStep() + " curr: " + getQuestProgress()); } } } @Override public void onStart() { getCookingAssistantTask() .add(new WalkTask("walk to cook", 0, QUEST_CONFIG, getBot().getMethods(), PATH_TO_COOK, COOKS_AREA)); getCookingAssistantTask().add(new DialogueTask("talk with cook", 0, QUEST_CONFIG, getBot().getMethods(), COOKS_AREA, 4626, new String[] { "What's wrong?", "I'm always happy to help a cook in distress", "I'll get right on it", "Actually, I know where to find this stuff." })); if (!getInventory().contains("Bucket of milk")) { getCookingAssistantTask().add(new WalkTask("walk cow milking", 1, QUEST_CONFIG, getBot().getMethods(), PATH_TO_MILKING_COW, MILKING_AREA)); getCookingAssistantTask().add(new ClickObjectTask("fill bucket", 1, QUEST_CONFIG, getBot().getMethods(), MILKING_AREA, 8689, "Milk", "Bucket of milk")); } if (!getInventory().contains("Egg")) { getCookingAssistantTask().add(new WalkTask("walk to chickens", 1, QUEST_CONFIG, getBot().getMethods(), PATH_TO_CHICKENS, CHICKENS_AREA)); getCookingAssistantTask().add( new PickupItemTask("pickup egg", 1, QUEST_CONFIG, getBot().getMethods(), CHICKENS_AREA, "Egg")); } if (!getInventory().contains("Pot of flour")) { getCookingAssistantTask().add(new WalkTask("path to wheat field", 1, QUEST_CONFIG, getBot().getMethods(), PATH_TO_WHEAT_FIELD, WHEAT_AREA)); if (!getInventory().contains("Grain")) { getCookingAssistantTask().add(new ClickObjectTask("take wheat", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_AREA, 15506, "Pick", "Grain")); } getCookingAssistantTask().add(new WalkTask("path to wind mill", 1, QUEST_CONFIG, getBot().getMethods(), PATH_TO_WINDMILL, WHEAT_FLOOR_0)); // go up 2 ladders getCookingAssistantTask().add(new ClickObjectTask("climb up 1", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_0, 12964, "Climb-up", WHEAT_FLOOR_1)); getCookingAssistantTask().add(new ClickObjectTask("climb up 2", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_1, 12965, "Climb-up", WHEAT_FLOOR_2)); getCookingAssistantTask().add(new ItemOnObjectTask("grain on machine", 1, QUEST_CONFIG, getBot().getMethods(), FLOWER_AREA, 24961, "Grain")); getCookingAssistantTask().add(new ClickObjectTask("operate", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_2, 24964, 24967)); // go down 2 ladders getCookingAssistantTask().add(new ClickObjectTask("climb down 1", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_2, 12966, "Climb-down", WHEAT_FLOOR_1)); getCookingAssistantTask().add(new ClickObjectTask("climb down 0", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_1, 12965, "Climb-down", WHEAT_FLOOR_0)); getCookingAssistantTask().add(new ClickObjectTask("get flour to pot", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_0, 1781, "Pot of flour")); } getCookingAssistantTask().add(new WalkTask("path to cook from mill", 1, QUEST_CONFIG, getBot().getMethods(), PATH_TO_COOK_FROM_MILL, COOKS_AREA)); getCookingAssistantTask().add(new DialogueTask("talk with cook final", 1, QUEST_CONFIG, getBot().getMethods(), COOKS_AREA, 4626, new String[] { "" })); } @Override public void onLoop() throws InterruptedException { // TODO Auto-generated method stub // log(getQuestProgress()); // log(progress); // // switch (getQuestProgress()) { // case 0: // // Starting quest // // if (walkToPosition(PATH_TO_COOK, COOKS_AREA) && talkWithNpc()) { // log("talked with npc"); // } // // break; // // case 1: // // Progress on starting up // if (progress == CooksAssistantSteps.TALK_WITH_COOK) { // progress = CooksAssistantSteps.GOING_TO_BASEMENT_FOR_BUCKET; // } // // // Started quest // if (progress == CooksAssistantSteps.GOING_TO_BASEMENT_FOR_BUCKET) { // if (pickupBucket()) { // progress = CooksAssistantSteps.GETTING_BUCKET_OF_MILK; // log("picked up bucket"); // if (walkUpToCook()) { // log("walked back to cook"); // } // } // } else if (progress == CooksAssistantSteps.GETTING_BUCKET_OF_MILK) { // if (getBucketOfMilk()) { // log("got bucket of milk"); // } // } // break; // // case 2: // // Finished quest // break; // // default: // break; // } } /** * * @return */ private boolean walkUpToCook() { if (BASEMENT_AREA.contains(myPlayer())) { if (clickObjectToArea("Ladder", COOKS_AREA)) { return clickObjectToArea("Ladder", COOKS_AREA); } } else { return walkToPosition(PATH_TO_COOK, COOKS_AREA); } return false; } /** * Retreives a bucket of milk * * @return */ private boolean getBucketOfMilk() { if (getInventory().contains("Bucket of milk")) { return true; } if (walkToPosition(PATH_TO_MILKING_COW, MILKING_AREA)) { return clickObject(8689, "Bucket of milk", "Milk"); } return false; } /** * Picks up the bucket in the basement * * @return */ // private boolean pickupBucket() { // // je hebt al een bucket // if (getInventory().contains("Bucket")) { // return true; // } // progress = CooksAssistantSteps.GOING_TO_BASEMENT_FOR_BUCKET; // // // wanneer niet in de basement ga er naartoe // if (!getInventory().contains("Bucket")) { // if (!BASEMENT_AREA.contains(myPlayer())) { // if (walkToPosition(PATH_TO_COOK, COOKS_AREA) && clickObjectToArea(14880, // BASEMENT_AREA)) { // log("going down to basement"); // } // } // // // wanneer wel in de basement ga het oppakken // else if (BASEMENT_AREA.contains(myPlayer())) { // if (getWalking().walk(BUCKET_POSITION_IN_BASEMENT)) { // if (pickupItem(1925)) { // log("trying to pickup"); // Sleep.sleepUntil(() -> getInventory().contains("Bucket"), 10000); // return true; // } else { // // wanneer er geen bucket is, wachten op de bucket // log("waiting for bucket spawn..."); // Sleep.sleepUntil(() -> getGroundItems().closest("Bucket") != null, 60000, // 2000); // return false; // } // } // } // } // return false; // } @Override public boolean isCompleted() { // TODO Auto-generated method stub return false; } @Override public MainState getNextMainState() { // TODO Auto-generated method stub return null; } /** * @return the cookingAssistantTask */ public List<Task> getCookingAssistantTask() { return cookingAssistantTask; } /** * @param cookingAssistantTask * the cookingAssistantTask to set */ public void setCookingAssistantTask(List<Task> cookingAssistantTask) { this.cookingAssistantTask = cookingAssistantTask; } /** * @return the currentTask */ public Task getCurrentTask() { return currentTask; } /** * @param currentTask * the currentTask to set */ public void setCurrentTask(Task currentTask) { this.currentTask = currentTask; } }
pim97/osbot_scripts_tasks
src/osbot_scripts/qp7/progress/CookingsAssistant.java
5,782
// // wanneer er geen bucket is, wachten op de bucket
line_comment
nl
package osbot_scripts.qp7.progress; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.osbot.rs07.api.map.Area; import org.osbot.rs07.api.map.Position; import osbot_scripts.framework.AccountStage; import osbot_scripts.framework.ClickObjectTask; import osbot_scripts.framework.DialogueTask; import osbot_scripts.framework.ItemOnObjectTask; import osbot_scripts.framework.PickupItemTask; import osbot_scripts.framework.WalkTask; import osbot_scripts.sections.total.progress.MainState; import osbot_scripts.task.Task; import osbot_scripts.taskhandling.TaskHandler; public class CookingsAssistant extends QuestStep { private List<Task> cookingAssistantTask = new ArrayList<Task>(); private Task currentTask; private static final List<Position> PATH_TO_COOK = new ArrayList<Position>( Arrays.asList(new Position(3235, 3218, 0), new Position(3227, 3218, 0), new Position(3217, 3218, 0), new Position(3214, 3218, 0), new Position(3214, 3210, 0), new Position(3208, 3210, 0), new Position(3210, 3213, 0))); private static final List<Position> PATH_TO_MILKING_COW = new ArrayList<Position>( Arrays.asList(new Position(3208, 3212, 0), new Position(3214, 3210, 0), new Position(3214, 3219, 0), new Position(3224, 3219, 0), new Position(3234, 3219, 0), new Position(3235, 3218, 0), new Position(3236, 3225, 0), new Position(3246, 3226, 0), new Position(3256, 3227, 0), new Position(3258, 3227, 0), new Position(3255, 3237, 0), new Position(3252, 3247, 0), new Position(3249, 3257, 0), new Position(3250, 3257, 0), new Position(3249, 3266, 0), new Position(3256, 3269, 0))); private static final Area MILKING_AREA = new Area(new int[][] { { 3253, 3255 }, { 3266, 3255 }, { 3266, 3297 }, { 3264, 3299 }, { 3262, 3299 }, { 3261, 3300 }, { 3257, 3300 }, { 3256, 3299 }, { 3241, 3299 }, { 3240, 3298 }, { 3240, 3296 }, { 3241, 3295 }, { 3241, 3294 }, { 3242, 3293 }, { 3242, 3290 }, { 3241, 3289 }, { 3241, 3288 }, { 3240, 3287 }, { 3240, 3285 }, { 3244, 3281 }, { 3244, 3280 }, { 3246, 3278 }, { 3249, 3278 }, { 3251, 3276 }, { 3251, 3274 }, { 3253, 3272 } }); private static final List<Position> PATH_TO_CHICKENS = new ArrayList<Position>( Arrays.asList(new Position(3255, 3266, 0), new Position(3249, 3267, 0), new Position(3244, 3274, 0), new Position(3239, 3283, 0), new Position(3238, 3285, 0), new Position(3239, 3294, 0), new Position(3230, 3299, 0), new Position(3230, 3299, 0))); private static final List<Position> PATH_TO_WHEAT_FIELD = new ArrayList<Position>( Arrays.asList(new Position(3233, 3293, 0), new Position(3238, 3296, 0), new Position(3239, 3286, 0), new Position(3240, 3276, 0), new Position(3240, 3276, 0), new Position(3242, 3266, 0), new Position(3243, 3260, 0), new Position(3233, 3260, 0), new Position(3223, 3260, 0), new Position(3215, 3260, 0), new Position(3214, 3270, 0), new Position(3213, 3280, 0), new Position(3213, 3280, 0), new Position(3203, 3281, 0), new Position(3193, 3282, 0), new Position(3184, 3284, 0), new Position(3174, 3285, 0), new Position(3164, 3286, 0), new Position(3162, 3287, 0), new Position(3159, 3296, 0), new Position(3158, 3299, 0))); private static final List<Position> PATH_TO_WINDMILL = new ArrayList<Position>( Arrays.asList(new Position(3162, 3287, 0), new Position(3166, 3291, 0), new Position(3167, 3300, 0), new Position(3169, 3307, 0))); private static final Area CHICKENS_AREA = new Area( new int[][] { { 3226, 3302 }, { 3225, 3301 }, { 3225, 3295 }, { 3231, 3295 }, { 3231, 3287 }, { 3237, 3287 }, { 3237, 3290 }, { 3238, 3291 }, { 3238, 3293 }, { 3237, 3294 }, { 3237, 3297 }, { 3238, 3298 }, { 3238, 3299 }, { 3238, 3300 }, { 3235, 3302 }, { 3226, 3302 } }); private static final Area COOKS_AREA = new Area(new int[][] { { 3205, 3217 }, { 3205, 3209 }, { 3215, 3209 }, { 3217, 3211 }, { 3217, 3212 }, { 3213, 3212 }, { 3213, 3218 }, { 3205, 3218 } }); private static final Area WHEAT_AREA = new Area( new int[][] { { 3153, 3305 }, { 3153, 3297 }, { 3155, 3295 }, { 3157, 3295 }, { 3162, 3290 }, { 3164, 3290 }, { 3165, 3291 }, { 3165, 3292 }, { 3164, 3293 }, { 3164, 3296 }, { 3165, 3297 }, { 3165, 3299 }, { 3162, 3302 }, { 3162, 3303 }, { 3160, 3305 }, { 3160, 3306 }, { 3159, 3307 }, { 3158, 3307 }, { 3157, 3308 }, { 3155, 3308 }, { 3153, 3306 }, { 3153, 3305 } }); private static final Position FLOWER_POSITION = new Position(3165, 3308, 2); private static final Area FLOWER_AREA = new Area(new int[][] { { 3164, 3308 }, { 3166, 3310 }, { 3168, 3310 }, { 3170, 3308 }, { 3170, 3306 }, { 3168, 3304 }, { 3166, 3304 }, { 3164, 3306 }, { 3164, 3308 } }) .setPlane(2); private static final Area WHEAT_FLOOR_1 = new Area(new int[][] { { 3166, 3310 }, { 3168, 3310 }, { 3170, 3308 }, { 3170, 3306 }, { 3168, 3304 }, { 3165, 3304 }, { 3164, 3306 }, { 3164, 3308 } }).setPlane(1); private static final Area WHEAT_FLOOR_2 = new Area(new int[][] { { 3166, 3310 }, { 3168, 3310 }, { 3170, 3308 }, { 3170, 3306 }, { 3168, 3304 }, { 3165, 3304 }, { 3164, 3306 }, { 3164, 3308 } }).setPlane(2); private static final Area WHEAT_FLOOR_0 = new Area(new int[][] { { 3166, 3310 }, { 3168, 3310 }, { 3170, 3308 }, { 3170, 3306 }, { 3168, 3304 }, { 3165, 3304 }, { 3164, 3306 }, { 3164, 3308 } }).setPlane(0); private static final Area BASEMENT_AREA = new Area( new int[][] { { 3207, 9614 }, { 3207, 9627 }, { 3221, 9627 }, { 3221, 9614 } }); private static final List<Position> PATH_TO_COOK_FROM_MILL = new ArrayList<Position>( Arrays.asList(new Position(3166, 3301, 0), new Position(3166, 3291, 0), new Position(3166, 3287, 0), new Position(3176, 3285, 0), new Position(3186, 3283, 0), new Position(3186, 3283, 0), new Position(3196, 3281, 0), new Position(3206, 3279, 0), new Position(3208, 3278, 0), new Position(3214, 3270, 0), new Position(3216, 3268, 0), new Position(3216, 3258, 0), new Position(3216, 3250, 0), new Position(3222, 3242, 0), new Position(3227, 3234, 0), new Position(3231, 3225, 0), new Position(3235, 3216, 0), new Position(3225, 3217, 0), new Position(3218, 3218, 0), new Position(3215, 3219, 0), new Position(3214, 3213, 0), new Position(3214, 3209, 0), new Position(3209, 3209, 0), new Position(3208, 3214, 0))); private static final Position POT_ON_MACHINE = new Position(3167, 3305, 0); private static final Position BUCKET_POSITION_IN_BASEMENT = new Position(3215, 9624, 0); private static final int QUEST_CONFIG = 29; public CookingsAssistant(int questStartNpc, int configQuestId) { super(questStartNpc, configQuestId, AccountStage.QUEST_COOK_ASSISTANT); // TODO Auto-generated constructor stub } private String scriptName = this.getClass().getSimpleName(); /** */ public void decideOnStartTask() { if (getCurrentTask() != null) { return; } // The task system for (Task task : getCookingAssistantTask()) { if (getCurrentTask() == null && getQuestProgress() == task.requiredConfigQuestStep()) { setCurrentTask(task); log("set task to: " + getCurrentTask()); } else { log("is not in quest step for: " + task.getClass().getSimpleName() + " step: " + task.requiredConfigQuestStep() + " curr: " + getQuestProgress()); } } } @Override public void onStart() { getCookingAssistantTask() .add(new WalkTask("walk to cook", 0, QUEST_CONFIG, getBot().getMethods(), PATH_TO_COOK, COOKS_AREA)); getCookingAssistantTask().add(new DialogueTask("talk with cook", 0, QUEST_CONFIG, getBot().getMethods(), COOKS_AREA, 4626, new String[] { "What's wrong?", "I'm always happy to help a cook in distress", "I'll get right on it", "Actually, I know where to find this stuff." })); if (!getInventory().contains("Bucket of milk")) { getCookingAssistantTask().add(new WalkTask("walk cow milking", 1, QUEST_CONFIG, getBot().getMethods(), PATH_TO_MILKING_COW, MILKING_AREA)); getCookingAssistantTask().add(new ClickObjectTask("fill bucket", 1, QUEST_CONFIG, getBot().getMethods(), MILKING_AREA, 8689, "Milk", "Bucket of milk")); } if (!getInventory().contains("Egg")) { getCookingAssistantTask().add(new WalkTask("walk to chickens", 1, QUEST_CONFIG, getBot().getMethods(), PATH_TO_CHICKENS, CHICKENS_AREA)); getCookingAssistantTask().add( new PickupItemTask("pickup egg", 1, QUEST_CONFIG, getBot().getMethods(), CHICKENS_AREA, "Egg")); } if (!getInventory().contains("Pot of flour")) { getCookingAssistantTask().add(new WalkTask("path to wheat field", 1, QUEST_CONFIG, getBot().getMethods(), PATH_TO_WHEAT_FIELD, WHEAT_AREA)); if (!getInventory().contains("Grain")) { getCookingAssistantTask().add(new ClickObjectTask("take wheat", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_AREA, 15506, "Pick", "Grain")); } getCookingAssistantTask().add(new WalkTask("path to wind mill", 1, QUEST_CONFIG, getBot().getMethods(), PATH_TO_WINDMILL, WHEAT_FLOOR_0)); // go up 2 ladders getCookingAssistantTask().add(new ClickObjectTask("climb up 1", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_0, 12964, "Climb-up", WHEAT_FLOOR_1)); getCookingAssistantTask().add(new ClickObjectTask("climb up 2", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_1, 12965, "Climb-up", WHEAT_FLOOR_2)); getCookingAssistantTask().add(new ItemOnObjectTask("grain on machine", 1, QUEST_CONFIG, getBot().getMethods(), FLOWER_AREA, 24961, "Grain")); getCookingAssistantTask().add(new ClickObjectTask("operate", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_2, 24964, 24967)); // go down 2 ladders getCookingAssistantTask().add(new ClickObjectTask("climb down 1", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_2, 12966, "Climb-down", WHEAT_FLOOR_1)); getCookingAssistantTask().add(new ClickObjectTask("climb down 0", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_1, 12965, "Climb-down", WHEAT_FLOOR_0)); getCookingAssistantTask().add(new ClickObjectTask("get flour to pot", 1, QUEST_CONFIG, getBot().getMethods(), WHEAT_FLOOR_0, 1781, "Pot of flour")); } getCookingAssistantTask().add(new WalkTask("path to cook from mill", 1, QUEST_CONFIG, getBot().getMethods(), PATH_TO_COOK_FROM_MILL, COOKS_AREA)); getCookingAssistantTask().add(new DialogueTask("talk with cook final", 1, QUEST_CONFIG, getBot().getMethods(), COOKS_AREA, 4626, new String[] { "" })); } @Override public void onLoop() throws InterruptedException { // TODO Auto-generated method stub // log(getQuestProgress()); // log(progress); // // switch (getQuestProgress()) { // case 0: // // Starting quest // // if (walkToPosition(PATH_TO_COOK, COOKS_AREA) && talkWithNpc()) { // log("talked with npc"); // } // // break; // // case 1: // // Progress on starting up // if (progress == CooksAssistantSteps.TALK_WITH_COOK) { // progress = CooksAssistantSteps.GOING_TO_BASEMENT_FOR_BUCKET; // } // // // Started quest // if (progress == CooksAssistantSteps.GOING_TO_BASEMENT_FOR_BUCKET) { // if (pickupBucket()) { // progress = CooksAssistantSteps.GETTING_BUCKET_OF_MILK; // log("picked up bucket"); // if (walkUpToCook()) { // log("walked back to cook"); // } // } // } else if (progress == CooksAssistantSteps.GETTING_BUCKET_OF_MILK) { // if (getBucketOfMilk()) { // log("got bucket of milk"); // } // } // break; // // case 2: // // Finished quest // break; // // default: // break; // } } /** * * @return */ private boolean walkUpToCook() { if (BASEMENT_AREA.contains(myPlayer())) { if (clickObjectToArea("Ladder", COOKS_AREA)) { return clickObjectToArea("Ladder", COOKS_AREA); } } else { return walkToPosition(PATH_TO_COOK, COOKS_AREA); } return false; } /** * Retreives a bucket of milk * * @return */ private boolean getBucketOfMilk() { if (getInventory().contains("Bucket of milk")) { return true; } if (walkToPosition(PATH_TO_MILKING_COW, MILKING_AREA)) { return clickObject(8689, "Bucket of milk", "Milk"); } return false; } /** * Picks up the bucket in the basement * * @return */ // private boolean pickupBucket() { // // je hebt al een bucket // if (getInventory().contains("Bucket")) { // return true; // } // progress = CooksAssistantSteps.GOING_TO_BASEMENT_FOR_BUCKET; // // // wanneer niet in de basement ga er naartoe // if (!getInventory().contains("Bucket")) { // if (!BASEMENT_AREA.contains(myPlayer())) { // if (walkToPosition(PATH_TO_COOK, COOKS_AREA) && clickObjectToArea(14880, // BASEMENT_AREA)) { // log("going down to basement"); // } // } // // // wanneer wel in de basement ga het oppakken // else if (BASEMENT_AREA.contains(myPlayer())) { // if (getWalking().walk(BUCKET_POSITION_IN_BASEMENT)) { // if (pickupItem(1925)) { // log("trying to pickup"); // Sleep.sleepUntil(() -> getInventory().contains("Bucket"), 10000); // return true; // } else { // // wanneer er<SUF> // log("waiting for bucket spawn..."); // Sleep.sleepUntil(() -> getGroundItems().closest("Bucket") != null, 60000, // 2000); // return false; // } // } // } // } // return false; // } @Override public boolean isCompleted() { // TODO Auto-generated method stub return false; } @Override public MainState getNextMainState() { // TODO Auto-generated method stub return null; } /** * @return the cookingAssistantTask */ public List<Task> getCookingAssistantTask() { return cookingAssistantTask; } /** * @param cookingAssistantTask * the cookingAssistantTask to set */ public void setCookingAssistantTask(List<Task> cookingAssistantTask) { this.cookingAssistantTask = cookingAssistantTask; } /** * @return the currentTask */ public Task getCurrentTask() { return currentTask; } /** * @param currentTask * the currentTask to set */ public void setCurrentTask(Task currentTask) { this.currentTask = currentTask; } }
139098_1
/* * Copyright 2017 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.flink; import com.navercorp.pinpoint.collector.receiver.thrift.TCPReceiverBean; import com.navercorp.pinpoint.common.server.bo.stat.join.JoinStatBo; import com.navercorp.pinpoint.common.util.IOUtils; import com.navercorp.pinpoint.flink.cluster.FlinkServerRegister; import com.navercorp.pinpoint.flink.config.FlinkProperties; import com.navercorp.pinpoint.flink.dao.hbase.ApplicationMetricDao; import com.navercorp.pinpoint.flink.dao.hbase.StatisticsDao; import com.navercorp.pinpoint.flink.dao.hbase.StatisticsDaoInterceptor; import com.navercorp.pinpoint.flink.function.ApplicationStatBoWindowInterceptor; import com.navercorp.pinpoint.flink.process.ApplicationCache; import com.navercorp.pinpoint.flink.process.TBaseFlatMapper; import com.navercorp.pinpoint.flink.process.TBaseFlatMapperInterceptor; import com.navercorp.pinpoint.flink.receiver.AgentStatHandler; import com.navercorp.pinpoint.flink.receiver.TcpDispatchHandler; import com.navercorp.pinpoint.flink.receiver.TcpSourceFunction; import com.navercorp.pinpoint.flink.vo.RawData; import org.apache.flink.streaming.api.environment.LocalStreamEnvironment; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.source.SourceFunction.SourceContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.io.Closeable; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author minwoo.jung */ public class Bootstrap { private static final Logger logger = LogManager.getLogger(Bootstrap.class); private static final String SPRING_PROFILE = "spring.profiles.active"; private static final String PINPOINT_PROFILE = "pinpoint.profiles.active"; private volatile static Bootstrap instance; private final StatisticsDao statisticsDao; private final ApplicationContext applicationContext; private final TBaseFlatMapper tbaseFlatMapper; private final FlinkProperties flinkProperties; private final TcpDispatchHandler tcpDispatchHandler; private final TcpSourceFunction tcpSourceFunction; private final ApplicationCache applicationCache; private final List<ApplicationMetricDao<JoinStatBo>> applicationMetricDaoList; private final TBaseFlatMapperInterceptor tBaseFlatMapperInterceptor; private final StatisticsDaoInterceptor statisticsDaoInterceptor; private final ApplicationStatBoWindowInterceptor applicationStatBoWindowInterceptor; private final AgentStatHandler agentStatHandler; private Bootstrap() { applicationContext = new AnnotationConfigApplicationContext(FlinkModule.class); tbaseFlatMapper = applicationContext.getBean("tbaseFlatMapper", TBaseFlatMapper.class); flinkProperties = applicationContext.getBean("flinkProperties", FlinkProperties.class); tcpDispatchHandler = applicationContext.getBean("tcpDispatchHandler", TcpDispatchHandler.class); tcpSourceFunction = applicationContext.getBean("tcpSourceFunction", TcpSourceFunction.class); applicationCache = applicationContext.getBean("applicationCache", ApplicationCache.class); statisticsDao = applicationContext.getBean("statisticsDao", StatisticsDao.class); this.applicationMetricDaoList = getApplicationMetricDao(); tBaseFlatMapperInterceptor = applicationContext.getBean("tBaseFlatMapperInterceptor", TBaseFlatMapperInterceptor.class); statisticsDaoInterceptor = applicationContext.getBean("statisticsDaoInterceptor", StatisticsDaoInterceptor.class); applicationStatBoWindowInterceptor = applicationContext.getBean("applicationStatBoWindowInterceptor", ApplicationStatBoWindowInterceptor.class); agentStatHandler = applicationContext.getBean("agentStatHandler", AgentStatHandler.class); } @SuppressWarnings("unchecked") private List<ApplicationMetricDao<JoinStatBo>> getApplicationMetricDao() { Map<String, ApplicationMetricDao> metricDaoMap = applicationContext.getBeansOfType(ApplicationMetricDao.class); metricDaoMap.forEach((beanName, applicationMetricDao) -> logger.info("ApplicationMetricDao BeanName:{}", beanName)); List<ApplicationMetricDao> values = new ArrayList<>(metricDaoMap.values()); return (List<ApplicationMetricDao<JoinStatBo>>) (List<?>) values; } public static Bootstrap getInstance(Map<String, String> jobParameters) { synchronized(Bootstrap.class) { if (instance == null) { instance = buildBootstrap(jobParameters); } return instance; } } private static Bootstrap buildBootstrap(Map<String, String> jobParameters) { String profiles = jobParameters.getOrDefault(SPRING_PROFILE, "local"); System.setProperty(PINPOINT_PROFILE, profiles); Bootstrap bootstrap = new Bootstrap(); logger.info("Initialized bootstrap: jobParameters=" + jobParameters); return bootstrap; } public static void close() { synchronized(Bootstrap.class) { if (instance == null) { logger.warn("Invalid attempt of closing bootstrap: bootstrap is not initialized yet"); return; } logger.info("Closing bootstrap: {}", instance); final ApplicationContext applicationContext = instance.getApplicationContext(); if (applicationContext instanceof Closeable closeable) { logger.info("Closing an instance of ApplicationContext: {}", applicationContext); IOUtils.closeQuietly(closeable); } else { logger.warn("Invalid type of applicationContext was found: {}", applicationContext); } instance = null; logger.info("Closed bootstrap: {}", instance); } } public ApplicationContext getApplicationContext() { return applicationContext; } public StatisticsDao getStatisticsDao() { return statisticsDao; } public List<ApplicationMetricDao<JoinStatBo>> getApplicationMetricDaoList() { return applicationMetricDaoList; } public TBaseFlatMapper getTbaseFlatMapper() { return tbaseFlatMapper; } public ApplicationCache getApplicationCache() { return applicationCache; } public FlinkProperties getFlinkProperties() { return flinkProperties; } public StreamExecutionEnvironment createStreamExecutionEnvironment() { if (flinkProperties.isLocalforFlinkStreamExecutionEnvironment()) { LocalStreamEnvironment localEnvironment = StreamExecutionEnvironment.createLocalEnvironment(); localEnvironment.setParallelism(1); return localEnvironment; } else { return StreamExecutionEnvironment.getExecutionEnvironment(); } } public void setStatHandlerTcpDispatchHandler(SourceContext<RawData> sourceContext) { agentStatHandler.addSourceContext(sourceContext); tcpDispatchHandler.setSimpletHandler(agentStatHandler); } public FlinkServerRegister initFlinkServerRegister() { return applicationContext.getBean("flinkServerRegister", FlinkServerRegister.class); } public void initTcpReceiver() { // lazy init applicationContext.getBean("tcpReceiver", TCPReceiverBean.class); } public TcpSourceFunction getTcpSourceFunction() { return tcpSourceFunction; } public TBaseFlatMapperInterceptor getTbaseFlatMapperInterceptor() { return tBaseFlatMapperInterceptor; } public StatisticsDaoInterceptor getStatisticsDaoInterceptor() { return statisticsDaoInterceptor; } public ApplicationStatBoWindowInterceptor getApplicationStatBoWindowInterceptor() { return applicationStatBoWindowInterceptor; } }
pinpoint-apm/pinpoint
flink/src/main/java/com/navercorp/pinpoint/flink/Bootstrap.java
2,280
/** * @author minwoo.jung */
block_comment
nl
/* * Copyright 2017 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.flink; import com.navercorp.pinpoint.collector.receiver.thrift.TCPReceiverBean; import com.navercorp.pinpoint.common.server.bo.stat.join.JoinStatBo; import com.navercorp.pinpoint.common.util.IOUtils; import com.navercorp.pinpoint.flink.cluster.FlinkServerRegister; import com.navercorp.pinpoint.flink.config.FlinkProperties; import com.navercorp.pinpoint.flink.dao.hbase.ApplicationMetricDao; import com.navercorp.pinpoint.flink.dao.hbase.StatisticsDao; import com.navercorp.pinpoint.flink.dao.hbase.StatisticsDaoInterceptor; import com.navercorp.pinpoint.flink.function.ApplicationStatBoWindowInterceptor; import com.navercorp.pinpoint.flink.process.ApplicationCache; import com.navercorp.pinpoint.flink.process.TBaseFlatMapper; import com.navercorp.pinpoint.flink.process.TBaseFlatMapperInterceptor; import com.navercorp.pinpoint.flink.receiver.AgentStatHandler; import com.navercorp.pinpoint.flink.receiver.TcpDispatchHandler; import com.navercorp.pinpoint.flink.receiver.TcpSourceFunction; import com.navercorp.pinpoint.flink.vo.RawData; import org.apache.flink.streaming.api.environment.LocalStreamEnvironment; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.source.SourceFunction.SourceContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.io.Closeable; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author minwoo.jung <SUF>*/ public class Bootstrap { private static final Logger logger = LogManager.getLogger(Bootstrap.class); private static final String SPRING_PROFILE = "spring.profiles.active"; private static final String PINPOINT_PROFILE = "pinpoint.profiles.active"; private volatile static Bootstrap instance; private final StatisticsDao statisticsDao; private final ApplicationContext applicationContext; private final TBaseFlatMapper tbaseFlatMapper; private final FlinkProperties flinkProperties; private final TcpDispatchHandler tcpDispatchHandler; private final TcpSourceFunction tcpSourceFunction; private final ApplicationCache applicationCache; private final List<ApplicationMetricDao<JoinStatBo>> applicationMetricDaoList; private final TBaseFlatMapperInterceptor tBaseFlatMapperInterceptor; private final StatisticsDaoInterceptor statisticsDaoInterceptor; private final ApplicationStatBoWindowInterceptor applicationStatBoWindowInterceptor; private final AgentStatHandler agentStatHandler; private Bootstrap() { applicationContext = new AnnotationConfigApplicationContext(FlinkModule.class); tbaseFlatMapper = applicationContext.getBean("tbaseFlatMapper", TBaseFlatMapper.class); flinkProperties = applicationContext.getBean("flinkProperties", FlinkProperties.class); tcpDispatchHandler = applicationContext.getBean("tcpDispatchHandler", TcpDispatchHandler.class); tcpSourceFunction = applicationContext.getBean("tcpSourceFunction", TcpSourceFunction.class); applicationCache = applicationContext.getBean("applicationCache", ApplicationCache.class); statisticsDao = applicationContext.getBean("statisticsDao", StatisticsDao.class); this.applicationMetricDaoList = getApplicationMetricDao(); tBaseFlatMapperInterceptor = applicationContext.getBean("tBaseFlatMapperInterceptor", TBaseFlatMapperInterceptor.class); statisticsDaoInterceptor = applicationContext.getBean("statisticsDaoInterceptor", StatisticsDaoInterceptor.class); applicationStatBoWindowInterceptor = applicationContext.getBean("applicationStatBoWindowInterceptor", ApplicationStatBoWindowInterceptor.class); agentStatHandler = applicationContext.getBean("agentStatHandler", AgentStatHandler.class); } @SuppressWarnings("unchecked") private List<ApplicationMetricDao<JoinStatBo>> getApplicationMetricDao() { Map<String, ApplicationMetricDao> metricDaoMap = applicationContext.getBeansOfType(ApplicationMetricDao.class); metricDaoMap.forEach((beanName, applicationMetricDao) -> logger.info("ApplicationMetricDao BeanName:{}", beanName)); List<ApplicationMetricDao> values = new ArrayList<>(metricDaoMap.values()); return (List<ApplicationMetricDao<JoinStatBo>>) (List<?>) values; } public static Bootstrap getInstance(Map<String, String> jobParameters) { synchronized(Bootstrap.class) { if (instance == null) { instance = buildBootstrap(jobParameters); } return instance; } } private static Bootstrap buildBootstrap(Map<String, String> jobParameters) { String profiles = jobParameters.getOrDefault(SPRING_PROFILE, "local"); System.setProperty(PINPOINT_PROFILE, profiles); Bootstrap bootstrap = new Bootstrap(); logger.info("Initialized bootstrap: jobParameters=" + jobParameters); return bootstrap; } public static void close() { synchronized(Bootstrap.class) { if (instance == null) { logger.warn("Invalid attempt of closing bootstrap: bootstrap is not initialized yet"); return; } logger.info("Closing bootstrap: {}", instance); final ApplicationContext applicationContext = instance.getApplicationContext(); if (applicationContext instanceof Closeable closeable) { logger.info("Closing an instance of ApplicationContext: {}", applicationContext); IOUtils.closeQuietly(closeable); } else { logger.warn("Invalid type of applicationContext was found: {}", applicationContext); } instance = null; logger.info("Closed bootstrap: {}", instance); } } public ApplicationContext getApplicationContext() { return applicationContext; } public StatisticsDao getStatisticsDao() { return statisticsDao; } public List<ApplicationMetricDao<JoinStatBo>> getApplicationMetricDaoList() { return applicationMetricDaoList; } public TBaseFlatMapper getTbaseFlatMapper() { return tbaseFlatMapper; } public ApplicationCache getApplicationCache() { return applicationCache; } public FlinkProperties getFlinkProperties() { return flinkProperties; } public StreamExecutionEnvironment createStreamExecutionEnvironment() { if (flinkProperties.isLocalforFlinkStreamExecutionEnvironment()) { LocalStreamEnvironment localEnvironment = StreamExecutionEnvironment.createLocalEnvironment(); localEnvironment.setParallelism(1); return localEnvironment; } else { return StreamExecutionEnvironment.getExecutionEnvironment(); } } public void setStatHandlerTcpDispatchHandler(SourceContext<RawData> sourceContext) { agentStatHandler.addSourceContext(sourceContext); tcpDispatchHandler.setSimpletHandler(agentStatHandler); } public FlinkServerRegister initFlinkServerRegister() { return applicationContext.getBean("flinkServerRegister", FlinkServerRegister.class); } public void initTcpReceiver() { // lazy init applicationContext.getBean("tcpReceiver", TCPReceiverBean.class); } public TcpSourceFunction getTcpSourceFunction() { return tcpSourceFunction; } public TBaseFlatMapperInterceptor getTbaseFlatMapperInterceptor() { return tBaseFlatMapperInterceptor; } public StatisticsDaoInterceptor getStatisticsDaoInterceptor() { return statisticsDaoInterceptor; } public ApplicationStatBoWindowInterceptor getApplicationStatBoWindowInterceptor() { return applicationStatBoWindowInterceptor; } }
166627_24
/* * Copyright (C) 2011-2016 Markus Junginger, greenrobot (http://greenrobot.org) * * This file is part of greenDAO Generator. * * greenDAO Generator 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. * greenDAO Generator 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 greenDAO Generator. If not, see <http://www.gnu.org/licenses/>. */ package org.greenrobot.greendao.generator; import org.greenrobot.greendao.generator.Property.PropertyBuilder; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * Model class for an entity: a Java data object mapped to a data base table. A new entity is added to a {@link Schema} * by the method {@link Schema#addEntity(String)} (there is no public constructor for {@link Entity} itself). <br/> * <br/> Use the various addXXX methods to add entity properties, indexes, and relations to other entities (addToOne, * addToMany).<br/> <br/> There are further configuration possibilities: <ul> <li>{@link * Entity#implementsInterface(String...)} and {@link #implementsSerializable()} to specify interfaces the entity will * implement</li> <li>{@link #setSuperclass(String)} to specify a class of which the entity will extend from</li> * <li>Various setXXX methods</li> </ul> * * @see <a href="http://greendao-orm.com/documentation/modelling-entities/">Modelling Entities (Documentation page)</a> * @see <a href="http://greendao-orm.com/documentation/relations/">Relations (Documentation page)</a> */ @SuppressWarnings("unused") public class Entity { private final Schema schema; private final String className; private final List<Property> properties; private List<Property> propertiesColumns; private final List<Property> propertiesPk; private final List<Property> propertiesNonPk; private final Set<String> propertyNames; private final List<Index> indexes; private final List<Index> multiIndexes; private final List<ToOne> toOneRelations; private final List<ToManyBase> toManyRelations; private final List<ToManyBase> incomingToManyRelations; private final Collection<String> additionalImportsEntity; private final Collection<String> additionalImportsDao; private final List<String> interfacesToImplement; private final List<ContentProvider> contentProviders; private String dbName; private boolean nonDefaultDbName; private String classNameDao; private String classNameTest; private String javaPackage; private String javaPackageDao; private String javaPackageTest; private Property pkProperty; private String pkType; private String superclass; private String javaDoc; private String codeBeforeClass; private boolean protobuf; private boolean constructors; private boolean skipGeneration; private boolean skipGenerationTest; private boolean skipCreationInDb; private Boolean active; private Boolean hasKeepSections; Entity(Schema schema, String className) { this.schema = schema; this.className = className; properties = new ArrayList<>(); propertiesPk = new ArrayList<>(); propertiesNonPk = new ArrayList<>(); propertyNames = new HashSet<>(); indexes = new ArrayList<>(); multiIndexes = new ArrayList<>(); toOneRelations = new ArrayList<>(); toManyRelations = new ArrayList<>(); incomingToManyRelations = new ArrayList<>(); additionalImportsEntity = new TreeSet<>(); additionalImportsDao = new TreeSet<>(); interfacesToImplement = new ArrayList<>(); contentProviders = new ArrayList<>(); constructors = true; } public PropertyBuilder addBooleanProperty(String propertyName) { return addProperty(PropertyType.Boolean, propertyName); } public PropertyBuilder addByteProperty(String propertyName) { return addProperty(PropertyType.Byte, propertyName); } public PropertyBuilder addShortProperty(String propertyName) { return addProperty(PropertyType.Short, propertyName); } public PropertyBuilder addIntProperty(String propertyName) { return addProperty(PropertyType.Int, propertyName); } public PropertyBuilder addLongProperty(String propertyName) { return addProperty(PropertyType.Long, propertyName); } public PropertyBuilder addFloatProperty(String propertyName) { return addProperty(PropertyType.Float, propertyName); } public PropertyBuilder addDoubleProperty(String propertyName) { return addProperty(PropertyType.Double, propertyName); } public PropertyBuilder addByteArrayProperty(String propertyName) { return addProperty(PropertyType.ByteArray, propertyName); } public PropertyBuilder addStringProperty(String propertyName) { return addProperty(PropertyType.String, propertyName); } public PropertyBuilder addDateProperty(String propertyName) { return addProperty(PropertyType.Date, propertyName); } public PropertyBuilder addProperty(PropertyType propertyType, String propertyName) { if (!propertyNames.add(propertyName)) { throw new RuntimeException("Property already defined: " + propertyName); } PropertyBuilder builder = new PropertyBuilder(schema, this, propertyType, propertyName); properties.add(builder.getProperty()); return builder; } /** Adds a standard _id column required by standard Android classes, e.g. list adapters. */ public PropertyBuilder addIdProperty() { PropertyBuilder builder = addLongProperty("id"); builder.dbName("_id").primaryKey(); return builder; } /** Adds a to-many relationship; the target entity is joined to the PK property of this entity (typically the ID). */ public ToMany addToMany(Entity target, Property targetProperty) { Property[] targetProperties = {targetProperty}; return addToMany(null, target, targetProperties); } /** * Convenience method for {@link Entity#addToMany(Entity, Property)} with a subsequent call to {@link * ToMany#setName(String)}. */ public ToMany addToMany(Entity target, Property targetProperty, String name) { ToMany toMany = addToMany(target, targetProperty); toMany.setName(name); return toMany; } /** * Add a to-many relationship; the target entity is joined using the given target property (of the target entity) * and given source property (of this entity). */ public ToMany addToMany(Property sourceProperty, Entity target, Property targetProperty) { Property[] sourceProperties = {sourceProperty}; Property[] targetProperties = {targetProperty}; return addToMany(sourceProperties, target, targetProperties); } public ToMany addToMany(Property[] sourceProperties, Entity target, Property[] targetProperties) { if (protobuf) { throw new IllegalStateException("Protobuf entities do not support relations, currently"); } ToMany toMany = new ToMany(schema, this, sourceProperties, target, targetProperties); toManyRelations.add(toMany); target.incomingToManyRelations.add(toMany); return toMany; } public ToManyWithJoinEntity addToMany(Entity target, Entity joinEntity, Property id1, Property id2) { ToManyWithJoinEntity toMany = new ToManyWithJoinEntity(schema, this, target, joinEntity, id1, id2); toManyRelations.add(toMany); target.incomingToManyRelations.add(toMany); return toMany; } /** * Adds a to-one relationship to the given target entity using the given given foreign key property (which belongs * to this entity). */ public ToOne addToOne(Entity target, Property fkProperty) { if (protobuf) { throw new IllegalStateException("Protobuf entities do not support realtions, currently"); } Property[] fkProperties = {fkProperty}; ToOne toOne = new ToOne(schema, this, target, fkProperties, true); toOneRelations.add(toOne); return toOne; } /** Convenience for {@link #addToOne(Entity, Property)} with a subsequent call to {@link ToOne#setName(String)}. */ public ToOne addToOne(Entity target, Property fkProperty, String name) { ToOne toOne = addToOne(target, fkProperty); toOne.setName(name); return toOne; } public ToOne addToOneWithoutProperty(String name, Entity target, String fkColumnName) { return addToOneWithoutProperty(name, target, fkColumnName, false, false); } public ToOne addToOneWithoutProperty(String name, Entity target, String fkColumnName, boolean notNull, boolean unique) { PropertyBuilder propertyBuilder = new PropertyBuilder(schema, this, null, name); if (notNull) { propertyBuilder.notNull(); } if (unique) { propertyBuilder.unique(); } propertyBuilder.dbName(fkColumnName); Property column = propertyBuilder.getProperty(); Property[] fkColumns = {column}; ToOne toOne = new ToOne(schema, this, target, fkColumns, false); toOne.setName(name); toOneRelations.add(toOne); return toOne; } protected void addIncomingToMany(ToMany toMany) { incomingToManyRelations.add(toMany); } public ContentProvider addContentProvider() { List<Entity> entities = new ArrayList<>(); entities.add(this); ContentProvider contentProvider = new ContentProvider(schema, entities); contentProviders.add(contentProvider); return contentProvider; } /** Adds a new index to the entity. */ public Entity addIndex(Index index) { indexes.add(index); return this; } public Entity addImport(String additionalImport) { additionalImportsEntity.add(additionalImport); return this; } /** The entity is represented by a protocol buffers object. Requires some special actions like using builders. */ Entity useProtobuf() { protobuf = true; return this; } public boolean isProtobuf() { return protobuf; } public Schema getSchema() { return schema; } public String getDbName() { return dbName; } @Deprecated /** * @deprecated Use setDbName */ public void setTableName(String tableName) { setDbName(tableName); } public void setDbName(String dbName) { this.dbName = dbName; this.nonDefaultDbName = dbName != null; } public String getClassName() { return className; } public List<Property> getProperties() { return properties; } public List<Property> getPropertiesColumns() { return propertiesColumns; } public String getJavaPackage() { return javaPackage; } public void setJavaPackage(String javaPackage) { this.javaPackage = javaPackage; } public String getJavaPackageDao() { return javaPackageDao; } public void setJavaPackageDao(String javaPackageDao) { this.javaPackageDao = javaPackageDao; } public String getClassNameDao() { return classNameDao; } public void setClassNameDao(String classNameDao) { this.classNameDao = classNameDao; } public String getClassNameTest() { return classNameTest; } public void setClassNameTest(String classNameTest) { this.classNameTest = classNameTest; } public String getJavaPackageTest() { return javaPackageTest; } public void setJavaPackageTest(String javaPackageTest) { this.javaPackageTest = javaPackageTest; } /** Internal property used by templates, don't use during entity definition. */ public List<Property> getPropertiesPk() { return propertiesPk; } /** Internal property used by templates, don't use during entity definition. */ public List<Property> getPropertiesNonPk() { return propertiesNonPk; } /** Internal property used by templates, don't use during entity definition. */ public Property getPkProperty() { return pkProperty; } public List<Index> getIndexes() { return indexes; } /** Internal property used by templates, don't use during entity definition. */ public String getPkType() { return pkType; } public boolean isConstructors() { return constructors; } /** Flag to define if constructors should be generated. */ public void setConstructors(boolean constructors) { this.constructors = constructors; } public boolean isSkipGeneration() { return skipGeneration; } /** * Flag if the entity's code generation should be skipped. E.g. if you need to change the class after initial * generation. */ public void setSkipGeneration(boolean skipGeneration) { this.skipGeneration = skipGeneration; } @Deprecated /** * @deprecated Use setSkipCreationInDb */ public void setSkipTableCreation(boolean skipTableCreation) { setSkipCreationInDb(skipTableCreation); } /** Flag if CREATE and DROP TABLE scripts should be skipped in Dao. */ public void setSkipCreationInDb(boolean skipCreationInDb) { this.skipCreationInDb = skipCreationInDb; } public boolean isSkipCreationInDb() { return skipCreationInDb; } public boolean isSkipGenerationTest() { return skipGenerationTest; } public void setSkipGenerationTest(boolean skipGenerationTest) { this.skipGenerationTest = skipGenerationTest; } public List<ToOne> getToOneRelations() { return toOneRelations; } public List<ToManyBase> getToManyRelations() { return toManyRelations; } public List<ToManyBase> getIncomingToManyRelations() { return incomingToManyRelations; } /** * Entities with relations are active, but this method allows to make the entities active even if it does not have * relations. */ public void setActive(Boolean active) { this.active = active; } public Boolean getActive() { return active; } public Boolean getHasKeepSections() { return hasKeepSections; } public Collection<String> getAdditionalImportsEntity() { return additionalImportsEntity; } public Collection<String> getAdditionalImportsDao() { return additionalImportsDao; } public void setHasKeepSections(Boolean hasKeepSections) { this.hasKeepSections = hasKeepSections; } public List<String> getInterfacesToImplement() { return interfacesToImplement; } public List<ContentProvider> getContentProviders() { return contentProviders; } public void implementsInterface(String... interfaces) { for (String interfaceToImplement : interfaces) { if (interfacesToImplement.contains(interfaceToImplement)) { throw new RuntimeException("Interface defined more than once: " + interfaceToImplement); } interfacesToImplement.add(interfaceToImplement); } } public void implementsSerializable() { interfacesToImplement.add("java.io.Serializable"); } public String getSuperclass() { return superclass; } public void setSuperclass(String classToExtend) { this.superclass = classToExtend; } public String getJavaDoc() { return javaDoc; } public void setJavaDoc(String javaDoc) { this.javaDoc = DaoUtil.checkConvertToJavaDoc(javaDoc, ""); } public String getCodeBeforeClass() { return codeBeforeClass; } public void setCodeBeforeClass(String codeBeforeClass) { this.codeBeforeClass = codeBeforeClass; } void init2ndPass() { init2ndPassNamesWithDefaults(); for (int i = 0; i < properties.size(); i++) { Property property = properties.get(i); property.setOrdinal(i); property.init2ndPass(); if (property.isPrimaryKey()) { propertiesPk.add(property); } else { propertiesNonPk.add(property); } } for (int i = 0; i < indexes.size(); i++) { final Index index = indexes.get(i); final int propertiesSize = index.getProperties().size(); if (propertiesSize == 1) { final Property property = index.getProperties().get(0); property.setIndex(index); } else if (propertiesSize > 1) { multiIndexes.add(index); } } if (propertiesPk.size() == 1) { pkProperty = propertiesPk.get(0); pkType = schema.mapToJavaTypeNullable(pkProperty.getPropertyType()); } else { pkType = "Void"; } propertiesColumns = new ArrayList<>(properties); for (ToOne toOne : toOneRelations) { toOne.init2ndPass(); Property[] fkProperties = toOne.getFkProperties(); for (Property fkProperty : fkProperties) { if (!propertiesColumns.contains(fkProperty)) { propertiesColumns.add(fkProperty); } } } for (ToManyBase toMany : toManyRelations) { toMany.init2ndPass(); // Source Properties may not be virtual, so we do not need the following code: // for (Property sourceProperty : toMany.getSourceProperties()) { // if (!propertiesColumns.contains(sourceProperty)) { // propertiesColumns.add(sourceProperty); // } // } } if (active == null) { active = schema.isUseActiveEntitiesByDefault(); } active |= !toOneRelations.isEmpty() || !toManyRelations.isEmpty(); if (hasKeepSections == null) { hasKeepSections = schema.isHasKeepSectionsByDefault(); } init2ndPassIndexNamesWithDefaults(); for (ContentProvider contentProvider : contentProviders) { contentProvider.init2ndPass(); } } protected void init2ndPassNamesWithDefaults() { if (dbName == null) { dbName = DaoUtil.dbName(className); nonDefaultDbName = false; } if (classNameDao == null) { classNameDao = className + "Dao"; } if (classNameTest == null) { classNameTest = className + "Test"; } if (javaPackage == null) { javaPackage = schema.getDefaultJavaPackage(); } if (javaPackageDao == null) { javaPackageDao = schema.getDefaultJavaPackageDao(); if (javaPackageDao == null) { javaPackageDao = javaPackage; } } if (javaPackageTest == null) { javaPackageTest = schema.getDefaultJavaPackageTest(); if (javaPackageTest == null) { javaPackageTest = javaPackage; } } } protected void init2ndPassIndexNamesWithDefaults() { for (int i = 0; i < indexes.size(); i++) { Index index = indexes.get(i); if (index.getName() == null) { String indexName = "IDX_" + getDbName(); List<Property> properties = index.getProperties(); for (int j = 0; j < properties.size(); j++) { Property property = properties.get(j); indexName += "_" + property.getDbName(); if ("DESC".equalsIgnoreCase(index.getPropertiesOrder().get(j))) { indexName += "_DESC"; } } // TODO can this get too long? how to shorten reliably without depending on the order (i) index.setDefaultName(indexName); } } } void init3rdPass() { for (Property property : properties) { property.init3ndPass(); } init3rdPassRelations(); init3rdPassAdditionalImports(); } private void init3rdPassRelations() { Set<String> toOneNames = new HashSet<>(); for (ToOne toOne : toOneRelations) { toOne.init3ndPass(); if (!toOneNames.add(toOne.getName().toLowerCase())) { throw new RuntimeException("Duplicate name for " + toOne); } } Set<String> toManyNames = new HashSet<>(); for (ToManyBase toMany : toManyRelations) { toMany.init3rdPass(); if (toMany instanceof ToMany) { Entity targetEntity = toMany.getTargetEntity(); for (Property targetProperty : ((ToMany) toMany).getTargetProperties()) { if (!targetEntity.propertiesColumns.contains(targetProperty)) { targetEntity.propertiesColumns.add(targetProperty); } } } if (!toManyNames.add(toMany.getName().toLowerCase())) { throw new RuntimeException("Duplicate name for " + toMany); } } } private void init3rdPassAdditionalImports() { if (active && !javaPackage.equals(javaPackageDao)) { additionalImportsEntity.add(javaPackageDao + "." + classNameDao); } for (ToOne toOne : toOneRelations) { Entity targetEntity = toOne.getTargetEntity(); checkAdditionalImportsEntityTargetEntity(targetEntity); // For deep loading checkAdditionalImportsDaoTargetEntity(targetEntity); } for (ToManyBase toMany : toManyRelations) { Entity targetEntity = toMany.getTargetEntity(); checkAdditionalImportsEntityTargetEntity(targetEntity); } for (ToManyBase incomingToMany : incomingToManyRelations) { if (incomingToMany instanceof ToManyWithJoinEntity) { final ToManyWithJoinEntity toManyWithJoinEntity = (ToManyWithJoinEntity) incomingToMany; final Entity joinEntity = toManyWithJoinEntity.getJoinEntity(); checkAdditionalImportsDaoTargetEntity(joinEntity); } } for (Property property : properties) { String customType = property.getCustomType(); if (customType != null) { String pack = DaoUtil.getPackageFromFullyQualified(customType); if (pack != null && !pack.equals(javaPackage)) { additionalImportsEntity.add(customType); } if (pack != null && !pack.equals(javaPackageDao)) { additionalImportsDao.add(customType); } } String converter = property.getConverter(); if (converter != null) { String pack = DaoUtil.getPackageFromFullyQualified(converter); if (pack != null && !pack.equals(javaPackageDao)) { additionalImportsDao.add(converter); } } } } private void checkAdditionalImportsEntityTargetEntity(Entity targetEntity) { if (!targetEntity.getJavaPackage().equals(javaPackage)) { additionalImportsEntity.add(targetEntity.getJavaPackage() + "." + targetEntity.getClassName()); } if (!targetEntity.getJavaPackageDao().equals(javaPackage)) { additionalImportsEntity.add(targetEntity.getJavaPackageDao() + "." + targetEntity.getClassNameDao()); } } private void checkAdditionalImportsDaoTargetEntity(Entity targetEntity) { if (!targetEntity.getJavaPackage().equals(javaPackageDao)) { additionalImportsDao.add(targetEntity.getJavaPackage() + "." + targetEntity.getClassName()); } } public void validatePropertyExists(Property property) { if (!properties.contains(property)) { throw new RuntimeException("Property " + property + " does not exist in " + this); } } public List<Index> getMultiIndexes() { return multiIndexes; } public boolean isNonDefaultDbName() { return nonDefaultDbName; } @Override public String toString() { return "Entity " + className + " (package: " + javaPackage + ")"; } }
pioneerz/greenDAO
DaoGenerator/src/org/greenrobot/greendao/generator/Entity.java
6,546
// For deep loading
line_comment
nl
/* * Copyright (C) 2011-2016 Markus Junginger, greenrobot (http://greenrobot.org) * * This file is part of greenDAO Generator. * * greenDAO Generator 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. * greenDAO Generator 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 greenDAO Generator. If not, see <http://www.gnu.org/licenses/>. */ package org.greenrobot.greendao.generator; import org.greenrobot.greendao.generator.Property.PropertyBuilder; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * Model class for an entity: a Java data object mapped to a data base table. A new entity is added to a {@link Schema} * by the method {@link Schema#addEntity(String)} (there is no public constructor for {@link Entity} itself). <br/> * <br/> Use the various addXXX methods to add entity properties, indexes, and relations to other entities (addToOne, * addToMany).<br/> <br/> There are further configuration possibilities: <ul> <li>{@link * Entity#implementsInterface(String...)} and {@link #implementsSerializable()} to specify interfaces the entity will * implement</li> <li>{@link #setSuperclass(String)} to specify a class of which the entity will extend from</li> * <li>Various setXXX methods</li> </ul> * * @see <a href="http://greendao-orm.com/documentation/modelling-entities/">Modelling Entities (Documentation page)</a> * @see <a href="http://greendao-orm.com/documentation/relations/">Relations (Documentation page)</a> */ @SuppressWarnings("unused") public class Entity { private final Schema schema; private final String className; private final List<Property> properties; private List<Property> propertiesColumns; private final List<Property> propertiesPk; private final List<Property> propertiesNonPk; private final Set<String> propertyNames; private final List<Index> indexes; private final List<Index> multiIndexes; private final List<ToOne> toOneRelations; private final List<ToManyBase> toManyRelations; private final List<ToManyBase> incomingToManyRelations; private final Collection<String> additionalImportsEntity; private final Collection<String> additionalImportsDao; private final List<String> interfacesToImplement; private final List<ContentProvider> contentProviders; private String dbName; private boolean nonDefaultDbName; private String classNameDao; private String classNameTest; private String javaPackage; private String javaPackageDao; private String javaPackageTest; private Property pkProperty; private String pkType; private String superclass; private String javaDoc; private String codeBeforeClass; private boolean protobuf; private boolean constructors; private boolean skipGeneration; private boolean skipGenerationTest; private boolean skipCreationInDb; private Boolean active; private Boolean hasKeepSections; Entity(Schema schema, String className) { this.schema = schema; this.className = className; properties = new ArrayList<>(); propertiesPk = new ArrayList<>(); propertiesNonPk = new ArrayList<>(); propertyNames = new HashSet<>(); indexes = new ArrayList<>(); multiIndexes = new ArrayList<>(); toOneRelations = new ArrayList<>(); toManyRelations = new ArrayList<>(); incomingToManyRelations = new ArrayList<>(); additionalImportsEntity = new TreeSet<>(); additionalImportsDao = new TreeSet<>(); interfacesToImplement = new ArrayList<>(); contentProviders = new ArrayList<>(); constructors = true; } public PropertyBuilder addBooleanProperty(String propertyName) { return addProperty(PropertyType.Boolean, propertyName); } public PropertyBuilder addByteProperty(String propertyName) { return addProperty(PropertyType.Byte, propertyName); } public PropertyBuilder addShortProperty(String propertyName) { return addProperty(PropertyType.Short, propertyName); } public PropertyBuilder addIntProperty(String propertyName) { return addProperty(PropertyType.Int, propertyName); } public PropertyBuilder addLongProperty(String propertyName) { return addProperty(PropertyType.Long, propertyName); } public PropertyBuilder addFloatProperty(String propertyName) { return addProperty(PropertyType.Float, propertyName); } public PropertyBuilder addDoubleProperty(String propertyName) { return addProperty(PropertyType.Double, propertyName); } public PropertyBuilder addByteArrayProperty(String propertyName) { return addProperty(PropertyType.ByteArray, propertyName); } public PropertyBuilder addStringProperty(String propertyName) { return addProperty(PropertyType.String, propertyName); } public PropertyBuilder addDateProperty(String propertyName) { return addProperty(PropertyType.Date, propertyName); } public PropertyBuilder addProperty(PropertyType propertyType, String propertyName) { if (!propertyNames.add(propertyName)) { throw new RuntimeException("Property already defined: " + propertyName); } PropertyBuilder builder = new PropertyBuilder(schema, this, propertyType, propertyName); properties.add(builder.getProperty()); return builder; } /** Adds a standard _id column required by standard Android classes, e.g. list adapters. */ public PropertyBuilder addIdProperty() { PropertyBuilder builder = addLongProperty("id"); builder.dbName("_id").primaryKey(); return builder; } /** Adds a to-many relationship; the target entity is joined to the PK property of this entity (typically the ID). */ public ToMany addToMany(Entity target, Property targetProperty) { Property[] targetProperties = {targetProperty}; return addToMany(null, target, targetProperties); } /** * Convenience method for {@link Entity#addToMany(Entity, Property)} with a subsequent call to {@link * ToMany#setName(String)}. */ public ToMany addToMany(Entity target, Property targetProperty, String name) { ToMany toMany = addToMany(target, targetProperty); toMany.setName(name); return toMany; } /** * Add a to-many relationship; the target entity is joined using the given target property (of the target entity) * and given source property (of this entity). */ public ToMany addToMany(Property sourceProperty, Entity target, Property targetProperty) { Property[] sourceProperties = {sourceProperty}; Property[] targetProperties = {targetProperty}; return addToMany(sourceProperties, target, targetProperties); } public ToMany addToMany(Property[] sourceProperties, Entity target, Property[] targetProperties) { if (protobuf) { throw new IllegalStateException("Protobuf entities do not support relations, currently"); } ToMany toMany = new ToMany(schema, this, sourceProperties, target, targetProperties); toManyRelations.add(toMany); target.incomingToManyRelations.add(toMany); return toMany; } public ToManyWithJoinEntity addToMany(Entity target, Entity joinEntity, Property id1, Property id2) { ToManyWithJoinEntity toMany = new ToManyWithJoinEntity(schema, this, target, joinEntity, id1, id2); toManyRelations.add(toMany); target.incomingToManyRelations.add(toMany); return toMany; } /** * Adds a to-one relationship to the given target entity using the given given foreign key property (which belongs * to this entity). */ public ToOne addToOne(Entity target, Property fkProperty) { if (protobuf) { throw new IllegalStateException("Protobuf entities do not support realtions, currently"); } Property[] fkProperties = {fkProperty}; ToOne toOne = new ToOne(schema, this, target, fkProperties, true); toOneRelations.add(toOne); return toOne; } /** Convenience for {@link #addToOne(Entity, Property)} with a subsequent call to {@link ToOne#setName(String)}. */ public ToOne addToOne(Entity target, Property fkProperty, String name) { ToOne toOne = addToOne(target, fkProperty); toOne.setName(name); return toOne; } public ToOne addToOneWithoutProperty(String name, Entity target, String fkColumnName) { return addToOneWithoutProperty(name, target, fkColumnName, false, false); } public ToOne addToOneWithoutProperty(String name, Entity target, String fkColumnName, boolean notNull, boolean unique) { PropertyBuilder propertyBuilder = new PropertyBuilder(schema, this, null, name); if (notNull) { propertyBuilder.notNull(); } if (unique) { propertyBuilder.unique(); } propertyBuilder.dbName(fkColumnName); Property column = propertyBuilder.getProperty(); Property[] fkColumns = {column}; ToOne toOne = new ToOne(schema, this, target, fkColumns, false); toOne.setName(name); toOneRelations.add(toOne); return toOne; } protected void addIncomingToMany(ToMany toMany) { incomingToManyRelations.add(toMany); } public ContentProvider addContentProvider() { List<Entity> entities = new ArrayList<>(); entities.add(this); ContentProvider contentProvider = new ContentProvider(schema, entities); contentProviders.add(contentProvider); return contentProvider; } /** Adds a new index to the entity. */ public Entity addIndex(Index index) { indexes.add(index); return this; } public Entity addImport(String additionalImport) { additionalImportsEntity.add(additionalImport); return this; } /** The entity is represented by a protocol buffers object. Requires some special actions like using builders. */ Entity useProtobuf() { protobuf = true; return this; } public boolean isProtobuf() { return protobuf; } public Schema getSchema() { return schema; } public String getDbName() { return dbName; } @Deprecated /** * @deprecated Use setDbName */ public void setTableName(String tableName) { setDbName(tableName); } public void setDbName(String dbName) { this.dbName = dbName; this.nonDefaultDbName = dbName != null; } public String getClassName() { return className; } public List<Property> getProperties() { return properties; } public List<Property> getPropertiesColumns() { return propertiesColumns; } public String getJavaPackage() { return javaPackage; } public void setJavaPackage(String javaPackage) { this.javaPackage = javaPackage; } public String getJavaPackageDao() { return javaPackageDao; } public void setJavaPackageDao(String javaPackageDao) { this.javaPackageDao = javaPackageDao; } public String getClassNameDao() { return classNameDao; } public void setClassNameDao(String classNameDao) { this.classNameDao = classNameDao; } public String getClassNameTest() { return classNameTest; } public void setClassNameTest(String classNameTest) { this.classNameTest = classNameTest; } public String getJavaPackageTest() { return javaPackageTest; } public void setJavaPackageTest(String javaPackageTest) { this.javaPackageTest = javaPackageTest; } /** Internal property used by templates, don't use during entity definition. */ public List<Property> getPropertiesPk() { return propertiesPk; } /** Internal property used by templates, don't use during entity definition. */ public List<Property> getPropertiesNonPk() { return propertiesNonPk; } /** Internal property used by templates, don't use during entity definition. */ public Property getPkProperty() { return pkProperty; } public List<Index> getIndexes() { return indexes; } /** Internal property used by templates, don't use during entity definition. */ public String getPkType() { return pkType; } public boolean isConstructors() { return constructors; } /** Flag to define if constructors should be generated. */ public void setConstructors(boolean constructors) { this.constructors = constructors; } public boolean isSkipGeneration() { return skipGeneration; } /** * Flag if the entity's code generation should be skipped. E.g. if you need to change the class after initial * generation. */ public void setSkipGeneration(boolean skipGeneration) { this.skipGeneration = skipGeneration; } @Deprecated /** * @deprecated Use setSkipCreationInDb */ public void setSkipTableCreation(boolean skipTableCreation) { setSkipCreationInDb(skipTableCreation); } /** Flag if CREATE and DROP TABLE scripts should be skipped in Dao. */ public void setSkipCreationInDb(boolean skipCreationInDb) { this.skipCreationInDb = skipCreationInDb; } public boolean isSkipCreationInDb() { return skipCreationInDb; } public boolean isSkipGenerationTest() { return skipGenerationTest; } public void setSkipGenerationTest(boolean skipGenerationTest) { this.skipGenerationTest = skipGenerationTest; } public List<ToOne> getToOneRelations() { return toOneRelations; } public List<ToManyBase> getToManyRelations() { return toManyRelations; } public List<ToManyBase> getIncomingToManyRelations() { return incomingToManyRelations; } /** * Entities with relations are active, but this method allows to make the entities active even if it does not have * relations. */ public void setActive(Boolean active) { this.active = active; } public Boolean getActive() { return active; } public Boolean getHasKeepSections() { return hasKeepSections; } public Collection<String> getAdditionalImportsEntity() { return additionalImportsEntity; } public Collection<String> getAdditionalImportsDao() { return additionalImportsDao; } public void setHasKeepSections(Boolean hasKeepSections) { this.hasKeepSections = hasKeepSections; } public List<String> getInterfacesToImplement() { return interfacesToImplement; } public List<ContentProvider> getContentProviders() { return contentProviders; } public void implementsInterface(String... interfaces) { for (String interfaceToImplement : interfaces) { if (interfacesToImplement.contains(interfaceToImplement)) { throw new RuntimeException("Interface defined more than once: " + interfaceToImplement); } interfacesToImplement.add(interfaceToImplement); } } public void implementsSerializable() { interfacesToImplement.add("java.io.Serializable"); } public String getSuperclass() { return superclass; } public void setSuperclass(String classToExtend) { this.superclass = classToExtend; } public String getJavaDoc() { return javaDoc; } public void setJavaDoc(String javaDoc) { this.javaDoc = DaoUtil.checkConvertToJavaDoc(javaDoc, ""); } public String getCodeBeforeClass() { return codeBeforeClass; } public void setCodeBeforeClass(String codeBeforeClass) { this.codeBeforeClass = codeBeforeClass; } void init2ndPass() { init2ndPassNamesWithDefaults(); for (int i = 0; i < properties.size(); i++) { Property property = properties.get(i); property.setOrdinal(i); property.init2ndPass(); if (property.isPrimaryKey()) { propertiesPk.add(property); } else { propertiesNonPk.add(property); } } for (int i = 0; i < indexes.size(); i++) { final Index index = indexes.get(i); final int propertiesSize = index.getProperties().size(); if (propertiesSize == 1) { final Property property = index.getProperties().get(0); property.setIndex(index); } else if (propertiesSize > 1) { multiIndexes.add(index); } } if (propertiesPk.size() == 1) { pkProperty = propertiesPk.get(0); pkType = schema.mapToJavaTypeNullable(pkProperty.getPropertyType()); } else { pkType = "Void"; } propertiesColumns = new ArrayList<>(properties); for (ToOne toOne : toOneRelations) { toOne.init2ndPass(); Property[] fkProperties = toOne.getFkProperties(); for (Property fkProperty : fkProperties) { if (!propertiesColumns.contains(fkProperty)) { propertiesColumns.add(fkProperty); } } } for (ToManyBase toMany : toManyRelations) { toMany.init2ndPass(); // Source Properties may not be virtual, so we do not need the following code: // for (Property sourceProperty : toMany.getSourceProperties()) { // if (!propertiesColumns.contains(sourceProperty)) { // propertiesColumns.add(sourceProperty); // } // } } if (active == null) { active = schema.isUseActiveEntitiesByDefault(); } active |= !toOneRelations.isEmpty() || !toManyRelations.isEmpty(); if (hasKeepSections == null) { hasKeepSections = schema.isHasKeepSectionsByDefault(); } init2ndPassIndexNamesWithDefaults(); for (ContentProvider contentProvider : contentProviders) { contentProvider.init2ndPass(); } } protected void init2ndPassNamesWithDefaults() { if (dbName == null) { dbName = DaoUtil.dbName(className); nonDefaultDbName = false; } if (classNameDao == null) { classNameDao = className + "Dao"; } if (classNameTest == null) { classNameTest = className + "Test"; } if (javaPackage == null) { javaPackage = schema.getDefaultJavaPackage(); } if (javaPackageDao == null) { javaPackageDao = schema.getDefaultJavaPackageDao(); if (javaPackageDao == null) { javaPackageDao = javaPackage; } } if (javaPackageTest == null) { javaPackageTest = schema.getDefaultJavaPackageTest(); if (javaPackageTest == null) { javaPackageTest = javaPackage; } } } protected void init2ndPassIndexNamesWithDefaults() { for (int i = 0; i < indexes.size(); i++) { Index index = indexes.get(i); if (index.getName() == null) { String indexName = "IDX_" + getDbName(); List<Property> properties = index.getProperties(); for (int j = 0; j < properties.size(); j++) { Property property = properties.get(j); indexName += "_" + property.getDbName(); if ("DESC".equalsIgnoreCase(index.getPropertiesOrder().get(j))) { indexName += "_DESC"; } } // TODO can this get too long? how to shorten reliably without depending on the order (i) index.setDefaultName(indexName); } } } void init3rdPass() { for (Property property : properties) { property.init3ndPass(); } init3rdPassRelations(); init3rdPassAdditionalImports(); } private void init3rdPassRelations() { Set<String> toOneNames = new HashSet<>(); for (ToOne toOne : toOneRelations) { toOne.init3ndPass(); if (!toOneNames.add(toOne.getName().toLowerCase())) { throw new RuntimeException("Duplicate name for " + toOne); } } Set<String> toManyNames = new HashSet<>(); for (ToManyBase toMany : toManyRelations) { toMany.init3rdPass(); if (toMany instanceof ToMany) { Entity targetEntity = toMany.getTargetEntity(); for (Property targetProperty : ((ToMany) toMany).getTargetProperties()) { if (!targetEntity.propertiesColumns.contains(targetProperty)) { targetEntity.propertiesColumns.add(targetProperty); } } } if (!toManyNames.add(toMany.getName().toLowerCase())) { throw new RuntimeException("Duplicate name for " + toMany); } } } private void init3rdPassAdditionalImports() { if (active && !javaPackage.equals(javaPackageDao)) { additionalImportsEntity.add(javaPackageDao + "." + classNameDao); } for (ToOne toOne : toOneRelations) { Entity targetEntity = toOne.getTargetEntity(); checkAdditionalImportsEntityTargetEntity(targetEntity); // For deep<SUF> checkAdditionalImportsDaoTargetEntity(targetEntity); } for (ToManyBase toMany : toManyRelations) { Entity targetEntity = toMany.getTargetEntity(); checkAdditionalImportsEntityTargetEntity(targetEntity); } for (ToManyBase incomingToMany : incomingToManyRelations) { if (incomingToMany instanceof ToManyWithJoinEntity) { final ToManyWithJoinEntity toManyWithJoinEntity = (ToManyWithJoinEntity) incomingToMany; final Entity joinEntity = toManyWithJoinEntity.getJoinEntity(); checkAdditionalImportsDaoTargetEntity(joinEntity); } } for (Property property : properties) { String customType = property.getCustomType(); if (customType != null) { String pack = DaoUtil.getPackageFromFullyQualified(customType); if (pack != null && !pack.equals(javaPackage)) { additionalImportsEntity.add(customType); } if (pack != null && !pack.equals(javaPackageDao)) { additionalImportsDao.add(customType); } } String converter = property.getConverter(); if (converter != null) { String pack = DaoUtil.getPackageFromFullyQualified(converter); if (pack != null && !pack.equals(javaPackageDao)) { additionalImportsDao.add(converter); } } } } private void checkAdditionalImportsEntityTargetEntity(Entity targetEntity) { if (!targetEntity.getJavaPackage().equals(javaPackage)) { additionalImportsEntity.add(targetEntity.getJavaPackage() + "." + targetEntity.getClassName()); } if (!targetEntity.getJavaPackageDao().equals(javaPackage)) { additionalImportsEntity.add(targetEntity.getJavaPackageDao() + "." + targetEntity.getClassNameDao()); } } private void checkAdditionalImportsDaoTargetEntity(Entity targetEntity) { if (!targetEntity.getJavaPackage().equals(javaPackageDao)) { additionalImportsDao.add(targetEntity.getJavaPackage() + "." + targetEntity.getClassName()); } } public void validatePropertyExists(Property property) { if (!properties.contains(property)) { throw new RuntimeException("Property " + property + " does not exist in " + this); } } public List<Index> getMultiIndexes() { return multiIndexes; } public boolean isNonDefaultDbName() { return nonDefaultDbName; } @Override public String toString() { return "Entity " + className + " (package: " + javaPackage + ")"; } }
32205_4
/* * 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 di.uniba.it.tri.changepoint; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord; import org.apache.commons.math.stat.StatUtils; /** * * @author pierpaolo */ public class MeanShiftCPD { private static final Logger LOG = Logger.getLogger(MeanShiftCPD.class.getName()); private String csvSplitBy = ","; public Map<String, List<Double>> load(String filename) { return load(new File(filename)); } /** * Load time series from file * * @param file Input file * @return HashMap of time series */ public Map<String, List<Double>> load(File file) { //HashMap of time series LOG.info("Load data in memory..."); Map<String, List<Double>> series = new HashMap<>(); try { Reader in = new FileReader(file); Iterable<CSVRecord> records = CSVFormat.DEFAULT.withDelimiter(';').withFirstRecordAsHeader().parse(in); for (CSVRecord record : records) { //String id = record.get(0); String key = record.get(1); List<Double> values = new ArrayList<>(); for (int i = 2; i < record.size(); i++) { values.add(Double.parseDouble(record.get(i))); } // add time series into hashmap series.put(key, values); } in.close(); LOG.info("Data loaded!"); } catch (IOException e) { LOG.log(Level.SEVERE, null, e); } return series; } public String getCsvSplitBy() { return csvSplitBy; } public void setCsvSplitBy(String csvSplitBy) { this.csvSplitBy = csvSplitBy; } /** * Normalize time series * * @param word * @param series * @return */ @Deprecated public List<Double> normalize(String word, Map<String, List<Double>> series) { List<Double> get = series.get(word); if (get == null) { return new ArrayList<>(); } else { double[] arr = new double[get.size()]; for (int i = 0; i < get.size(); i++) { arr[i] = get.get(i); } /* double mean = StatUtils.mean(arr); double variance = StatUtils.variance(arr); List<Double> r = new ArrayList<>(arr.length); for (int i = 0; i < arr.length; i++) { r.add((arr[i] - mean) / variance); }*/ double[] ser_norm = StatUtils.normalize(arr); List<Double> r = new ArrayList<>(arr.length); for (int i = 0; i < arr.length; i++) { r.add(ser_norm[i]); } System.out.println(r); return r; } } /** * Normalize time series * * @param series * @return series normalizzata * @throws java.io.IOException */ public Map<String, List<Double>> normalize2(Map<String, List<Double>> series) throws IOException { LOG.info("Data normalization..."); //Map<String, List<Double>> ser_norm = new HashMap<>(); //Sposto la map in una matrice Iterator it = series.entrySet().iterator(); Map.Entry w = (Map.Entry) it.next(); List<Double> s = (List<Double>) w.getValue(); //it.remove(); //double[][] m = new double[series.size()][s.size()]; double[][] m = new double[series.size()][s.size()]; int i = 0; Iterator ite = series.entrySet().iterator(); while (ite.hasNext()) { Map.Entry word = (Map.Entry) ite.next(); List<Double> t = (List<Double>) word.getValue(); for (int j = 0; j < s.size(); j++) { m[i][j] = t.get(j); } i++; //ite.remove(); // avoids a ConcurrentModificationException } //normalizzo la matrice double[] list_to_norm = new double[series.size()]; for (int col = 0; col < s.size(); col++) { for (int rig = 0; rig < series.size(); rig++) { list_to_norm[rig] = m[rig][col]; } //se la varianza e' zero ricopio solo i valori senza normalizzare if (StatUtils.variance(list_to_norm) != 0) { double[] list_norm = StatUtils.normalize(list_to_norm); for (int rig = 0; rig < series.size(); rig++) { m[rig][col] = list_norm[rig]; } } else { for (int rig = 0; rig < series.size(); rig++) { m[rig][col] = list_to_norm[rig]; } } } //copio la matrice nella map Iterator iter = series.entrySet().iterator(); int riga = 0; //BufferedWriter writer = new BufferedWriter(new FileWriter("/home/rodman/Scrivania/Sperimentazione_TRI/en_stat/serie_normalizzata_ri_pointwise")); while (iter.hasNext()) { List<Double> t = new ArrayList<>(); Map.Entry word = (Map.Entry) iter.next(); //writer.write((String)word.getKey()+" "); for (int col = 0; col < s.size(); col++) { t.add(m[riga][col]); } //writer.write(t.toString()+"\n"); word.setValue(t); riga++; } //writer.close(); LOG.info("Normalization done!"); return series; } /** * Compute mean shift for a normalized time series * * @param s time series * @return mean shift values */ public List<Double> meanShift(List<Double> s) { double sum_pre_j = 0; double sum_post_j = 0; List<Double> meanShift = new ArrayList<>(); for (int j = 0; j < s.size() - 1; j++) { //after j for (int k = j + 1; k < s.size(); k++) { sum_post_j += s.get(k); } sum_post_j = sum_post_j / (s.size() - (j + 1)); //before j for (int k = 0; k <= j; k++) { sum_pre_j += s.get(k); } sum_pre_j = sum_pre_j / (j + 1); meanShift.add(sum_post_j - sum_pre_j); sum_post_j = 0; sum_pre_j = 0; } return meanShift; } /** * Bootstrapping * * @param k * @param num_bs * @return */ public List<List<Double>> bootstrapping(List<Double> k, int num_bs) { List<List<Double>> bs = new ArrayList<>(); for (int i = 0; i < num_bs; i++) { List<Double> temp = new ArrayList<>(k); java.util.Collections.shuffle(temp); bs.add(temp); } return bs; } /** * Compute p-value (rows 8-10 of the algorithm) * * @param meanshift * @param samples * @return */ public List<Double> computePValue(List<Double> meanshift, List<List<Double>> samples) { List<Double> p_values = new ArrayList<>(); List<List<Double>> samples_ms = new ArrayList(); //Compute meanShift of samples for (List s : samples) { samples_ms.add(meanShift(s)); } for (int i = 0; i < meanshift.size(); i++) { int cont = 0; for (int j = 0; j < samples_ms.size(); j++) { if (samples_ms.get(j).get(i) > meanshift.get(i)) { cont++; } } double v = (double) cont / (samples.size()); p_values.add(v); } return p_values; } /** * Change point detection (rows 11-14 of the algorithm) * * @param norm normalized values * @param threshold threshold * @param pValues p values * @return */ public Map<Double, Integer> changePointDetection(List<Double> norm, double threshold, List<Double> pValues) { Map<Double, Integer> cgp = new HashMap<>(); //series indicies that overcome the threshold List<Integer> c = new ArrayList<>(); for (int j = 0; j < norm.size(); j++) { //attenzione ai valori di soglia spesso oltre che piccolissimi sono anche negativi if (norm.get(j) > threshold) { c.add(j); } } //System.out.println(c); if (!c.isEmpty()) { double min = pValues.get(0); int j = 0; for (int i = 1; i < c.size() - 1; i++) { if (pValues.get(c.get(i)) < min) { j = c.get(i); min = pValues.get(c.get(i)); } } cgp.put(min, j); }/* else { cgp.put(Double.NaN, -1); }*/ //gli indici ritornati devono essere incrementati di 1 per coincidere con gli anni //poichè non potremmo mai avere un cambiamento al primo anno return cgp; } public List<ChangePointResults> changePointDetectionList(List<Double> norm, double threshold, List<Double> pValues) { //series indicies that overcome the threshold List<ChangePointResults> l = new ArrayList<>(); for (int j = 0; j < norm.size()-1; j++) { //attenzione ai valori di soglia spesso oltre che piccolissimi sono anche negativi if (norm.get(j) > threshold) { l.add(new ChangePointResults(j, pValues.get(j))); } } Collections.sort(l); return l; } }
pippokill/tri
src/main/java/di/uniba/it/tri/changepoint/MeanShiftCPD.java
3,050
//String id = record.get(0);
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 di.uniba.it.tri.changepoint; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord; import org.apache.commons.math.stat.StatUtils; /** * * @author pierpaolo */ public class MeanShiftCPD { private static final Logger LOG = Logger.getLogger(MeanShiftCPD.class.getName()); private String csvSplitBy = ","; public Map<String, List<Double>> load(String filename) { return load(new File(filename)); } /** * Load time series from file * * @param file Input file * @return HashMap of time series */ public Map<String, List<Double>> load(File file) { //HashMap of time series LOG.info("Load data in memory..."); Map<String, List<Double>> series = new HashMap<>(); try { Reader in = new FileReader(file); Iterable<CSVRecord> records = CSVFormat.DEFAULT.withDelimiter(';').withFirstRecordAsHeader().parse(in); for (CSVRecord record : records) { //String id<SUF> String key = record.get(1); List<Double> values = new ArrayList<>(); for (int i = 2; i < record.size(); i++) { values.add(Double.parseDouble(record.get(i))); } // add time series into hashmap series.put(key, values); } in.close(); LOG.info("Data loaded!"); } catch (IOException e) { LOG.log(Level.SEVERE, null, e); } return series; } public String getCsvSplitBy() { return csvSplitBy; } public void setCsvSplitBy(String csvSplitBy) { this.csvSplitBy = csvSplitBy; } /** * Normalize time series * * @param word * @param series * @return */ @Deprecated public List<Double> normalize(String word, Map<String, List<Double>> series) { List<Double> get = series.get(word); if (get == null) { return new ArrayList<>(); } else { double[] arr = new double[get.size()]; for (int i = 0; i < get.size(); i++) { arr[i] = get.get(i); } /* double mean = StatUtils.mean(arr); double variance = StatUtils.variance(arr); List<Double> r = new ArrayList<>(arr.length); for (int i = 0; i < arr.length; i++) { r.add((arr[i] - mean) / variance); }*/ double[] ser_norm = StatUtils.normalize(arr); List<Double> r = new ArrayList<>(arr.length); for (int i = 0; i < arr.length; i++) { r.add(ser_norm[i]); } System.out.println(r); return r; } } /** * Normalize time series * * @param series * @return series normalizzata * @throws java.io.IOException */ public Map<String, List<Double>> normalize2(Map<String, List<Double>> series) throws IOException { LOG.info("Data normalization..."); //Map<String, List<Double>> ser_norm = new HashMap<>(); //Sposto la map in una matrice Iterator it = series.entrySet().iterator(); Map.Entry w = (Map.Entry) it.next(); List<Double> s = (List<Double>) w.getValue(); //it.remove(); //double[][] m = new double[series.size()][s.size()]; double[][] m = new double[series.size()][s.size()]; int i = 0; Iterator ite = series.entrySet().iterator(); while (ite.hasNext()) { Map.Entry word = (Map.Entry) ite.next(); List<Double> t = (List<Double>) word.getValue(); for (int j = 0; j < s.size(); j++) { m[i][j] = t.get(j); } i++; //ite.remove(); // avoids a ConcurrentModificationException } //normalizzo la matrice double[] list_to_norm = new double[series.size()]; for (int col = 0; col < s.size(); col++) { for (int rig = 0; rig < series.size(); rig++) { list_to_norm[rig] = m[rig][col]; } //se la varianza e' zero ricopio solo i valori senza normalizzare if (StatUtils.variance(list_to_norm) != 0) { double[] list_norm = StatUtils.normalize(list_to_norm); for (int rig = 0; rig < series.size(); rig++) { m[rig][col] = list_norm[rig]; } } else { for (int rig = 0; rig < series.size(); rig++) { m[rig][col] = list_to_norm[rig]; } } } //copio la matrice nella map Iterator iter = series.entrySet().iterator(); int riga = 0; //BufferedWriter writer = new BufferedWriter(new FileWriter("/home/rodman/Scrivania/Sperimentazione_TRI/en_stat/serie_normalizzata_ri_pointwise")); while (iter.hasNext()) { List<Double> t = new ArrayList<>(); Map.Entry word = (Map.Entry) iter.next(); //writer.write((String)word.getKey()+" "); for (int col = 0; col < s.size(); col++) { t.add(m[riga][col]); } //writer.write(t.toString()+"\n"); word.setValue(t); riga++; } //writer.close(); LOG.info("Normalization done!"); return series; } /** * Compute mean shift for a normalized time series * * @param s time series * @return mean shift values */ public List<Double> meanShift(List<Double> s) { double sum_pre_j = 0; double sum_post_j = 0; List<Double> meanShift = new ArrayList<>(); for (int j = 0; j < s.size() - 1; j++) { //after j for (int k = j + 1; k < s.size(); k++) { sum_post_j += s.get(k); } sum_post_j = sum_post_j / (s.size() - (j + 1)); //before j for (int k = 0; k <= j; k++) { sum_pre_j += s.get(k); } sum_pre_j = sum_pre_j / (j + 1); meanShift.add(sum_post_j - sum_pre_j); sum_post_j = 0; sum_pre_j = 0; } return meanShift; } /** * Bootstrapping * * @param k * @param num_bs * @return */ public List<List<Double>> bootstrapping(List<Double> k, int num_bs) { List<List<Double>> bs = new ArrayList<>(); for (int i = 0; i < num_bs; i++) { List<Double> temp = new ArrayList<>(k); java.util.Collections.shuffle(temp); bs.add(temp); } return bs; } /** * Compute p-value (rows 8-10 of the algorithm) * * @param meanshift * @param samples * @return */ public List<Double> computePValue(List<Double> meanshift, List<List<Double>> samples) { List<Double> p_values = new ArrayList<>(); List<List<Double>> samples_ms = new ArrayList(); //Compute meanShift of samples for (List s : samples) { samples_ms.add(meanShift(s)); } for (int i = 0; i < meanshift.size(); i++) { int cont = 0; for (int j = 0; j < samples_ms.size(); j++) { if (samples_ms.get(j).get(i) > meanshift.get(i)) { cont++; } } double v = (double) cont / (samples.size()); p_values.add(v); } return p_values; } /** * Change point detection (rows 11-14 of the algorithm) * * @param norm normalized values * @param threshold threshold * @param pValues p values * @return */ public Map<Double, Integer> changePointDetection(List<Double> norm, double threshold, List<Double> pValues) { Map<Double, Integer> cgp = new HashMap<>(); //series indicies that overcome the threshold List<Integer> c = new ArrayList<>(); for (int j = 0; j < norm.size(); j++) { //attenzione ai valori di soglia spesso oltre che piccolissimi sono anche negativi if (norm.get(j) > threshold) { c.add(j); } } //System.out.println(c); if (!c.isEmpty()) { double min = pValues.get(0); int j = 0; for (int i = 1; i < c.size() - 1; i++) { if (pValues.get(c.get(i)) < min) { j = c.get(i); min = pValues.get(c.get(i)); } } cgp.put(min, j); }/* else { cgp.put(Double.NaN, -1); }*/ //gli indici ritornati devono essere incrementati di 1 per coincidere con gli anni //poichè non potremmo mai avere un cambiamento al primo anno return cgp; } public List<ChangePointResults> changePointDetectionList(List<Double> norm, double threshold, List<Double> pValues) { //series indicies that overcome the threshold List<ChangePointResults> l = new ArrayList<>(); for (int j = 0; j < norm.size()-1; j++) { //attenzione ai valori di soglia spesso oltre che piccolissimi sono anche negativi if (norm.get(j) > threshold) { l.add(new ChangePointResults(j, pValues.get(j))); } } Collections.sort(l); return l; } }
158367_2
package de.gwdg.europeanaqa.spark.graph; import com.jayway.jsonpath.InvalidJsonException; import de.gwdg.europeanaqa.api.abbreviation.EdmDataProviderManager; import de.gwdg.europeanaqa.api.calculator.MultiFieldExtractor; import de.gwdg.europeanaqa.api.model.Format; import de.gwdg.europeanaqa.spark.bean.Graph4PLD; import de.gwdg.europeanaqa.spark.cli.Parameters; import de.gwdg.metadataqa.api.model.pathcache.JsonPathCache; import de.gwdg.metadataqa.api.model.XmlFieldInstance; import de.gwdg.metadataqa.api.schema.EdmFullBeanSchema; import de.gwdg.metadataqa.api.schema.EdmOaiPmhXmlSchema; import de.gwdg.metadataqa.api.schema.Schema; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SaveMode; import org.apache.spark.sql.SparkSession; import java.io.FileNotFoundException; import java.util.*; import java.util.logging.Logger; import static org.apache.spark.sql.functions.col; /** * * @author Péter Király <peter.kiraly at gwdg.de> */ public class GraphByPLDExtractor { private static final Logger logger = Logger.getLogger(GraphByPLDExtractor.class.getCanonicalName()); private static Options options = new Options(); private static final EdmDataProviderManager dataProviderManager = new EdmDataProviderManager(); public static void main(String[] args) throws FileNotFoundException, ParseException { if (args.length < 1) { System.err.println("Please provide a full path to the input files"); System.exit(0); } if (args.length < 2) { System.err.println("Please provide a full path to the output file"); System.exit(0); } Parameters parameters = new Parameters(args); final String inputFileName = parameters.getInputFileName(); final String outputDirName = parameters.getOutputFileName(); final boolean checkSkippableCollections = parameters.getSkipEnrichments(); // (args.length >= 5 && args[4].equals("checkSkippableCollections")); logger.info("arg length: " + args.length); logger.info("Input file is " + inputFileName); logger.info("Output file is " + outputDirName); logger.info("checkSkippableCollections: " + checkSkippableCollections); System.err.println("Input file is " + inputFileName); SparkConf conf = new SparkConf().setAppName("GraphExtractor"); JavaSparkContext context = new JavaSparkContext(conf); SparkSession spark = SparkSession.builder().getOrCreate(); Map<String, String> extractableFields = new LinkedHashMap<>(); Schema qaSchema = null; if (parameters.getFormat() == null || parameters.getFormat().equals(Format.OAI_PMH_XML)) { qaSchema = new EdmOaiPmhXmlSchema(); // extractableFields.put("recordId", "$.identifier"); extractableFields.put("dataProvider", "$.['ore:Aggregation'][0]['edm:dataProvider'][0]"); extractableFields.put("provider", "$.['ore:Aggregation'][0]['edm:provider'][0]"); extractableFields.put("agent", "$.['edm:Agent'][*]['@about']"); extractableFields.put("concept", "$.['skos:Concept'][*]['@about']"); extractableFields.put("place", "$.['edm:Place'][*]['@about']"); extractableFields.put("timespan", "$.['edm:TimeSpan'][*]['@about']"); } else { qaSchema = new EdmFullBeanSchema(); // extractableFields.put("recordId", "$.identifier"); extractableFields.put("dataProvider", "$.['aggregations'][0]['edmDataProvider'][0]"); extractableFields.put("provider", "$.['aggregations'][0]['edmProvider'][0]"); extractableFields.put("agent", "$.['agents'][*]['about']"); extractableFields.put("concept", "$.['concepts'][*]['about']"); extractableFields.put("place", "$.['places'][*]['about']"); extractableFields.put("timespan", "$.['timespans'][*]['about']"); } qaSchema.setExtractableFields(extractableFields); final MultiFieldExtractor fieldExtractor = new MultiFieldExtractor(qaSchema); List<String> entities = Arrays.asList("agent", "concept", "place", "timespan"); List<List<String>> statistics = new ArrayList<>(); JavaRDD<String> inputFile = context.textFile(inputFileName); // statistics.add(Arrays.asList("proxy-nodes", String.valueOf(inputFile.count()))); JavaRDD<Graph4PLD> idsRDD = inputFile .flatMap(jsonString -> { List<Graph4PLD> values = new ArrayList<>(); try { JsonPathCache<? extends XmlFieldInstance> cache = new JsonPathCache<>(jsonString); fieldExtractor.measure(cache); Map<String, ? extends Object> map = fieldExtractor.getResultMap(); // String recordId = ((List<String>) map.get("recordId")).get(0); String dataProvider = extractValue(map, "dataProvider"); String provider = extractValue(map, "provider"); String providerId = (dataProvider != null) ? getDataProviderCode(dataProvider) : (provider != null ? getDataProviderCode(provider) : "0"); for (String entity : entities) { for (String item : (List<String>) map.get(entity)) { values.add(new Graph4PLD(providerId, entity, extractPLD(item))); } } } catch (InvalidJsonException e) { logger.severe(String.format("Invalid JSON in %s: %s. Error message: %s.", inputFileName, jsonString, e.getLocalizedMessage())); } return values.iterator(); } ); Dataset<Row> df = spark.createDataFrame(idsRDD, Graph4PLD.class).distinct(); df.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld-raw"); Dataset<Row> counted = df .groupBy("type", "vocabulary") .count(); counted.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld-counted"); Dataset<Row> ordered = counted .orderBy(col("type"), col("count").desc()); // output every individual entity IDs with count ordered.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld"); } public static String getDataProviderCode(String dataProvider) { String dataProviderCode; if (dataProvider == null) { dataProviderCode = "0"; } else if (dataProviderManager != null) { dataProviderCode = String.valueOf(dataProviderManager.lookup(dataProvider)); } else { dataProviderCode = dataProvider; } return dataProviderCode; } public static String extractPLD(String identifier) { String pld = identifier .replaceAll("https?://", "[pld]") .replaceAll("data.europeana.eu/agent/.*", "data.europeana.eu/agent/") .replaceAll("data.europeana.eu/place/.*", "data.europeana.eu/place/") .replaceAll("data.europeana.eu/concept/.*", "data.europeana.eu/concept/") .replaceAll("rdf.kulturarvvasternorrland.se/.*", "rdf.kulturarvvasternorrland.se") .replaceAll("d-nb.info/gnd/.*", "d-nb.info/gnd/") .replaceAll("^#person-.*", "#person") .replaceAll("^#agent_.*", "#agent") .replaceAll("^RM0001.PEOPLE.*", "RM0001.PEOPLE") .replaceAll("^RM0001.THESAU.*", "RM0001.THESAU") .replaceAll("^person_uuid.*", "person_uuid") .replaceAll("^MTB-PE-.*", "MTB-PE") .replaceAll("^#[0-9a-f]{8}-[0-9a-f]{4}-.*", "#uuid") .replaceAll("^[0-9a-f]{8}-[0-9a-f]{4}-.*", "uuid") .replaceAll("^#ort-dargestellt-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-dargestellt") .replaceAll("^#ort-herstellung-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-herstellung") .replaceAll("^#ort-fund-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-fund") .replaceAll("^HA\\d+/SP", "HA___/SP") .replaceAll("^iid:\\d{7}", "iid") .replaceAll("^iid:\\d{4}", "iid") .replaceAll("^iid:\\d{3}", "iid") .replaceAll("^#5[5-9]\\..*", "#5x.coord") .replaceAll("^#6[0-5]\\..*", "#6x.coord") .replaceAll("^#locationOf:nn.*", "#locationOf:nn") .replaceAll("^#placeOf:.*", "#placeOf") .replaceAll("^Rijksmonumentnummer.*", "Rijksmonumentnummer") .replaceAll("^urn:nbn:nl:ui:13-.*", "urn:nbn:nl:ui:13") .replaceAll("^KIVOTOS_CETI_.*", "KIVOTOS_CETI") .replaceAll("^DMS01-.*", "DMS01") .replaceAll("^DMS02-.*", "DMS02") .replaceAll("^UJAEN_HASSET_.*", "UJAEN_HASSET") .replaceAll("^5500\\d{5}/", "5500") // concept .replaceAll("^urn:Mood:.*", "urn:Mood") .replaceAll("^urn:Instrument:.*", "urn:Instrument") .replaceAll("^DASI:supL.*", "DASI:supL") .replaceAll("^context_\\d{4}.*", "context_yyyy") .replaceAll("^context_AUR_\\d{4}.*", "context_AUR_yyyy") .replaceAll("^context_SLA_OU_\\d{4}.*", "context_SLA_OU_yyyy") .replaceAll("^context_AT-KLA_.*", "context_AT-KLA") .replaceAll("^context_WienStClaraOSCI_.*", "context_WienStClaraOSCI") .replaceAll("^context_A_.*", "context_A") .replaceAll("^context_B_.*", "context_B") .replaceAll("^context_C_.*", "context_C") .replaceAll("^context_D_.*", "context_D") .replaceAll("^context_E_.*", "context_E") .replaceAll("^context_F_.*", "context_F") .replaceAll("^context_G_.*", "context_G") .replaceAll("^context_H_.*", "context_H") .replaceAll("^context_I_.*", "context_I") .replaceAll("^context_K_.*", "context_K") .replaceAll("^context_L_.*", "context_L") .replaceAll("^context_M_.*", "context_M") .replaceAll("^context_O_.*", "context_O") .replaceAll("^context_P_.*", "context_P") .replaceAll("^context_.*", "context") .replaceAll("^#concept-.*", "#concept") // timespan .replaceAll("^#Timesspan_OpenUp!.*", "#Timesspan_OpenUp!") .replaceAll("^#57620.*", "#57620") .replaceAll("^#datierung-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#datierung") .replaceAll("^datierung_uuid=[0-9a-f]{8}-[0-9a-f]{4}-.*", "datierung_uuid") ; if (!pld.contains("data.europeana.eu/agent/") && !pld.contains("data.europeana.eu/place/") && !pld.contains("data.europeana.eu/concept/") && !pld.contains("d-nb.info/gnd/")) { pld = pld.replaceAll("/.+", "/"); } if (pld == null) pld = ""; return pld; } private static String extractValue(Map map, String key) { String value = null; if (map.get(key) != null && !((List<String>) map.get(key)).isEmpty()) value = ((List<String>) map.get(key)).get(0); return value; } private static void help() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -cp [jar] de.gwdg.europeanaqa.spark.CompletenessCount [options]", options); } }
pkiraly/europeana-qa-spark
src/main/java/de/gwdg/europeanaqa/spark/graph/GraphByPLDExtractor.java
3,803
// String recordId = ((List<String>) map.get("recordId")).get(0);
line_comment
nl
package de.gwdg.europeanaqa.spark.graph; import com.jayway.jsonpath.InvalidJsonException; import de.gwdg.europeanaqa.api.abbreviation.EdmDataProviderManager; import de.gwdg.europeanaqa.api.calculator.MultiFieldExtractor; import de.gwdg.europeanaqa.api.model.Format; import de.gwdg.europeanaqa.spark.bean.Graph4PLD; import de.gwdg.europeanaqa.spark.cli.Parameters; import de.gwdg.metadataqa.api.model.pathcache.JsonPathCache; import de.gwdg.metadataqa.api.model.XmlFieldInstance; import de.gwdg.metadataqa.api.schema.EdmFullBeanSchema; import de.gwdg.metadataqa.api.schema.EdmOaiPmhXmlSchema; import de.gwdg.metadataqa.api.schema.Schema; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SaveMode; import org.apache.spark.sql.SparkSession; import java.io.FileNotFoundException; import java.util.*; import java.util.logging.Logger; import static org.apache.spark.sql.functions.col; /** * * @author Péter Király <peter.kiraly at gwdg.de> */ public class GraphByPLDExtractor { private static final Logger logger = Logger.getLogger(GraphByPLDExtractor.class.getCanonicalName()); private static Options options = new Options(); private static final EdmDataProviderManager dataProviderManager = new EdmDataProviderManager(); public static void main(String[] args) throws FileNotFoundException, ParseException { if (args.length < 1) { System.err.println("Please provide a full path to the input files"); System.exit(0); } if (args.length < 2) { System.err.println("Please provide a full path to the output file"); System.exit(0); } Parameters parameters = new Parameters(args); final String inputFileName = parameters.getInputFileName(); final String outputDirName = parameters.getOutputFileName(); final boolean checkSkippableCollections = parameters.getSkipEnrichments(); // (args.length >= 5 && args[4].equals("checkSkippableCollections")); logger.info("arg length: " + args.length); logger.info("Input file is " + inputFileName); logger.info("Output file is " + outputDirName); logger.info("checkSkippableCollections: " + checkSkippableCollections); System.err.println("Input file is " + inputFileName); SparkConf conf = new SparkConf().setAppName("GraphExtractor"); JavaSparkContext context = new JavaSparkContext(conf); SparkSession spark = SparkSession.builder().getOrCreate(); Map<String, String> extractableFields = new LinkedHashMap<>(); Schema qaSchema = null; if (parameters.getFormat() == null || parameters.getFormat().equals(Format.OAI_PMH_XML)) { qaSchema = new EdmOaiPmhXmlSchema(); // extractableFields.put("recordId", "$.identifier"); extractableFields.put("dataProvider", "$.['ore:Aggregation'][0]['edm:dataProvider'][0]"); extractableFields.put("provider", "$.['ore:Aggregation'][0]['edm:provider'][0]"); extractableFields.put("agent", "$.['edm:Agent'][*]['@about']"); extractableFields.put("concept", "$.['skos:Concept'][*]['@about']"); extractableFields.put("place", "$.['edm:Place'][*]['@about']"); extractableFields.put("timespan", "$.['edm:TimeSpan'][*]['@about']"); } else { qaSchema = new EdmFullBeanSchema(); // extractableFields.put("recordId", "$.identifier"); extractableFields.put("dataProvider", "$.['aggregations'][0]['edmDataProvider'][0]"); extractableFields.put("provider", "$.['aggregations'][0]['edmProvider'][0]"); extractableFields.put("agent", "$.['agents'][*]['about']"); extractableFields.put("concept", "$.['concepts'][*]['about']"); extractableFields.put("place", "$.['places'][*]['about']"); extractableFields.put("timespan", "$.['timespans'][*]['about']"); } qaSchema.setExtractableFields(extractableFields); final MultiFieldExtractor fieldExtractor = new MultiFieldExtractor(qaSchema); List<String> entities = Arrays.asList("agent", "concept", "place", "timespan"); List<List<String>> statistics = new ArrayList<>(); JavaRDD<String> inputFile = context.textFile(inputFileName); // statistics.add(Arrays.asList("proxy-nodes", String.valueOf(inputFile.count()))); JavaRDD<Graph4PLD> idsRDD = inputFile .flatMap(jsonString -> { List<Graph4PLD> values = new ArrayList<>(); try { JsonPathCache<? extends XmlFieldInstance> cache = new JsonPathCache<>(jsonString); fieldExtractor.measure(cache); Map<String, ? extends Object> map = fieldExtractor.getResultMap(); // String recordId<SUF> String dataProvider = extractValue(map, "dataProvider"); String provider = extractValue(map, "provider"); String providerId = (dataProvider != null) ? getDataProviderCode(dataProvider) : (provider != null ? getDataProviderCode(provider) : "0"); for (String entity : entities) { for (String item : (List<String>) map.get(entity)) { values.add(new Graph4PLD(providerId, entity, extractPLD(item))); } } } catch (InvalidJsonException e) { logger.severe(String.format("Invalid JSON in %s: %s. Error message: %s.", inputFileName, jsonString, e.getLocalizedMessage())); } return values.iterator(); } ); Dataset<Row> df = spark.createDataFrame(idsRDD, Graph4PLD.class).distinct(); df.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld-raw"); Dataset<Row> counted = df .groupBy("type", "vocabulary") .count(); counted.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld-counted"); Dataset<Row> ordered = counted .orderBy(col("type"), col("count").desc()); // output every individual entity IDs with count ordered.write().mode(SaveMode.Overwrite).csv(outputDirName + "/type-entity-count-pld"); } public static String getDataProviderCode(String dataProvider) { String dataProviderCode; if (dataProvider == null) { dataProviderCode = "0"; } else if (dataProviderManager != null) { dataProviderCode = String.valueOf(dataProviderManager.lookup(dataProvider)); } else { dataProviderCode = dataProvider; } return dataProviderCode; } public static String extractPLD(String identifier) { String pld = identifier .replaceAll("https?://", "[pld]") .replaceAll("data.europeana.eu/agent/.*", "data.europeana.eu/agent/") .replaceAll("data.europeana.eu/place/.*", "data.europeana.eu/place/") .replaceAll("data.europeana.eu/concept/.*", "data.europeana.eu/concept/") .replaceAll("rdf.kulturarvvasternorrland.se/.*", "rdf.kulturarvvasternorrland.se") .replaceAll("d-nb.info/gnd/.*", "d-nb.info/gnd/") .replaceAll("^#person-.*", "#person") .replaceAll("^#agent_.*", "#agent") .replaceAll("^RM0001.PEOPLE.*", "RM0001.PEOPLE") .replaceAll("^RM0001.THESAU.*", "RM0001.THESAU") .replaceAll("^person_uuid.*", "person_uuid") .replaceAll("^MTB-PE-.*", "MTB-PE") .replaceAll("^#[0-9a-f]{8}-[0-9a-f]{4}-.*", "#uuid") .replaceAll("^[0-9a-f]{8}-[0-9a-f]{4}-.*", "uuid") .replaceAll("^#ort-dargestellt-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-dargestellt") .replaceAll("^#ort-herstellung-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-herstellung") .replaceAll("^#ort-fund-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#ort-fund") .replaceAll("^HA\\d+/SP", "HA___/SP") .replaceAll("^iid:\\d{7}", "iid") .replaceAll("^iid:\\d{4}", "iid") .replaceAll("^iid:\\d{3}", "iid") .replaceAll("^#5[5-9]\\..*", "#5x.coord") .replaceAll("^#6[0-5]\\..*", "#6x.coord") .replaceAll("^#locationOf:nn.*", "#locationOf:nn") .replaceAll("^#placeOf:.*", "#placeOf") .replaceAll("^Rijksmonumentnummer.*", "Rijksmonumentnummer") .replaceAll("^urn:nbn:nl:ui:13-.*", "urn:nbn:nl:ui:13") .replaceAll("^KIVOTOS_CETI_.*", "KIVOTOS_CETI") .replaceAll("^DMS01-.*", "DMS01") .replaceAll("^DMS02-.*", "DMS02") .replaceAll("^UJAEN_HASSET_.*", "UJAEN_HASSET") .replaceAll("^5500\\d{5}/", "5500") // concept .replaceAll("^urn:Mood:.*", "urn:Mood") .replaceAll("^urn:Instrument:.*", "urn:Instrument") .replaceAll("^DASI:supL.*", "DASI:supL") .replaceAll("^context_\\d{4}.*", "context_yyyy") .replaceAll("^context_AUR_\\d{4}.*", "context_AUR_yyyy") .replaceAll("^context_SLA_OU_\\d{4}.*", "context_SLA_OU_yyyy") .replaceAll("^context_AT-KLA_.*", "context_AT-KLA") .replaceAll("^context_WienStClaraOSCI_.*", "context_WienStClaraOSCI") .replaceAll("^context_A_.*", "context_A") .replaceAll("^context_B_.*", "context_B") .replaceAll("^context_C_.*", "context_C") .replaceAll("^context_D_.*", "context_D") .replaceAll("^context_E_.*", "context_E") .replaceAll("^context_F_.*", "context_F") .replaceAll("^context_G_.*", "context_G") .replaceAll("^context_H_.*", "context_H") .replaceAll("^context_I_.*", "context_I") .replaceAll("^context_K_.*", "context_K") .replaceAll("^context_L_.*", "context_L") .replaceAll("^context_M_.*", "context_M") .replaceAll("^context_O_.*", "context_O") .replaceAll("^context_P_.*", "context_P") .replaceAll("^context_.*", "context") .replaceAll("^#concept-.*", "#concept") // timespan .replaceAll("^#Timesspan_OpenUp!.*", "#Timesspan_OpenUp!") .replaceAll("^#57620.*", "#57620") .replaceAll("^#datierung-[0-9a-f]{8}-[0-9a-f]{4}-.*", "#datierung") .replaceAll("^datierung_uuid=[0-9a-f]{8}-[0-9a-f]{4}-.*", "datierung_uuid") ; if (!pld.contains("data.europeana.eu/agent/") && !pld.contains("data.europeana.eu/place/") && !pld.contains("data.europeana.eu/concept/") && !pld.contains("d-nb.info/gnd/")) { pld = pld.replaceAll("/.+", "/"); } if (pld == null) pld = ""; return pld; } private static String extractValue(Map map, String key) { String value = null; if (map.get(key) != null && !((List<String>) map.get(key)).isEmpty()) value = ((List<String>) map.get(key)).get(0); return value; } private static void help() { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -cp [jar] de.gwdg.europeanaqa.spark.CompletenessCount [options]", options); } }